### Implement TestEnvironmentSetup for Database Setup Source: https://github.com/xvik/dropwizard-guicey/blob/master/dropwizard-guicey/src/doc/docs/guide/test/junit5/setup-object.md Example of implementing `TestEnvironmentSetup` to start a test database and apply its connection details as configuration overrides for the Dropwizard application. ```java public class TestDbSetup implements TestEnvironmentSetup { @Override public Object setup(TestExtension extension) throws Exception { // pseudo code Db db = DbFactory.startTestDb(); // register required configuration extension .configOverride("database.url", ()-> db.getUrl()) .configOverride("database.user", ()-> db.getUser()) .configOverride("database.password", ()-> db.getPassword); // assuming object implements Closable return db; } } ``` -------------------------------- ### Application Server Start Commands Source: https://github.com/xvik/dropwizard-guicey/blob/master/examples/ext-jdbi3/README.md Shows example commands for starting the Dropwizard application with a specific configuration file. These are pseudo-commands indicating how to run the main application class with server arguments. ```Shell Jdbi3Application server example-config.yml ``` -------------------------------- ### Start Dropwizard Application Source: https://github.com/xvik/dropwizard-guicey/blob/master/examples/ext-gsp/README.md Demonstrates how to start a Dropwizard application using a configuration file. The command `server config.yml` is used to launch the application with the specified configuration. ```YAML server config.yml ``` -------------------------------- ### Java Implementing TestExecutionListener Source: https://github.com/xvik/dropwizard-guicey/blob/master/dropwizard-guicey/src/doc/docs/guide/test/junit5/setup-object.md Demonstrates how a custom setup class can implement `TestExecutionListener` and register itself to receive lifecycle events. The `setup` method is overridden to listen for events, and specific event methods like `started` can be implemented. ```java public class MySetup implements TestEnvironmentSetup, TestExecutionListener { @Override public Object setup(TestExtension extension) throws Exception { extension.listen(this); } @Override public void started(final EventContext context) throws Exception { // something } } ``` -------------------------------- ### Example Guicey Bundle Implementation Source: https://github.com/xvik/dropwizard-guicey/blob/master/dropwizard-guicey/src/doc/docs/guide/bundles.md Provides a practical example of implementing a `GuiceyBundle`. This includes setting up installers, Dropwizard bundles, Guice modules, and accessing Dropwizard's bootstrap and environment configurations within the `initialize` and `run` methods. ```java public class MyFeatureBundle implements GuiceyBundle { @Override public void initialize(GuiceyBootstrap bootstrap) throws Exception { bootstrap .installers(MyFeatureExtensionInstaller.class) // dropwizard bundle usage .dropwizardBundle(new RequiredDwBundle()) .modules(new MyFeatureModule()); // dropwizard bootstrap access bootstrap.bootstrap().addCommand(new MyFeatureCommand()); } @Override public void run(GuiceyEnvironment environment) throws Exception { // configuration access environment .modules(new SpecialModle(environment.configuration().getSomeValue())) .onApplicationStartup(() -> logger.info("Application started!")); // dropwizard environment access environment.environment().setValidator(new MyCustomValudatior()); } } ``` -------------------------------- ### Register TestDbSetup with Lambda Expression Source: https://github.com/xvik/dropwizard-guicey/blob/master/dropwizard-guicey/src/doc/docs/guide/test/junit5/setup-object.md Provides an example of registering a setup object using a lambda expression, allowing inline configuration overrides. ```java .setup(ext -> { Db db = new Db(); ext.configOverride("db.url", ()->db.getUrl()) return db; }) ``` -------------------------------- ### Java: Implement a Dropwizard Managed Object Source: https://github.com/xvik/dropwizard-guicey/blob/master/dropwizard-guicey/src/doc/docs/getting-started.md Creates a custom `Managed` object for Dropwizard, which is automatically discovered and installed by Guicey. The `start()` method is called on application startup, and `stop()` is called on shutdown. This example logs messages during start and stop. ```java import io.dropwizard.lifecycle.Managed; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.inject.Singleton; @Singleton public class SampleBootstrap implements Managed { private final Logger logger = LoggerFactory.getLogger(SampleBootstrap.class); @Override public void start() throws Exception { logger.info("Starting some resource"); } @Override public void stop() throws Exception { logger.info("Shutting down some resource"); } } ``` -------------------------------- ### Dropwizard App Initialization Source: https://github.com/xvik/dropwizard-guicey/blob/master/examples/openapi-client-server/README.md Initializes the Dropwizard application by adding the PetStoreBundle. This bundle configures the OpenAPI client and optionally starts the fake server. ```java @Override public void initialize(Bootstrap bootstrap) { bootstrap.addBundle(GuiceBundle.builder() .bundles(new PetStoreBundle()) .build()); } ``` -------------------------------- ### Implement Async Servlet Source: https://github.com/xvik/dropwizard-guicey/blob/master/dropwizard-guicey/src/doc/docs/installers/servlet.md Provides an example of an asynchronous servlet. This servlet uses `req.startAsync()` to handle requests asynchronously, allowing for non-blocking operations. This is a key feature where Guicey's installer differs from Guice Servlet modules. ```java import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.ServletException; import java.io.IOException; @WebServlet(urlPatterns = "/async", asyncSupported = true) public class AsyncServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { final AsyncContext context = req.startAsync(); context.start(() -> { context.getResponse().getWriter().write("done!"); context.complete(); }); } } ``` -------------------------------- ### Async Filter Example Source: https://github.com/xvik/dropwizard-guicey/blob/master/dropwizard-guicey/src/doc/docs/installers/filter.md Provides an example of an asynchronous filter. This functionality is only supported via the installer and not with the Guice Servlet Module. ```java import jakarta.servlet.annotation.WebFilter; import jakarta.servlet.Filter; import jakarta.servlet.FilterConfig; import jakarta.servlet.ServletException; import jakarta.servlet.ServletRequest; import jakarta.servlet.ServletResponse; import jakarta.servlet.FilterChain; import jakarta.servlet.AsyncContext; import java.io.IOException; @WebFilter(urlPatterns = "/asyncfilter", asyncSupported = true) public class AsyncFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { final AsyncContext context = request.startAsync(); context.start(() -> { context.getResponse().writer.write("done!"); context.complete(); }); } @Override public void destroy() { } } ``` -------------------------------- ### Custom Installer Implementation for EagerSingleton Source: https://github.com/xvik/dropwizard-guicey/blob/master/dropwizard-guicey/src/doc/docs/guide/diagnostic/extensions-report.md This Java code snippet shows an example of implementing a custom installer, specifically for the `EagerSingleton` feature. It demonstrates how to override the `getRecognizableSigns` method to define the signs that this installer recognizes. ```java public class EagerSingletonInstaller implements FeatureInstaller { ... @Override public List getRecognizableSigns() { return Collections.singletonList("@" + EagerSingleton.class.getSimpleName() + " on class"); } } ``` -------------------------------- ### Custom Installer: Reporting Installed Extensions Source: https://github.com/xvik/dropwizard-guicey/blob/master/dropwizard-guicey/src/doc/docs/guide/installers.md This Java code extends the previous example by adding reporting functionality. It uses a `Reporter` to log the class names of installed `ScheduledTask` instances in the `install` method and calls `reporter.report()` in the `report` method. ```java public class ScheduledInstaller implements FeatureInstaller, InstanceInstaller { private final Reporter reporter = new Reporter(ScheduledInstaller.class, "scheduled tasks ="); ... @Override public void install(Environment environment, ScheduledTask instance) { SchedulerFramework.registerTask(instance); // register for reporting reporter.line("(%s)", FeatureUtils.getInstanceClass(instance).getName()); } @Override public void report() { reporter.report(); } } ``` -------------------------------- ### Java: Create a Basic REST Resource Source: https://github.com/xvik/dropwizard-guicey/blob/master/dropwizard-guicey/src/doc/docs/getting-started.md Defines a simple REST resource class with a GET endpoint. This resource is automatically discovered and registered by Guicey when the application starts. It returns a 'ok' response. ```java import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.Response; @Path("/sample") @Produces("application/json") public class SampleResource { @GET @Path("/") public Response ask() { return Response.ok("ok").build(); } } ``` -------------------------------- ### Diagnostic Report Example Source: https://github.com/xvik/dropwizard-guicey/blob/master/examples/core-extensions/README.md An example of the diagnostic report output showing the order of installers and extensions found during application startup, including those found via scanning and Guice bindings. ```Text INSTALLERS and EXTENSIONS in processing order = resource (r.v.d.g.m.i.f.j.ResourceInstaller) MyResource (r.v.d.g.e.rest) MyResourceFromScan (r.v.d.g.e.rest.scan) *SCAN MyResourceFromBinding (r.v.d.g.e.rest) *BINDING APPLICATION ├── extension MyResource (r.v.d.g.e.rest) ├── module AppModule (r.v.d.guice.examples) ├── module GuiceBootstrapModule (r.v.d.guice.module) │ ├── CoreInstallersBundle (r.v.d.g.m.installer) │ ├── installer ResourceInstaller (r.v.d.g.m.i.f.jersey) │ └── WebInstallersBundle (r.v.d.g.m.installer) │ ├── CLASSPATH SCAN │ └── extension MyResourceFromScan (r.v.d.g.e.rest.scan) │ └── GUICE BINDINGS │ └── AppModule (r.v.d.guice.examples) └── extension MyResourceFromBinding (r.v.d.g.e.rest) ``` -------------------------------- ### JUnit 5 Test with Dropwizard Extension Source: https://github.com/xvik/dropwizard-guicey/blob/master/dropwizard-guicey/src/doc/docs/guide/test/junit5/setup.md An example of a JUnit 5 test class that utilizes Dropwizard extensions to start a separate Dropwizard application instance for testing. It shows how to inject a client and perform assertions. ```java @TestGuiceyApp(App.class) @ExtendWith(DropwizardExtensionsSupport.class) public class ClientSupportGuiceyTest { static DropwizardAppExtension app = new DropwizardAppExtension(App.class); @Test void testLimitedClient(ClientSupport client) { Assertions.assertEquals(200, client.target("http://localhost:8080/dummy/") .request().buildGet().invoke().getStatus()); } } ``` -------------------------------- ### Dropwizard 0.9 Guice Bundle Configuration Source: https://github.com/xvik/dropwizard-guicey/wiki/Authentication-integration Demonstrates how to configure the GuiceBundle for Dropwizard 0.9 with automatic installation of installers and extensions like `OAuthDynamicFeature` and `MySecuredResource`. ```java bootstrap.addBundle(GuiceBundle. builder() .installers(JerseyProviderInstaller.class, ResourceInstaller.class) .extensions(OAuthDynamicFeature.class, MySecuredResource.class) .build() ); ``` -------------------------------- ### Enabling Diagnostic Information Source: https://github.com/xvik/dropwizard-guicey/blob/master/dropwizard-guicey/src/doc/docs/getting-started.md Provides code snippets for enabling diagnostic logging in Guicey to help understand configuration, supported installers, and Guice bindings. ```Java GuiceBundle.builder() .printDiagnosticInfo() ... ``` ```Java GuiceBundle.builder() .printAvailableInstallers() ``` ```Java GuiceBundle.builder() .printGuiceBindings() ``` -------------------------------- ### Dropwizard Guicey Installer Order Diagnostic Source: https://github.com/xvik/dropwizard-guicey/wiki/Diagnostic-info Provides an example of the diagnostic output showing the order in which installers are processed. This is crucial for understanding the application's initialization flow and dependency resolution. ```Log INFO [2016-08-22 00:49:33,557] ru.vyarus.dropwizard.guice.module.context.debug.report.DiagnosticReporter: Configuration diagnostic info = INSTALLERS in processing order = lifecycle (r.v.d.g.m.i.f.LifeCycleInstaller) managed (r.v.d.g.m.i.f.ManagedInstaller) jerseyfeature (r.v.d.g.m.i.f.j.JerseyFeatureInstaller) jerseyprovider (r.v.d.g.m.i.f.j.p.JerseyProviderInstaller) resource (r.v.d.g.m.i.f.j.ResourceInstaller) eagersingleton (r.v.d.g.m.i.f.e.EagerSingletonInstaller) healthcheck (r.v.d.g.m.i.f.h.HealthCheckInstaller) task (r.v.d.g.m.i.f.TaskInstaller) plugin (r.v.d.g.m.i.f.plugin.PluginInstaller) webservlet (r.v.d.g.m.i.f.w.WebServletInstaller) webfilter (r.v.d.g.m.i.f.w.WebFilterInstaller) weblistener (r.v.d.g.m.i.f.w.l.WebListenerInstaller) ``` -------------------------------- ### Initialize Dropwizard Application with Hibernate and Guice Source: https://github.com/xvik/dropwizard-guicey/blob/master/examples/integration-hibernate/README.md This method initializes the Dropwizard application by adding the Hibernate bundle and the Guice bundle. The Hibernate bundle is added first to ensure the SessionFactory is initialized before the Guice context starts. ```Java @Override public void initialize(Bootstrap bootstrap) { final HbnBundle hibernate = new HbnBundle(); // register hbn bundle before guice to make sure factory initialized before guice context start bootstrap.addBundle(hibernate); bootstrap.addBundle(GuiceBundle.builder() .enableAutoConfig("ru.vyarus.dropwizard.guice.examples") .modules(new HbnModule(hibernate)) .build()); } ``` -------------------------------- ### Dropwizard Guicey Installer Disabling Example Source: https://github.com/xvik/dropwizard-guicey/wiki/Diagnostic-info Illustrates how disabled installers are represented in the configuration tree output, marked with '-disable'. This helps in understanding which installers are intentionally excluded from the application's setup. ```Text ├── -disable LifeCycleInstaller (r.v.d.g.m.i.feature) ``` -------------------------------- ### Java Installer Interface for Instance Installation Source: https://github.com/xvik/dropwizard-guicey/blob/master/dropwizard-guicey/src/doc/docs/guide/installers.md An interface for installers that handle the installation of extension instances. It takes the Dropwizard `Environment` and the extension instance as parameters, allowing for direct manipulation during the installation process. ```java public interface InstanceInstaller { void install(Environment environment, T instance); } ``` -------------------------------- ### Running Dropwizard Application from Command Line Source: https://github.com/xvik/dropwizard-guicey/blob/master/dropwizard-guicey/src/doc/docs/getting-started.md This command shows how to run a Dropwizard application from the command line. It assumes the main class is `SampleApplication` and the application is being run in 'server' mode. ```bash SampleApplication server ``` -------------------------------- ### Custom Installer: Jersey Extension Registration Source: https://github.com/xvik/dropwizard-guicey/blob/master/dropwizard-guicey/src/doc/docs/guide/installers.md This Java example shows a custom installer for Jersey extensions. It implements `FeatureInstaller` and `JerseyInstaller`, using `JerseyBinding.bindComponent` to register the extension with the provided `AbstractBinder`. ```java public class CustomInstaller implements FeatureInstaller, JerseyInstaller { @Override public boolean matches(final Class type) { return FeatureUtils.is(type, CustomFeature.class); } @Override public void install(final AbstractBinder binder, final Class type) { JerseyBinding.bindComponent(binder, type, false, false); ... } @Override public void report() { ... } } ``` -------------------------------- ### Direct Template Call Example Source: https://github.com/xvik/dropwizard-guicey/blob/master/examples/ext-gsp/README.md Shows how to directly call a FreeMarker template (`.ftl`) served by the application. The URL `http://localhost:8080/foo.ftl` maps to the template file `src/main/resources/com/example/app/foo.ftl`. ```HTTP http://localhost:8080/foo.ftl → src/main/resources/com/example/app/foo.ftl ``` -------------------------------- ### JerseyExtensionsInstalled Event Source: https://github.com/xvik/dropwizard-guicey/blob/master/dropwizard-guicey/src/doc/docs/guide/events.md The JerseyExtensionsInstalled event is triggered after all Jersey installers have finished installing their related extensions. This event is not fired if no extensions were installed or registered. Note that HK2 might not be completely started at this point, including its extensions. ```Java public interface JerseyExtensionsInstalled extends MetaEvent { // Marker interface for the JerseyExtensionsInstalled event } ``` -------------------------------- ### Database Schema Setup Source: https://github.com/xvik/dropwizard-guicey/blob/master/examples/ext-jdbi3/README.md SQL script for setting up the initial database schema, including table creation and constraints. This script is used by Flyway for database migration. ```SQL CREATE TABLE users ( id BIGINT PRIMARY KEY, name VARCHAR(100), version INT ); ``` -------------------------------- ### Register TestDbSetup Manually with TestGuiceyAppExtension (Class) Source: https://github.com/xvik/dropwizard-guicey/blob/master/dropwizard-guicey/src/doc/docs/guide/test/junit5/setup-object.md Shows how to manually register a setup class using the `setup()` method on `TestGuiceyAppExtension`. ```java @RegisterExtension TestGuiceyAppExtension ext = TestGuiceyAppExtension.forApp(App.class) // as class .setup(TestDbSetup.class) ``` -------------------------------- ### Guicey Bundle Configuration for Server Pages Source: https://github.com/xvik/dropwizard-guicey/blob/master/dropwizard-guicey/src/doc/docs/guide/web.md Configures Guicey with the ServerPagesBundle to enable template and resource serving. It registers an application named 'com.example.app' and sets a default index page for the application. ```java GuiceBundle.builder() .bundles( // global views support ServerPagesBundle.builder().build(), // application registration ServerPagesBundle.app("com.example.app", "/com/example/app/", "/") // rest path as index page .indexPage("person/") .build()); ``` -------------------------------- ### Register TestDbSetup Manually with TestGuiceyAppExtension (Instance) Source: https://github.com/xvik/dropwizard-guicey/blob/master/dropwizard-guicey/src/doc/docs/guide/test/junit5/setup-object.md Illustrates registering an instance of a setup class with `TestGuiceyAppExtension`. ```java @RegisterExtension TestGuiceyAppExtension ext = TestGuiceyAppExtension.forApp(App.class) // or as instance .setup(new TestDbSetup()) ``` -------------------------------- ### Simplified TestEnvironmentSetup Setup Method Source: https://github.com/xvik/dropwizard-guicey/blob/master/dropwizard-guicey/src/doc/docs/about/history.md Modifies the `TestEnvironmentSetup#setup()` method to declare `throws Exception`, simplifying its usage by removing the need for explicit exception handling in many cases. ```Java throws Exception ``` -------------------------------- ### Disable Items by Type Source: https://github.com/xvik/dropwizard-guicey/blob/master/dropwizard-guicey/src/doc/docs/guide/disables.md Provides an example of disabling specific items by their exact class types, including bundles, installers, and modules. ```java import static ru.vyarus.dropwizard.guice.module.context.Disables.* .disable(type(MyExtension.class, MyInstaller.class, MyBundle.class, MyModule.class)); ``` -------------------------------- ### Get Enabled Installers Source: https://github.com/xvik/dropwizard-guicey/blob/master/dropwizard-guicey/src/doc/docs/guide/diagnostic/configuration-model.md Retrieves a list of enabled installer classes from the configuration data. It uses shortcut methods provided by GuiceyConfigurationInfo for simplified data querying. ```java public List> getInstallers() { return typesOnly(getData().getItems(ConfigItem.Installer, Filters.enabled())); } ``` -------------------------------- ### Static Resource Call Example Source: https://github.com/xvik/dropwizard-guicey/blob/master/examples/ext-gsp/README.md Illustrates how to access a static resource (e.g., a CSS file) served by the Dropwizard application. The URL `http://localhost:8080/style.css` maps to the file `src/main/resources/com/example/app/style.css`. ```HTTP http://localhost:8080/style.css → src/main/resources/com/example/app/style.css ``` -------------------------------- ### Index Page Call Example Source: https://github.com/xvik/dropwizard-guicey/blob/master/examples/ext-gsp/README.md Shows how the index page is accessed via the root URL `http://localhost:8080/`. This maps to the configured index page, which in this example is `/rest/com.example.app/person/`. ```HTTP http://localhost:8080/ → /rest/com.example.app/person/ ``` -------------------------------- ### Disabling Web Installers Bundle Source: https://github.com/xvik/dropwizard-guicey/blob/master/dropwizard-guicey/src/doc/docs/guide/web.md Provides an example of how to disable all web installers provided by Guicey, which are typically used for automatic registration of servlets, filters, and listeners based on Jakarta annotations. ```java GuiceBundle.builder() .disableBindles(WebInstallersBundle.class) ... ``` -------------------------------- ### Configure Guicey Application Source: https://github.com/xvik/dropwizard-guicey/blob/master/examples/ext-gsp/README.md Configures a Dropwizard application using the Guicey server pages module. It sets the application name, resource path, and defines the index page. The `ServerPagesBundle.app()` method is used for this configuration. ```Java ServerPagesBundle.app("app", "/app/", "/") // rest path as index page .indexPage("person/") .build() ``` -------------------------------- ### Database Migration Commands Source: https://github.com/xvik/dropwizard-guicey/blob/master/examples/ext-jdbi3/README.md Provides example commands for managing the database schema using JDBI3Application. This includes commands for migrating the database to create the schema and for cleaning the database. ```Shell Jdbi3Application db migrate ``` ```Shell Jdbi3Application db clean ``` -------------------------------- ### Service Loader Configuration for Extensions Source: https://github.com/xvik/dropwizard-guicey/blob/master/dropwizard-guicey/src/doc/docs/guide/test/junit5/setup-object.md Illustrates how to enable automatic loading of custom `TestEnvironmentSetup` objects using Java's ServiceLoader mechanism. This involves creating a specific file in `META-INF/services` and listing the fully qualified class names of the extensions. ```text ru.vyarus.dropwizard.guice.test.jupiter.ext.log.RecordedLogsSupport ru.vyarus.dropwizard.guice.test.jupiter.ext.rest.RestStubSupport ru.vyarus.dropwizard.guice.test.jupiter.ext.stub.StubsSupport ru.vyarus.dropwizard.guice.test.jupiter.ext.mock.MocksSupport ``` -------------------------------- ### Add Listener for Command Execution Setup and Cleanup Source: https://github.com/xvik/dropwizard-guicey/blob/master/dropwizard-guicey/src/doc/docs/guide/test/junit5/command.md Shows how to integrate a listener with the command runner for executing setup and cleanup actions. This is useful for managing resources or state during command execution. ```Java TestSupport.buildCommandRunner(App.class) .listen(new CommandRunBuilder.CommandListener<>() { public void setup(String[] args) { /* ... */ } public void cleanup(CommandResult result) { /* ... */ } }) .run("cmd") ``` -------------------------------- ### Service Class Example (Java) Source: https://github.com/xvik/dropwizard-guicey/blob/master/dropwizard-guicey/src/doc/docs/guide/test/junit5/spies.md A simple Java service class with a 'get' method that returns a greeting string based on an integer input. This class is used in the following examples to demonstrate spying. ```java public static class Service { public String get(int id) { return "Hello " + id; } } ``` -------------------------------- ### Java Module with Transitive Install Source: https://github.com/xvik/dropwizard-guicey/blob/master/dropwizard-guicey/src/doc/docs/guide/deduplication.md Illustrates a scenario where a Guice module installs another module transitively. This example highlights a limitation in Guicey's de-duplication for transitive Guice modules, as it only sees modules at the class level. ```Java public class MyModule extends AbstractModule {} public class SomeModule extends AbstractModule { @Override public void configure() { // transitive module install(new MyModule()); } } GuiceBindle.builder() .modules(new OtherModule(), new MyModule()) .uniqueItems(MyModule.class) ``` -------------------------------- ### Install Servlet in Both Contexts Source: https://github.com/xvik/dropwizard-guicey/blob/master/dropwizard-guicey/src/doc/docs/installers/servlet.md Shows how to register a servlet in both the main application context and the admin context simultaneously by using the @AdminContext annotation with `andMain = true`. ```java import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import ru.vyarus.dropwizard.guice.module.installer.feature.AdminContext; @AdminContext(andMain = true) @WebServlet("/mapped") public class MyServlet extends HttpServlet { ... } ``` -------------------------------- ### Guicey EventBus Bundle Installation (Java) Source: https://github.com/xvik/dropwizard-guicey/blob/master/examples/ext-eventbus/README.md This snippet shows how to install the EventBusBundle provided by guicey-eventbus into a Dropwizard application using GuiceBundle.builder(). It enables automatic registration of event listeners and binding of the event bus. ```java GuiceBundle.builder() .bundles(new EventBusBundle()) ``` -------------------------------- ### Print Available Installers Source: https://github.com/xvik/dropwizard-guicey/blob/master/dropwizard-guicey/src/doc/docs/guide/diagnostic/diagnostic-tools.md Prints a list of available installers, aiding in the understanding of supported extensions within the application. ```Java .printAvailableInstallers() ``` -------------------------------- ### Guicey Bundle Installation Source: https://github.com/xvik/dropwizard-guicey/blob/master/guicey-server-pages/README.md This Java code demonstrates how to install the ServerPagesBundle using GuiceBundle.builder(). It's crucial to install this global bundle to enable Guicey Server Pages functionality and configure Dropwizard Views. ```java GuiceBundle.builder() .bundles(ServerPagesBundle.builder().build()); ``` -------------------------------- ### Initialize and Use RestClient Source: https://github.com/xvik/dropwizard-guicey/blob/master/dropwizard-guicey/src/doc/docs/guide/test/general/rest.md Provides examples of initializing the RestClient from a RestStubsRunner and demonstrates basic GET requests. ```Java RestClient rest = restHook.getRestClient(); ``` -------------------------------- ### Path Combination Example Source: https://github.com/xvik/dropwizard-guicey/blob/master/dropwizard-guicey/src/doc/docs/guide/test/general/client.md Illustrates how `ClientSupport` automatically combines multiple string arguments into a correct URL path, simplifying path construction for requests. ```Groovy client.targetRest("some", "other/", "/part") ``` -------------------------------- ### Run Application Startup Command Source: https://github.com/xvik/dropwizard-guicey/blob/master/dropwizard-guicey/src/doc/docs/guide/test/general/startup.md Demonstrates how to use the Command Runner to execute the 'server' command for application startup tests. This method is useful for verifying that the application starts correctly or fails as expected. ```java CommandResult result = TestSupport.buildCommandRunner(App.class) .run("server") ``` -------------------------------- ### Direct Application Execution vs. Command Runner Source: https://github.com/xvik/dropwizard-guicey/blob/master/dropwizard-guicey/src/doc/docs/guide/test/general/startup.md Illustrates the difference between running an application command directly and using the Command Runner. Direct execution can lead to `System.exit(1)` if an exception occurs during the run phase, whereas the Command Runner isolates command execution. ```java public abstract class Application { ... protected void onFatalError(Throwable t) { System.exit(1); } } ``` -------------------------------- ### Define a Service Class (Java) Source: https://github.com/xvik/dropwizard-guicey/blob/master/dropwizard-guicey/src/doc/docs/guide/test/general/spies.md A simple Java class representing a service with a 'get' method, used as an example for spying. ```java public static class Service { public String get(int id) { return "Hello " + id; } } ``` -------------------------------- ### Register Dropwizard Bundle with Guicey Source: https://github.com/xvik/dropwizard-guicey/blob/master/dropwizard-guicey/src/doc/docs/getting-started.md Demonstrates how to implement a GuiceyBundle and register a standard Dropwizard Bundle within its initialize method using the bootstrap object. ```java public class MyBundle implements GuiceyBundle { default void initialize(GuiceyBootstrap bootstrap) throws Exception { bootstrap.dropwizardBundles(new MyDropeizardBundle()); } } ``` -------------------------------- ### ApplicationRun Event Source: https://github.com/xvik/dropwizard-guicey/blob/master/dropwizard-guicey/src/doc/docs/guide/events.md The ApplicationRun event is triggered when the Guice injector has started, extensions are installed (excluding Jersey extensions), and all Guice singletons are initialized. Injection into registered commands is performed at this stage, which is important if a custom command runs the application. This event occurs just before the Application.run method and is an ideal point for installing Jersey and Jetty listeners. ```Java public interface ApplicationRun extends MetaEvent { // Marker interface for the ApplicationRun event } ``` -------------------------------- ### Install Dropwizard Managed Objects with Guicey Source: https://github.com/xvik/dropwizard-guicey/blob/master/dropwizard-guicey/src/doc/docs/installers/managed.md This snippet demonstrates how to implement Dropwizard's 'Managed' interface within a Guice bean. The ManagedInstallerBundle automatically detects and registers these classes, allowing for custom start and stop logic for your services. The '@Order' annotation can be used to control the startup and shutdown sequence. ```java import io.dropwizard.lifecycle.Managed; public class MyService implements Managed { @Override public void start() throws Exception { // Service startup logic } @Override public void stop() throws Exception { // Service shutdown logic } } // Example with ordering: import ru.vyarus.dropwizard.guice.core.order.Order; @Order(10) public class MyOrderedService implements Managed { // ... start() and stop() methods ... } ``` -------------------------------- ### Run Application Startup Command (Shortcut) Source: https://github.com/xvik/dropwizard-guicey/blob/master/dropwizard-guicey/src/doc/docs/guide/test/general/startup.md Provides a shortcut method to run the application startup command using the Command Runner. This simplifies the process of testing application startup scenarios. ```java CommandResult result = TestSupport.buildCommandRunner(App.class) .runApp() ``` -------------------------------- ### Extension Registration via Guice Bindings Source: https://github.com/xvik/dropwizard-guicey/blob/master/dropwizard-guicey/src/doc/docs/getting-started.md Demonstrates how Guicey automatically recognizes extensions declared through Guice bindings within an AbstractModule. This method simplifies registration by leveraging existing Guice configurations. ```Java bootstrap.addBundle(GuiceBundle.builder() .modules(new SampleModule()) .build()); public class SampleModule extends AbstractModule { @Override protected void configure() { bind(SampleResource.class).in(Singleton.class); bind(SampleBootstrap.class); bind(CustomHeaderFilter.class); } } ``` -------------------------------- ### PetStore API Guice Module Source: https://github.com/xvik/dropwizard-guicey/blob/master/examples/openapi-client-server/README.md Provides Guice bindings for the generated PetStore API client interfaces. It configures the ApiClient with the base path and debugging options, then binds instances of PetApi, StoreApi, and UserApi. ```java public class PetStoreApiModule extends DropwizardAwareModule { @Override protected void configure() { ApiClient apiClient = new ApiClient(); apiClient.setBasePath(configuration().getPetStoreUrl()); // optional apiClient.setDebugging(true); bind(ApiClient.class).toInstance(apiClient); bind(PetApi.class).toInstance(new PetApi(apiClient)); bind(StoreApi.class).toInstance(new StoreApi(apiClient)); bind(UserApi.class).toInstance(new UserApi(apiClient)); } } ``` -------------------------------- ### Asserting HTTP Response Source: https://github.com/xvik/dropwizard-guicey/blob/master/dropwizard-guicey/src/doc/docs/guide/test/general/client.md Provides an example of making a GET request using `ClientSupport` and asserting the status code and response body. ```Java Response res = client.targetRest("some").request().buildGet().invoke() Assertions.assertEquals(200, res.getStatus()) Assertions.assertEquals("response text", res.readEntity(String)) ``` -------------------------------- ### Shortcut for Application Start Detection Source: https://github.com/xvik/dropwizard-guicey/blob/master/dropwizard-guicey/src/doc/docs/about/history.md Provides a shortcut method `isApplicationStartedForClass()` in `TestEnvironmentSetup` to simplify detecting the application's start status for `beforeAll`/`beforeEach` extension lifecycle methods. ```Java isApplicationStartedForClass() ``` -------------------------------- ### Implement ModelProcessor in Java Source: https://github.com/xvik/dropwizard-guicey/blob/master/dropwizard-guicey/src/doc/docs/installers/jersey-ext.md Provides an example of implementing Jersey's ModelProcessor to customize resource models. This allows for processing resource models and sub-resources. ```java public class MyModelProcessor implements ModelProcessor { @Override public ResourceModel processResourceModel(ResourceModel resourceModel, Configuration configuration) { return resourceModel; } @Override public ResourceModel processSubResource(ResourceModel subResourceModel, Configuration configuration) { return subResourceModel; } } ``` -------------------------------- ### Guicey Extension Installation with Guice Bindings Source: https://github.com/xvik/dropwizard-guicey/blob/master/dropwizard-guicey/src/doc/docs/concepts.md Shows how to configure Guicey to recognize and install extensions by binding them in Guice modules. ```Java public class MyModule extends AbstarctModule { @Override protected void configure() { bind(MyResource.class); } } GuiceBundle.builder() .modules(new MyModule()) .build() ``` -------------------------------- ### Enable Debugging via Setup Object Source: https://github.com/xvik/dropwizard-guicey/blob/master/dropwizard-guicey/src/doc/docs/guide/test/junit5/debug.md Demonstrates how to enable debug mode programmatically within a setup object using the ext.debug() method. ```java @EnableSetup static TestEnvironmentSetup db = ext -> { ext.debug(); }; ``` -------------------------------- ### Java InjectionResolver for Custom Annotations Source: https://github.com/xvik/dropwizard-guicey/blob/master/dropwizard-guicey/src/doc/docs/installers/jersey-ext.md Shows how to implement `org.glassfish.hk2.api.InjectionResolver` in Java. This example `MyObjInjectionResolver` resolves custom annotations (`MyObjAnn`) and provides instances of `MyObj`. ```java class MyObjInjectionResolver implements InjectionResolver { @Override public Object resolve(Injectee injectee) { return new MyObj(); } @Override public Class getAnnotation() { return MyObjAnn.class; } @Override public boolean isConstructorParameterIndicator() { return false; } @Override public boolean isMethodParameterIndicator() { return true; } } ``` -------------------------------- ### Java ExceptionMapper for RuntimeException Source: https://github.com/xvik/dropwizard-guicey/blob/master/dropwizard-guicey/src/doc/docs/installers/jersey-ext.md Provides an example of implementing `jakarta.ws.rs.ext.ExceptionMapper` in Java to handle `RuntimeException`. This mapper logs the exception and returns a `BAD_REQUEST` response with the exception message. ```java public class DummyExceptionMapper implements ExceptionMapper { private final Logger logger = LoggerFactory.getLogger(DummyExceptionMapper.class); @Override public Response toResponse(RuntimeException e) { logger.debug("Problem while executing", e); return Response.status(Response.Status.BAD_REQUEST) .type(MediaType.TEXT_PLAIN) .entity(e.getMessage()) .build(); } } ``` -------------------------------- ### Java Extension Registration Example Source: https://github.com/xvik/dropwizard-guicey/blob/master/dropwizard-guicey/src/doc/docs/guide/test/overview.md Illustrates how to manually register an extension using GuiceBundle.builder() in Java. This method allows Guicey to control the installation of the extension, enabling it to be disabled later if needed. ```java GuiceBundle.builder() .extensions(MyExceptionMapper.class) ... ``` -------------------------------- ### Java Function for Auth Objects Source: https://github.com/xvik/dropwizard-guicey/blob/master/dropwizard-guicey/src/doc/docs/installers/jersey-ext.md Shows how to use `Function` as a replacement for factories when providing authentication objects. This example defines an `AuthFactory` that returns a `User` object. ```java @Provider class AuthFactory implements Function { @Override public User apply(ContainerRequest containerRequest) { return new User(); } } ``` -------------------------------- ### Initialize Guicey JDBI3 Bundle Source: https://github.com/xvik/dropwizard-guicey/blob/master/dropwizard-guicey/src/doc/docs/examples/jdbi3.md Demonstrates how to initialize the Guicey JDBI3 bundle, providing the database configuration and optionally including an H2DatabasePlugin. ```java GuiceBundle.builder() .bundles(JdbiBundle.forDatabase((conf, env) -> conf.getDatabase())) .withPlugins(new H2DatabasePlugin())) ``` -------------------------------- ### Add Custom Configuration Block with .with() Source: https://github.com/xvik/dropwizard-guicey/blob/master/dropwizard-guicey/src/doc/docs/guide/test/junit5/setup-object.md Shows how to use the `.with()` method to add custom configuration logic or overrides within an extension declaration. ```java @RegisterExtension static TestGuiceyAppExtension ext = TestGuiceyAppExtension.forApp(..) ... .with(builder -> { if (...) { builder.configOverrides("foo.bar", 12); } }) ``` -------------------------------- ### Java Supplier Implementation Source: https://github.com/xvik/dropwizard-guicey/blob/master/dropwizard-guicey/src/doc/docs/installers/jersey-ext.md Demonstrates how to implement `java.util.function.Supplier` in Java. This is useful for providing instances of a specific type, such as `MyModel` in this example. It replaces HK2's `Factory` interface. ```java public class MySupplier implements Supplier { @Override public MyModel get() { ... } } ``` -------------------------------- ### Dropwizard 0.9 OAuth Authentication Setup Source: https://github.com/xvik/dropwizard-guicey/wiki/Authentication-integration Configures OAuth authentication for Dropwizard 0.9 using Guice. It registers `OAuthDynamicFeature` with custom `OAuthAuthenticator` and `OAuthAuthorizer`, and sets up `RolesAllowedDynamicFeature` and `AuthValueFactoryProvider`. ```java @Provider class OAuthDynamicFeature extends AuthDynamicFeature { @Inject OAuthDynamicFeature(OAuthAuthenticator authenticator, OAuthAuthorizer authorizer, Environment environment) { super(new OAuthCredentialAuthFilter.Builder() .setAuthenticator(authenticator) .setAuthorizer(authorizer) .setPrefix("Bearer") .buildAuthFilter()) environment.jersey().register(RolesDynamicFeature.class) environment.jersey().register(new AuthValueFactoryProvider.Binder(User.class)) } // may be external class (internal for simplicity) @Singleton public static class OAuthAuthenticator implements Authenticator { @Override Optional authenticate(String credentials) throws AuthenticationException { return Optional.fromNullable(credentials == "valid" ? new User(name: "valid") : null) } } // may be external class (internal for simplicity) @Singleton public static class OAuthAuthorizer implements Authorizer { @Override public boolean authorize(User user, String role) { return user.getName().equals("good-guy") && role.equals("ADMIN"); } } } ``` -------------------------------- ### Optimize Dropwizard Guicey Startup Source: https://github.com/xvik/dropwizard-guicey/blob/master/dropwizard-guicey/src/doc/docs/guide/diagnostic/configuration-report.md This snippet provides VM options to potentially improve Dropwizard Guicey application startup times during development. It suggests using `-XX:TieredStopAtLevel=1 -noverify` for a faster initialization process. ```java -XX:TieredStopAtLevel=1 -noverify ``` -------------------------------- ### Implement Jakarta ContainerRequestFilter in Java Source: https://github.com/xvik/dropwizard-guicey/blob/master/dropwizard-guicey/src/doc/docs/installers/jersey-ext.md Provides an example of implementing the jakarta.ws.rs.container.ContainerRequestFilter interface to intercept and modify incoming JAX-RS requests. This is commonly used for authentication, authorization, or request preprocessing. ```java public class MyContainerRequestFilter implements ContainerRequestFilter { @Override public void filter(ContainerRequestContext requestContext) throws IOException { } } ``` -------------------------------- ### Setup Spock 1 Source: https://github.com/xvik/dropwizard-guicey/blob/master/dropwizard-guicey/src/doc/docs/guide/test/spock.md This is the basic setup for Spock 1 testing with Dropwizard Guicey. It requires the `guicey-test-spock` dependency, assuming a Bill of Materials (BOM) is used for version management. ```groovy testImplementation 'ru.vyarus.guicey:guicey-test-spock' ``` -------------------------------- ### Implement Custom Health Check Source: https://github.com/xvik/dropwizard-guicey/blob/master/dropwizard-guicey/src/doc/docs/installers/healthcheck.md Example of a custom health check class extending `NamedHealthCheck`. It injects a service and implements the `check()` and `getName()` methods to define the health status and name. ```java public class MyHealthCheck extends NamedHealthCheck { @Inject private MyService service; @Override protected Result check() throws Exception { if (service.isOk()) { return Result.healthy(); } else { return Result.unhealthy("Service is not ok"); } } @Override public String getName() { return "my-service"; } } ``` -------------------------------- ### Example Service for Bean Tracking Source: https://github.com/xvik/dropwizard-guicey/blob/master/dropwizard-guicey/src/doc/docs/guide/test/junit5/tracks.md A simple Java service class with a 'get' method that takes an integer and returns a string. This service will be used to demonstrate bean tracking in tests. ```Java public static class Service { public String get(int id) { return "Hello " + id; } } ``` -------------------------------- ### Configuration-Aware Module Registration Source: https://github.com/xvik/dropwizard-guicey/blob/master/dropwizard-guicey/src/doc/docs/getting-started.md Shows how to register a Guice module that requires access to Dropwizard's Configuration or Environment objects during the run phase. This is achieved using the `whenConfigurationReady` callback. ```Java bootstrap.addBundle(GuiceBundle.builder() ... .whenConfigurationReady(env -> { env.modules(new ConfAwareModule(env.configuration().getSomething())) }) .modules(new SampleModule()) .build()); ``` -------------------------------- ### Java TestExecutionListener Interface Source: https://github.com/xvik/dropwizard-guicey/blob/master/dropwizard-guicey/src/doc/docs/guide/test/junit5/setup-object.md Defines the interface for listening to test lifecycle events. Implementations can react to various stages of test execution, such as starting, beforeAll, beforeEach, afterEach, afterAll, and stopping. ```java public interface TestExecutionListener { default void starting(final EventContext context) throws Exception {} default void started(final EventContext context) throws Exception {} default void beforeAll(final EventContext context) throws Exception {} default void beforeEach(final EventContext context) throws Exception {} default void afterEach(final EventContext context) throws Exception {} default void afterAll(final EventContext context) throws Exception {} default void stopping(final EventContext context) throws Exception {} default void stopped(final EventContext context) throws Exception {} } ``` -------------------------------- ### Accessing Guice Beans with DropwizardAppRule - Java Source: https://github.com/xvik/dropwizard-guicey/blob/master/dropwizard-guicey/src/doc/docs/guide/test/junit4.md Illustrates how to access Guice-managed beans when using DropwizardAppRule, which starts the full Dropwizard application. It shows using InjectorLookup to get the injector and then retrieve beans. ```Java InjectorLookup.getInjector(RULE.getApplication()).getBean(MyService.class); ``` ```Java public class MyTest { @ClassRule static DropwizardAppRule RULE = ... @Inject MyService service; @Inject MyOtherService otherService; @Before public void setUp() { InjectorLookup.get(RULE.getApplication()).get().injectMemebers(this) } } ``` -------------------------------- ### Java Lambda-based Event Handling Source: https://github.com/xvik/dropwizard-guicey/blob/master/dropwizard-guicey/src/doc/docs/guide/test/junit5/setup-object.md Shows a concise way to handle test lifecycle events using lambda expressions directly within the test class. This approach simplifies event registration by providing methods like `onApplicationStarting`, `onApplicationStart`, etc. ```java public class Test { @EnableSetup static TestDbSetup db = ext -> ext .onApplicationStarting(event -> ...) .onApplicationStart(event -> ...) .onBeforeAll(event -> ...) .onBeforeEach(event -> ...) .onAfterEach(event -> ...) .onAfterAll(event -> ...) .onApplicationStopping(event -> ...) .onApplicationStop(event -> ...) } ``` -------------------------------- ### Implement Jakarta MessageBodyWriter in Java Source: https://github.com/xvik/dropwizard-guicey/blob/master/dropwizard-guicey/src/doc/docs/installers/jersey-ext.md Provides an example of implementing the jakarta.ws.rs.ext.MessageBodyWriter interface for custom serialization of response entities. This allows control over how Java objects are converted into specific media types for responses. ```java public class TypeMessageBodyWriter implements MessageBodyWriter { @Override public boolean isWriteable(Class type, java.lang.reflect.Type genericType, Annotation[] annotations, MediaType mediaType) { return false; } @Override public long getSize(Type type, Class type2, java.lang.reflect.Type genericType, Annotation[] annotations, MediaType mediaType) { return 0; } @Override public void writeTo(Type type, Class type2, java.lang.reflect.Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { } public static class Type {} } ``` -------------------------------- ### Basic DropwizardTestSupport Lifecycle Source: https://github.com/xvik/dropwizard-guicey/blob/master/dropwizard-guicey/src/doc/docs/guide/test/general/run.md Illustrates the fundamental usage of a `DropwizardTestSupport` object, showing the essential `before()` and `after()` calls to manage the test environment's lifecycle. ```java support.before() // test support.after() ``` -------------------------------- ### Disabling Default Extensions Source: https://github.com/xvik/dropwizard-guicey/blob/master/dropwizard-guicey/src/doc/docs/guide/test/junit5/setup-object.md Provides an example of how to disable the automatic loading of default extensions, including those loaded via service loaders. This is achieved by setting the `useDefaultExtensions` attribute to `false` in the `@TestGuiceyApp` annotation. ```java @TestGuiceyApp(.., useDefaultExtensions = false) ```