GithubHelp home page GithubHelp logo

dropwizard-guice's Introduction

Dropwizard-Guice

A simple DropWizard extension for integrating Guice via a bundle. It optionally uses classpath scanning courtesy of the Reflections project to discover resources and more to install into the dropwizard environment upon service start.

NOTE:

This library has been replaced by dropwizard-guicier, so we don't recommend using it for new development.

Usage

    <dependencies>
        <dependency>
            <groupId>com.hubspot.dropwizard</groupId>
            <artifactId>dropwizard-guice</artifactId>
            <version>${current.version}</version>
        </dependency>
    </dependencies>

A list of available versions can be found at https://github.com/HubSpot/dropwizard-guice/releases

Simply install a new instance of the bundle during your service initialization

public class HelloWorldApplication extends Application<HelloWorldConfiguration> {

  private GuiceBundle<HelloWorldConfiguration> guiceBundle;

  public static void main(String[] args) throws Exception {
    new HelloWorldApplication().run(args);
  }

  @Override
  public void initialize(Bootstrap<HelloWorldConfiguration> bootstrap) {

    guiceBundle = GuiceBundle.<HelloWorldConfiguration>newBuilder()
      .addModule(new HelloWorldModule())
      .setConfigClass(HelloWorldConfiguration.class)
      .build();

    bootstrap.addBundle(guiceBundle);
  }

  @Override
  public String getName() {
    return "hello-world";
  }

  @Override
  public void run(HelloWorldConfiguration helloWorldConfiguration, Environment environment) throws Exception {
    environment.jersey().register(HelloWorldResource.class);
    environment.lifecycle().manage(guiceBundle.getInjector().getInstance(TemplateHealthCheck.class));
  }
}

Auto Configuration

You can enable auto configuration via package scanning.

public class HelloWorldApplication extends Application<HelloWorldConfiguration> {

  public static void main(String[] args) throws Exception {
    new HelloWorldApplication().run(args);
  }

  @Override
  public void initialize(Bootstrap<HelloWorldConfiguration> bootstrap) {

    GuiceBundle<HelloWorldConfiguration> guiceBundle = GuiceBundle.<HelloWorldConfiguration>newBuilder()
      .addModule(new HelloWorldModule())
      .enableAutoConfig(getClass().getPackage().getName())
      .setConfigClass(HelloWorldConfiguration.class)
      .build();

    bootstrap.addBundle(guiceBundle);
  }

  @Override
  public String getName() {
    return "hello-world";
  }

  @Override
  public void run(HelloWorldConfiguration helloWorldConfiguration, Environment environment) throws Exception {
    // now you don't need to add resources, tasks, healthchecks or providers
    // you must have your health checks inherit from InjectableHealthCheck in order for them to be injected
  }
}

Dropwizard Task requires a TaskName. Therefore when Auto Configuring a Task, you need to inject in the TaskName:

    @Singleton
    public class MyTask extends Task {

        @Inject
        protected MyTask(@Named("MyTaskName") String name) {
            super(name);
        }

        @Override
        public void execute(ImmutableMultimap<String, String> immutableMultimap, PrintWriter printWriter) throws Exception {

        }
    }

And bind the TaskName in your module:

bindConstant().annotatedWith(Names.named("MyTaskName")).to("my awesome task");

See the test cases: InjectedTask and TestModule for more details.

Environment and Configuration

If you are having trouble accessing your Configuration or Environment inside a Guice Module, you could try using a provider.

public class HelloWorldModule extends AbstractModule {

  @Override
  protected void configure() {
    // anything you'd like to configure
  }

  @Provides
  public SomePool providesSomethingThatNeedsConfiguration(HelloWorldConfiguration configuration) {
    return new SomePool(configuration.getPoolName());
  }

  @Provides
  public SomeManager providesSomenthingThatNeedsEnvironment(Environment env) {
    return new SomeManager(env.getSomethingFromHere()));
  }
}

Injector Factory

You can also replace the default Guice Injector by implementing your own InjectorFactory. For example if you want to use Governator, you can set the following InjectorFactory (using Java 8 Lambda) when initializing the GuiceBundle:

@Override
public void initialize(Bootstrap<HelloWorldConfiguration> bootstrap) {

  GuiceBundle<HelloWorldConfiguration> guiceBundle = GuiceBundle.<HelloWorldConfiguration>newBuilder()
    .addModule(new HelloWorldModule())
    .enableAutoConfig(getClass().getPackage().getName())
    .setConfigClass(HelloWorldConfiguration.class)
    .setInjectorFactory((stage, modules) -> LifecycleInjector.builder()
        .inStage(stage)
        .withModules(modules)
        .build()
        .createInjector()))
    .build();

 bootstrap.addBundle(guiceBundle);
}

Testing

As of Dropwizard 0.8.x, when writing Integration Tests using DropwizardAppRule, you need to reset jersey2-guice by running:

JerseyGuiceUtils.reset();

Examples

Please fork an example project if you'd like to get going right away.

You may also find more updated and comprehensive examples in the test cases.

Enjoy!

dropwizard-guice's People

Contributors

a-h avatar andrew-m avatar andybergon avatar axiak avatar bramp avatar carterkozak avatar dmorgantini avatar eliast avatar hs-jenkins-bot avatar igorkatkov avatar jhaber avatar medvedev avatar mlk avatar mrserverless avatar oillio avatar rich4j avatar vvondra avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

dropwizard-guice's Issues

Properly reset ServiceLocatorGenerator / RuntimeDelegate in a test environment

I had problems using the DropwizardAppRule together with a legacy embedded Jersey Server not using Dropwizard, running in the same JVM for our tests.

The dropwizard-guice module overrides the ServiceLocatorGenerator and RuntimeDelegate in BootstrapUtils.install without ever resetting them, breaking our legacy Jersey server when it wants to boot up (saying that the ServiceLocatorImpl "has been shut down").

This can be fixed manually by enhancing the DropwizardAppRule with

BootstrapUtils.reset();

after the Rule has shutdown.

Unfortunately I couldn't find any references to BootstrapUtils.reset() in the dropwizard-guice code. Maybe there's a way to call that generally when the Jersey server is shutting down or at least in the test environment enhancing the DropwizardAppRule (prolly by providing an own test-rule).

Dealing with an AuthProvider that takes an injected constructor parameter

I have an AuthProvider as follows:

import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.google.inject.name.Named;
import com.mycompanyname.server.User;
import io.dropwizard.auth.Authenticator;
import io.dropwizard.auth.basic.BasicAuthProvider;
import io.dropwizard.auth.basic.BasicCredentials;

@singleton
@javax.ws.rs.ext.Provider
public class StormpathAuthProvider extends BasicAuthProvider {
@Inject
public StormpathAuthProvider(Authenticator<BasicCredentials, User> authenticator, @nAmed("realm") String realm) {
super(authenticator, realm);
}
}

(this is the only way I found of binding a BasicAuthProvider while using dropwizard-guice

And I simply bind it as:

    bind(StormpathAuthProvider.class);

I also bind:

    bind(new TypeLiteral<io.dropwizard.auth.Authenticator<BasicCredentials,User>>(){}).to(StormpathAuthenticator.class);

However, my StormpathAuthenticator takes a constructor parameter that is provided by a @provides method in my guice Module. This can only be run after the bootstrap stage has finished, and leads to:

  1. The dropwizard environment has not yet been set. This is likely caused by trying to access the dropwizard environment during the bootstrap phase.

Any ideas?

Support ContainerRequestFilters and ContainerResponseFilters

At present I'm storing the injector in a filed inside the application class and then manually registering the request filter in the run method as such.

@Override
public void run(RegistrationServiceConfiguration configuration, Environment environment) throws IOException {
environment.jersey().getResourceConfig().getContainerRequestFilters().add(guiceBundle.getInjector().getInstance(DeviceDataExtractionFilter.class));
. . .
}

It would be great if this could be auto discovered and injected similarly to the resource classes.

0.8.0 Could not find a suitable constructor

Hi,
I am new to dropwizard, thus also to dropwizard-guice. And i have problems getting the example to run. I tried rolling my own, because the example project linked in the readme is still using 0.7.x. I am just trying to get the dropwizard example working with guice.
When i run it and query my resource i get the 'Could not find a suitable constructor' exception.

My resource looks like this:

@Path("/hello-world")
@Produces(MediaType.APPLICATION_JSON)
@Resource
public class HelloWorldResource {
    private final String template;
    private final String defaultName;
    private final AtomicLong counter;

    public HelloWorldResource(@Named("template") String template, @Named("defaultName") String defaultName){
        this.template = template;
        this.defaultName = defaultName;
        this.counter = new AtomicLong();
    }

    @GET
    @Timed
    public Saying sayHello(@QueryParam("name") Optional<String> name) {
        final String value = String.format(template, name.or(defaultName));
        return new Saying(counter.incrementAndGet(), value);
    }
}

And my Application like this:

public class HelloWorldApplication extends Application<HelloWorldConfiguration> {
    public static void main(String[] args) throws Exception {
        new HelloWorldApplication().run(args);
    }

    @Override
    public String getName() {
        return "hello-world";
    }

    @Override
    public void initialize(Bootstrap<HelloWorldConfiguration> bootstrap) {
        GuiceBundle<HelloWorldConfiguration> guiceBundle = GuiceBundle.<HelloWorldConfiguration>newBuilder()
                  .addModule(new HelloWorldModule())
                  .enableAutoConfig(getClass().getPackage().getName())
                  .setConfigClass(HelloWorldConfiguration.class)
                  .build();

                bootstrap.addBundle(guiceBundle);
    }

    @Override
    public void run(HelloWorldConfiguration configuration,
            Environment environment) {
    }

Any help is appreciated (must be something i am overlooking).

Under latest guice 4.0-SNAPSHOT: Overriding @Provides method not allowed

It appears a policy/validation change introduced in recent guice development (required, btw, for java8 support) is incompatible with an implementation detail in dropwizard-guice.

With the following in my pom.xml:

<properties>
  <java.version>1.8</java.version>
  <guice.version>4.0-SNAPSHOT</guice.version>
  <dropwizard.version>0.7.0</dropwizard.version>

...

<repositories>
  <repository>
    <id>google-snapshots</id>
    <url>https://oss.sonatype.org/content/repositories/snapshots</url>
    <snapshots>
      <enabled>true</enabled>
    </snapshots>
  </repository>
</repositories>

...

  <dependency>
    <groupId>com.google.inject</groupId>
    <artifactId>guice</artifactId>
    <version>${guice.version}</version>
  </dependency>
  <dependency>
    <groupId>com.hubspot.dropwizard</groupId>
    <artifactId>dropwizard-guice</artifactId>
    <version>${dropwizard.version}</version>
  </dependency>

... server fails to start with the following error:

ERROR [2014-08-12 14:54:10,565] com.hubspot.dropwizard.guice.GuiceBundle: Exception occurred when creating Guice Injector - exiting
! com.google.inject.CreationException: Unable to create injector, see the following errors:
!
! 1) Overriding @provides methods is not allowed.
! @provides method: com.sun.jersey.guice.JerseyServletModule.webApp()
! overridden by: com.hubspot.dropwizard.guice.JerseyContainerModule.webApp()
! at com.google.inject.internal.ProviderMethodsModule.getProviderMethods(ProviderMethodsModule.java:126)

Binding annotations aren't being consistently honored

I tried to file this with Guice, but they won't look at it because I'm using Dropwizard, so maybe this is the right place?

I have two modules, each provides an instance of the same class (a specific Gson configuration). So, each module has a method like so:

@Provides
@ModuleA (this is @ModuleB in the other module)
public Gson provideGson() { ... }

Then I have constructors for classes that use those Gson items, that look like:

@Inject
public FooBar(@ModuleA gson) { ... }

This does NOT work consistently. Sometimes it injects the @moduleb version of Gson into things annotationed with @ModuleA.

I'm using Dropwizard 0.8.5 with dropwizard-guice 0.8.4 and Guice 4.1.

AutoConfig not finding all resources in package

I have 7 resources in a particular package, all of which are annotated with import javax.ws.rs.Path;

Two of the resources are not being picked up by AutoConfig. With my debugger active on the addResources method in AutoConfig, I can see that the Reflections library completely misses them, but I don't know why.

Running OneJar with Dropwizard Guice

Has anyone tried to run a dropwizard project with the Guice Bundle? I'm trying to but get the following error. It seems it can't find the resources. I do use .enableAutoConfig(getClass().getPackage().getName()), and this works in IntelliJ. Any suggestions?

No License inside Jar file

Hi team,

We are planning to use dropwizard-guice for an application but our build has a Nexus IQ scan that checks for License inside the jar and it fails complaining about it. But I do see on Maven central that the dropwizard-guice carries Apache license. So is there any plan to move license text inside jar files?

Question: warning when integrating Governator

Hi,

I have integrated Governator with Guice Bundle but i'm having this warning / dropwizard (0.8.1):


WARN  [2015-05-23 17:47:36,242] com.netflix.governator.lifecycle.ClasspathScanner: No base packages specified - no classpath scanning will be done

Here is how i create the guiceBundle in my module:


    private final GuiceBundle<CarsConfiguration> guiceGovernatorBundle = GuiceBundle.<CarsConfiguration>newBuilder()
            .addModule(this)
            .enableAutoConfig("ma.cars")
            .setConfigClass(CarsConfiguration.class)
            .setInjectorFactory((stage, modules) -> LifecycleInjector.builder()
                    .inStage(stage)
                    .withModules(modules)
                    .build()
                    .createInjector())
            .build();

Is this the correct way to integrate Governator with Guice? How could i get rid of the warning?

Thanks in advance,

Support Servlets with AutoConfig

Currently, servlets are ignored when using AutoConfig. This requires a finicky workaround in the Application class to save the injector to an instance variable during bootstrapping, using that to manually inject a servlet, wrap it in a holder, and add to the environment's getApplicationContext().

In short, it would be nice if Servlets were added and injected like Jersey Resources.

Question: AOP requires binding resources with Guice?

Hi, I have the following setup for GuiceBundle in initialize:

guiceBundle = GuiceBundle.<AppConfiguration>newBuilder()
        .addModule(new AppModule)
        .setConfigClass(AppConfiguration.class)
        .build(Stage.DEVELOPMENT);

        bootstrap.addBundle(guiceBundle);

Resources are setup with the normal env.jersey().register(SomeResource.class) and get their dependencies injected. But it seems our intercept setup in Guice is not running on requests to the resources:

// class-level @Transacational
bindInterceptor(annotatedWith(Transactional.class), any(), transactionInterceptor);
// method-level @Transacational
bindInterceptor(any(), annotatedWith(Transactional.class), transactionInterceptor);

As per Squarespace/jersey2-guice#17 I've registered the resources also in Guice with just a normal bind(SomeResource.class) and then the interceptor works. Is there a way to avoid duplicating this registration?

Resource not a singleton

For some reason, my resources aren't injected as singletons, so every request to a resource instantiates a full new object tree for that resource.

Is this expected behavior? Why? And how do I change it?

PS: I'm using enableAutoConfig

banner.txt not picking up when using enableAutoConfig in GuiceBundle

Just a minor issue, which i noticed with 0.7.0.2 version. The banner.txt file inside src/main/resources is not getting picked when the service is started, with enableAutoConfig in GuiceBundle.

I had to comment the line of enableAutoConfig and go back to registering jersey and health check inside the run method of Application, to get the banner text.

add a Module which need a Configuration

I'm in a case where, in order to initialize injection, one of my modules needs elements from Dropwizard configuration

The problem is the guiceBundle has to be instanciated at the Bootstrapping phase (Service.initialize() ) and I don't have the Configuration object at this time.

example :

public class MyModule {
     private MyConf conf
     public MyModule(MyConf conf) {
          this.conf = conf;
}

public class MyService {
      public void initialize(final Bootstrap<MyConf> bootstrap) {
          GuiceBundle<MyConf> guiceBundle = GuiceBundle
            .<MyMDBConfiguration> newBuilder()
                .addModule(new MyModule( ** How to pass the conf object here ** ) )
                .setConfigClass(MyConf.class)
                .enableAutoConfig(this.getClass().getPackage().getName())
                .build();
        bootstrap.addBundle(guiceBundle);
    }
}

Is it possible to do that using dropwizard-guice ?

How to inject configuration into managed object

Hi,
is there any possibility to inject a configuration into managed object.
Background: I have a managed object encapsulating Redis and want during startup access the configuration for that.
Thank you.

singleton with configuration - environment problem

An application with a singleton requiring configuration gives the following error:
The dropwizard environment has not yet been set. This is likely caused by trying to access the dropwizard environment during the bootstrap phase.

Using version 0.7.0.3
This was not a problem with 0.6.2

Configuration is done via a provider as mentioned in the readme.
Example configure

bind(SomeSingleton.class).in(Singleton.class);

with SomeSingleton depending on SomePool

DropwizardEnvironmentModule - Class<? extends Configuration> support

Is there any reason why DropwizardEnvironmentModule uses a Configuration @Provider instead of an application derived class? This mean that all dependent classes must downcast to use this dependency which is less than ideal. For value objects, it really makes sense to used the most derived type.

Perhaps also binding to an instance with a derived class object would help, by using configuration.getClass():

    modules.add(new AbstractModule() {
        @Override
        protected void configure() {
            bind(configuration.getClass()).toInstance(configuration);
            bind(Configuration.class).toInstance(configuration);
            bind(Environment.class).toInstance(environment);
        }
    });

System.exit() is evil, pls no

So I just discovered this using another dropwizard-guice library, but figured I should put it back here since it was caused by code based on this library.

So this line: https://github.com/HubSpot/dropwizard-guice/blob/master/src/main/java/com/hubspot/dropwizard/guice/GuiceBundle.java#L110

It's meant to terminate the server if initialization fails, which does make sense; but I discovered that, depending on what logging library is used, System.exit() terminates so forcefully, that it even kills the task that would print out that super-useful error message on the previous line. As such, my app started spitting out exit code 1's with no error message, no stacktrace; this was pretty terrible to debug. (Fun fact: If you put a breakpoint on the exit line, it actually gives the logger a chance to print, and you can see an error message again.)

In general, I've discovered that System.exit() is absolutely horrifying, in part because it's one of the few things that can stop threads mid-try-block, with no catch or finally - a dubious honor shared with (1) daemon threads, and (2) outright crash/segfault of the JVM.

Dropwizard 0.8.3 and 0.8.4 support

There are two new dropwizard releases, 0.8.3 and 0.8.4.

I am not sure whether it makes sense to support these two, since 0.9.0 is just around the corner. Just wanted to mention it.

I tried to fix it by updating jersey and the hk2 stuff, but I got failing tests.

Extending InjectableHealthCheck with abstract class

I have several healthchecks that do almost the same thing (testing if another host is reachable). They all extend InjectableHealthCheck.
I'd like to extract common functionality into an abstract superclass that extends InjectableHealthCheck. dropwizard-guice' AutoConfig doesn't check whether a sub type of InjectableHealthCheck is abtract or not. So guice tries to instantiate my abstract class, which obviously fails.

So basically dropwizard-guice needs to check whether the sub type can be instantiated or not.

I guess it would a good idea to check this somewhere here.

If you agree with fixing this problem the way I suggested, I'll do it and send a PR.

dropwizard 0.8.2

Hello,
when are you planning on supporting dropwizard 0.8.2?

Will you accept an pull request/release a new version if I prepare one?

greetings

InjectedResourcesTest.java question

Hi all, I'm struggling at making this example work with an injected resource as opposite to an explicit resource creation.

https://github.com/HubSpot/dropwizard-guice/blob/master/src/test/java/com/hubspot/dropwizard/guice/InjectedResourcesTest.java

public class InjectedResourcesTest {

    @ClassRule
    public static final ResourceTestRule resources = ResourceTestRule.builder()
            .addResource(new ExplicitResource(new ExplicitDAO()))  // <-- Guice here?
            .build();

   @Setup
   public void setup() {
      // Initialize Guice.
    }

    @Test
    public void shouldGetExplicitMessage() {
        // when
        String message = resources.client().target("/explicit/message").request().get(String.class);

        // then
        assertThat(message).isEqualTo("this DAO was bound explicitly");
    }

    @Test
    public void shouldGetJitMessage() {
        // when
        String message = resources.client().target("/explicit/message").request().get(String.class);

        // then
        assertThat(message).isEqualTo("this DAO was bound explicitly");
    }
}

The problem I see is that at the time the RULE runs, the setup method which initializes Guice hasn't yet run.

My goal es to test and end-to-end resource without mocking my DAOs or controllers, and I want to use Guice to resolve the injection dependencies.

Hopefully this question makes sense.
Thanks.

HibernateBundle + GuiceBundle

How can i combine the hibernate bundle with the guicebundle? I need the SessionFactory in my Dao objects, but this is only available after the bootstrap has finished. Guice however tries to inject the SessionFactory at boostrap time causing a nullpointer. How can i combine these two bundle to work in sync?

publish 0.7.0-rc2 to maven

Any plans of publishing an rc to maven?

Using this dependency:

<dependency>
    <groupId>io.dropwizard</groupId>
    <artifactId>dropwizard-core</artifactId>
    <version>0.7.0-rc2</version>
</dependency>

AVRO support by injecting my own ObjectMapper

Hi all, great work here.

I'm trying to add avro support to Jersey (which I was able to do directly on Jersey) but for some reason when plugging it in in the Guice Module via GuiceBundle it is not picked up.

In my module I do:

public class HelloWorldModule extends AbstractModule {

    @Override
    protected void configure() {
        bind(ObjectMapper.class).toProvider(ObjectMapperProvider.class).in(Singleton.class);
       bind(JacksonJsonProvider.class).toProvider(JacksonAPIJsonProviderProvider.class).in(Singleton.class);
    }

It does work (one way - AVRO to JSON) if I do this in the App class during the initialize method:
bootstrap.getObjectMapper().registerModule(new ObjectMapperProvider.MyModule());

Could you please advice?

Thanks

Getting a warning at startup: "It appears jersey2-guice-spi is either not present or in conflict with some other Jar"

I'm getting a WARN in my log at startup:

com.squarespace.jersey2.guice.JerseyGuiceUtils: It appears jersey2-guice-spi is either not present or in conflict with some other Jar: ServiceLocatorGeneratorImpl(hk2-locator, 814377348)

Is this to be expected? I can see that the GuiceBundle.java explicitly loads the HK2 ServiceLocator which is what makes the JerseyGuiceUtils complain:

https://github.com/HubSpot/dropwizard-guice/blob/master/src/main/java/com/hubspot/dropwizard/guice/GuiceBundle.java#L104-L111

Everything seems to work alright but still it's a bit annoying having a WARN in the startup log so I just to make sure that this is ok?

Managed impl being injected twice even though it is a @Singleton

In my injector, I am seeing my @Singleton getting injected twice if I do:

bind(DbManager.class).to(DbManagerImpl.class).asEagerSingleton();

Am I doing something wrong, or is this a bug?

I stepped through in a debugger, and it appears that two DbManagerImpl instances are added to the private list of _beans in org.eclipse.jetty.util.component.ContainerLifeCycle.doStart().

Guice Interceptors For Resources

Hi Team,

I have been struggling with adding a Guice Interceptor that wraps resource endpoints.

I have this Inteceptor:

public class MetricInterceptor implements MethodInterceptor {
    private static final Logger _log = LoggerFactory.getLogger(MethodInterceptor.class);

    @Override
    public Object invoke(MethodInvocation methodInvocation) throws Throwable {
        _log.info("WORKINGGGGGGG! " + methodInvocation.getMethod().getName());
        return methodInvocation.proceed();
    }
}

And an AbstractModule:

        bindInterceptor(Matchers.any(), Matchers.any(), new MetricInterceptor());

So basically the interceptor should be calling pretty much every method that is around.

But its called pretty much for every method that is around there, but its not called for Resource method calls, like on:

@Path("/integrations")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Singleton
public class IntegrationsResource {
    @POST
    @Path("hipchat")
    public Response addHipChatIntegration(@Auth User user, IntegrationHipChatDTO integrationHipChatDTO) {
    }
}

I have a TestApplication class:

public class TestApplication extends Application<APIConfigurationForTest> {

    public static GuiceBundle<APIConfigurationForTest> jersey2GuiceBundle;

    @Override
    public void initialize(final Bootstrap<APIConfigurationForTest> bootstrap) {
        jersey2GuiceBundle = GuiceBundle.<APIConfigurationForTest>newBuilder()
                .addModule(new SendgridEmailModule())
                .setConfigClass(APIConfigurationForTest.class)
                .enableAutoConfig(SettingsResource.class.getPackage().getName())
                .build();
        bootstrap.addBundle(jersey2GuiceBundle);
    }

and it is being called in our base test class:

public class BaseResourceEndToEndTest {
    private final DropwizardAppRule<APIConfigurationForTest> applicationRoule =
            new DropwizardAppRule<>(io.codigo.guice.TestApplication.class, resourceFilePath("config-test.yml"));
}

Any help would be appreciated

Thanks

Modules.override for JerseyServletModule conflicts with Shiro filters

I'm curious why you're using a JerseyContainerModule and overriding JerseyServletModule with it.

The problem that line 84 in GuiceBundle is causing me is that it conflicts with the ShiroWebModule. I'm getting errors like:

1) Scope ServletScopes.REQUEST is already bound to com.google.inject.servlet.RequestScoped. Cannot bind ServletScopes.REQUEST.
  at com.google.inject.servlet.InternalServletModule.configure(InternalServletModule.java:77)

2) Scope ServletScopes.SESSION is already bound to com.google.inject.servlet.SessionScoped. Cannot bind ServletScopes.SESSION.
  at com.google.inject.servlet.InternalServletModule.configure(InternalServletModule.java:78)

If I remove line 84 from GuiceBundle and replace it with:

modules.add(new JerseyServletModule());

then the problem disappears.

I suspect the issue is with the use of Modules.override(). This issue indicates that there's a problem with Modules.override() and the servlet module. Furthermore, Dhanji says in this thread that Modules.override() is not supported for ServletModules.

How could this be refactored to avoid the issue I'm seeing?

com.google.inject.OutOfScopeException on inject javax.servlet.http.HttpServletRequest

I updated to dropwizard-guice 1.0.0
Since then I do get an com.google.inject.OutOfScopeException when I try to inject the HttpServletRequest:

This is the method signature:

public Response uploadCsvFile(@PathParam("subject_id") String subjectId, @Context HttpServletRequest request)

This is my stacktrace:

WARN  [2016-08-30 12:57:27,713] [X-PEX-CORRELATION-ID:] org.glassfish.jersey.internal.Errors: The following warnings have been detected: WARNING: Unknown HK2 failure detected:
MultiException stack 1 of 1
com.google.inject.ProvisionException: Unable to provision, see the following errors:

1) Error in custom provider, com.google.inject.OutOfScopeException: Cannot access scoped [javax.servlet.http.HttpServletRequest]. Either we are not currently inside an HTTP Servlet request, or you may have forgotten to apply com.google.inject.servlet.GuiceFilter as a servlet filter for this request.
  at com.google.inject.servlet.InternalServletModule.provideHttpServletRequest(InternalServletModule.java:106) (via modules: com.google.inject.servlet.ServletModule -> com.google.inject.servlet.InternalServletModule)
  while locating javax.servlet.http.HttpServletRequest

1 error
    at com.google.inject.internal.InjectorImpl$2.get(InjectorImpl.java:1025)
    at com.squarespace.jersey2.guice.GuiceBindingDescriptor.create(GuiceBindingDescriptor.java:66)
    at org.jvnet.hk2.internal.SystemDescriptor.create(SystemDescriptor.java:463)
    at com.squarespace.jersey2.guice.GuiceScopeContext.findOrCreate(GuiceScopeContext.java:36)
    at org.jvnet.hk2.internal.Utilities.createService(Utilities.java:2022)
    at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:114)
    at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:88)
    at org.glassfish.jersey.internal.inject.ContextInjectionResolver.resolve(ContextInjectionResolver.java:126)
    at org.glassfish.jersey.server.internal.inject.DelegatedInjectionValueFactoryProvider$1.provide(DelegatedInjectionValueFactoryProvider.java:107)
    at org.glassfish.jersey.server.spi.internal.ParamValueFactoryWithSource.provide(ParamValueFactoryWithSource.java:71)
    at org.glassfish.jersey.server.spi.internal.ParameterValueHelper.getParameterValues(ParameterValueHelper.java:90)
    at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$AbstractMethodParamInvoker.getParamValues(JavaResourceMethodDispatcherProvider.java:127)
    at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$ResponseOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:160)
    at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:99)
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:389)
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:347)
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:102)
    at org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:326)
    at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
    at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:267)
    at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317)
    at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:305)
    at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1154)
    at org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:473)
    at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:427)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:388)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:341)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:228)
    at io.dropwizard.jetty.NonblockingServletHolder.handle(NonblockingServletHolder.java:49)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1689)
    at io.dropwizard.servlets.ThreadNameFilter.doFilter(ThreadNameFilter.java:34)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1676)
    at io.dropwizard.jersey.filter.AllowedMethodsFilter.handle(AllowedMethodsFilter.java:50)
    at io.dropwizard.jersey.filter.AllowedMethodsFilter.doFilter(AllowedMethodsFilter.java:44)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1676)
    at com.signavio.pex.common.util.PexCorrelationIdFilter.doFilter(PexCorrelationIdFilter.java:32)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1676)
    at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:581)
    at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1174)
    at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:511)
    at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1106)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
    at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:134)
    at com.codahale.metrics.jetty9.InstrumentedHandler.handle(InstrumentedHandler.java:240)
    at io.dropwizard.jetty.RoutingHandler.handle(RoutingHandler.java:51)
    at org.eclipse.jetty.server.handler.gzip.GzipHandler.handle(GzipHandler.java:396)
    at io.dropwizard.jetty.BiDiGzipHandler.handle(BiDiGzipHandler.java:68)
    at org.eclipse.jetty.server.handler.RequestLogHandler.handle(RequestLogHandler.java:56)
    at org.eclipse.jetty.server.handler.StatisticsHandler.handle(StatisticsHandler.java:169)
    at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:134)
    at org.eclipse.jetty.server.Server.handle(Server.java:524)
    at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:319)
    at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:253)
    at org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:273)
    at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:95)
    at org.eclipse.jetty.io.SelectChannelEndPoint$2.run(SelectChannelEndPoint.java:93)
    at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.executeProduceConsume(ExecuteProduceConsume.java:303)
    at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.produceConsume(ExecuteProduceConsume.java:148)
    at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.run(ExecuteProduceConsume.java:136)
    at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:671)
    at org.eclipse.jetty.util.thread.QueuedThreadPool$2.run(QueuedThreadPool.java:589)
    at java.lang.Thread.run(Thread.java:745)
Caused by: com.google.inject.OutOfScopeException: Cannot access scoped [javax.servlet.http.HttpServletRequest]. Either we are not currently inside an HTTP Servlet request, or you may have forgotten to apply com.google.inject.servlet.GuiceFilter as a servlet filter for this request.
    at com.google.inject.servlet.GuiceFilter.getContext(GuiceFilter.java:165)
    at com.google.inject.servlet.GuiceFilter.getOriginalRequest(GuiceFilter.java:147)
    at com.google.inject.servlet.ServletScopes$1$1.get(ServletScopes.java:107)
    at com.google.inject.internal.InternalFactoryToProviderAdapter.get(InternalFactoryToProviderAdapter.java:41)
    at com.google.inject.internal.InjectorImpl$2$1.call(InjectorImpl.java:1016)
    at com.google.inject.internal.InjectorImpl.callInContext(InjectorImpl.java:1092)
    at com.google.inject.internal.InjectorImpl$2.get(InjectorImpl.java:1012)
    ... 64 more

Any idea what might be wrong here?
Thanks

In guice 4, overriding @Provides methods is not allowed

Upgrade to guice 4 (to get around, e.g. google/guice#757) and you'll get this error:

! 1) Overriding @provides methods is not allowed.
! @provides method: com.sun.jersey.guice.JerseyServletModule.webApp()
! overridden by: com.hubspot.dropwizard.guice.JerseyContainerModule.webApp()
! at com.google.inject.internal.ProviderMethodsModule.getProviderMethods(ProviderMethodsModule.java:128)
!

Request: Testing Example

Do you guys use guice/dropwizard-guice while writing tests for your service/resource implementations? I'm curious to see an example in the example project.

Order of Managed objects added to environment

AutoConfig adds the managed object in random order since subclasses of Managed are returned as a Set.
The Managed objects are started by dropwizard in the order in which they were added to the environments and stopped in that reverse order.
As a solution I suggest supporting selective AutoConfig settings like:
GuiceBundle.newBuilder().enableAutoConfig().excludeManaged()
or split AutoConfig to be per AutoConfigManaged, AutoConfigHealthCheck .....

Overlapping classes with dropwizard-core

When using dropwizard-guice together with dropwizard-core (which is, I presume, a common use-case), both in version 0.8.0, there are 3 pairs of JARs defined under different artifact descriptors that have overlapping classes. Sample output from maven-shade-plugin:

[WARNING] aopalliance-repackaged-2.4.0-b09.jar, aopalliance-1.0.jar define 9 overlappping classes: 
[WARNING]   - org.aopalliance.intercept.ConstructorInterceptor
[WARNING]   - org.aopalliance.intercept.MethodInvocation
[WARNING]   - org.aopalliance.intercept.MethodInterceptor
[WARNING]   - org.aopalliance.intercept.Invocation
[WARNING]   - org.aopalliance.aop.AspectException
[WARNING]   - org.aopalliance.intercept.Interceptor
[WARNING]   - org.aopalliance.intercept.Joinpoint
[WARNING]   - org.aopalliance.intercept.ConstructorInvocation
[WARNING]   - org.aopalliance.aop.Advice
[WARNING] jsr305-3.0.0.jar, annotations-3.0.0.jar define 35 overlappping classes: 
[WARNING]   - javax.annotation.RegEx
[WARNING]   - javax.annotation.concurrent.Immutable
[WARNING]   - javax.annotation.meta.TypeQualifierDefault
[WARNING]   - javax.annotation.meta.TypeQualifier
[WARNING]   - javax.annotation.Syntax
[WARNING]   - javax.annotation.Nonnull
[WARNING]   - javax.annotation.CheckReturnValue
[WARNING]   - javax.annotation.CheckForNull
[WARNING]   - javax.annotation.meta.TypeQualifierNickname
[WARNING]   - javax.annotation.MatchesPattern
[WARNING]   - 25 more...
[WARNING] javax.inject-2.4.0-b09.jar, javax.inject-1.jar define 6 overlappping classes: 
[WARNING]   - javax.inject.Inject
[WARNING]   - javax.inject.Singleton
[WARNING]   - javax.inject.Scope
[WARNING]   - javax.inject.Named
[WARNING]   - javax.inject.Provider
[WARNING]   - javax.inject.Qualifier
[WARNING] maven-shade-plugin has detected that some .class files
[WARNING] are present in two or more JARs. When this happens, only
[WARNING] one single version of the class is copied in the uberjar.
[WARNING] Usually this is not harmful and you can skeep these
[WARNING] warnings, otherwise try to manually exclude artifacts
[WARNING] based on mvn dependency:tree -Ddetail=true and the above
[WARNING] output
[WARNING] See http://docs.codehaus.org/display/MAVENUSER/Shade+Plugin

A workaround is to define the proper exclusions on the dropwizard-guice dependency:

            <exclusions>
                <exclusion>
                    <groupId>aopalliance</groupId>
                    <artifactId>aopalliance</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>com.google.code.findbugs</groupId>
                    <artifactId>annotations</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>javax.inject</groupId>
                    <artifactId>javax.inject</artifactId>
                </exclusion>
            </exclusions>

Best would be, of course, if those dependencies would be aligned with dropwizard-core and the users of dropwizard-guice wouldn't have to worry about these dependency conflicts.

Code example is out of date

You have:

        environment.healthChecks().register("Template", TemplateHealthCheck.class);

within your code examples. Unfortunately Dropwizard seem to have changed the API to require an instance rather than a class. (This makes injecting into healthchecks without using autoconfig a challenge.)

support filters

It would be nice to have injection in filters.
For example, allowing

environment.addFilter(MyFilter.class, "/*");

instead of

environment.addFilter(injector.getInstance(MyFilter.class), "/*");

[Question] bindListener declared in module not being fired

So I'm trying to write a slf4j Logger provider for my app using Guice's custom injections, but when I try to use the injected instance in my resource class it's always null. Is there any extra setup needed for this to work besides what's in the link?

edit: I've also tried using sli4j, didn't work. Btw I'm using latest Java 7 and dropwizard-guice 0.8.1.0.

Thanks!

Governator integration is broken in dropwizard-guice 0.8.0

Governator is incompatible with the latest dropwizard (0.8.0), so the mentioned example in the README no longer works.

If we attempt to exclude Guice from Governator, we see the following stack trace:
Exception in thread "main" java.lang.NoClassDefFoundError: Lcom/google/inject/internal/util/$ImmutableList;
at java.lang.Class.getDeclaredFields0(Native Method)
at java.lang.Class.privateGetDeclaredFields(Class.java:2499)
at java.lang.Class.getDeclaredFields(Class.java:1811)
at com.google.inject.spi.InjectionPoint.getInjectionPoints(InjectionPoint.java:661)
at com.google.inject.spi.InjectionPoint.forInstanceMethodsAndFields(InjectionPoint.java:366)
at com.google.inject.spi.InjectionPoint.forInstanceMethodsAndFields(InjectionPoint.java:385)
at com.google.inject.internal.BindingBuilder.toProvider(BindingBuilder.java:110)
at com.google.inject.internal.BindingBuilder.toProvider(BindingBuilder.java:100)
at com.google.inject.internal.BindingBuilder.toProvider(BindingBuilder.java:43)
at com.google.inject.multibindings.Multibinder$RealMultibinder.configure(Multibinder.java:269)
at com.google.inject.spi.Elements$RecordingBinder.install(Elements.java:253)
at com.google.inject.multibindings.Multibinder.newSetBinder(Multibinder.java:115)
at com.google.inject.multibindings.Multibinder.newSetBinder(Multibinder.java:124)
at com.netflix.governator.guice.BootstrapBinder.(BootstrapBinder.java:65)
at com.netflix.governator.guice.InternalBootstrapModule.configure(InternalBootstrapModule.java:88)
at com.google.inject.AbstractModule.configure(AbstractModule.java:62)
at com.google.inject.spi.Elements$RecordingBinder.install(Elements.java:253)
at com.google.inject.spi.Elements.getElements(Elements.java:108)
at com.google.inject.internal.InjectorShell$Builder.build(InjectorShell.java:135)
at com.google.inject.internal.InternalInjectorCreator.build(InternalInjectorCreator.java:104)
at com.google.inject.Guice.createInjector(Guice.java:96)
at com.google.inject.Guice.createInjector(Guice.java:84)
at com.netflix.governator.guice.LifecycleInjector.(LifecycleInjector.java:418)
at com.netflix.governator.guice.LifecycleInjectorBuilderImpl.build(LifecycleInjectorBuilderImpl.java:309)
at com.gordysc.GovernatorInjectorFactory.create(GovernatorInjectorFactory.java:15)
at com.hubspot.dropwizard.guice.GuiceBundle.initInjector(GuiceBundle.java:105)
at com.hubspot.dropwizard.guice.GuiceBundle.initialize(GuiceBundle.java:96)
at io.dropwizard.setup.Bootstrap.addBundle(Bootstrap.java:142)
at com.gordysc.ExampleApplication.initialize(ExampleApplication.java:22)
at io.dropwizard.Application.run(Application.java:71)
at com.gordysc.ExampleApplication.main(ExampleApplication.java:32)
Caused by: java.lang.ClassNotFoundException: com.google.inject.internal.util.$ImmutableList
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
... 31 more

So, Governator depends on Guice 3.0 for ImmutableList:
http://grepcode.com/file/repo1.maven.org/maven2/com.google.inject/guice/3.0/com/google/inject/internal/util/ImmutableList.java?av=f

Note: This class no longer exists in Guice 4.0-beta5.

However, dropwizard-guice depends on Guice 4.0-beta5. You can see this by not excluding Guice from Governator (using 3.0), you'll see the stack trace:

Exception in thread "main" java.lang.NoSuchMethodError: com.google.inject.binder.AnnotatedBindingBuilder.toProvider(Ljavax/inject/Provider;)Lcom/google/inject/binder/ScopedBindingBuilder;
at com.squarespace.jersey2.guice.InternalJerseyModule.configure(InternalJerseyModule.java:58)
at com.google.inject.AbstractModule.configure(AbstractModule.java:59)
at com.google.inject.spi.Elements$RecordingBinder.install(Elements.java:223)
at com.google.inject.AbstractModule.install(AbstractModule.java:118)
at com.squarespace.jersey2.guice.BootstrapModule.configure(BootstrapModule.java:44)
at com.google.inject.AbstractModule.configure(AbstractModule.java:59)
at com.google.inject.spi.Elements$RecordingBinder.install(Elements.java:223)
at com.google.inject.AbstractModule.install(AbstractModule.java:118)
at com.hubspot.dropwizard.guice.JerseyModule.configureServlets(JerseyModule.java:15)
at com.google.inject.servlet.ServletModule.configure(ServletModule.java:55)
at com.google.inject.AbstractModule.configure(AbstractModule.java:59)
at com.google.inject.spi.Elements$RecordingBinder.install(Elements.java:223)
at com.google.inject.spi.Elements.getElements(Elements.java:101)
at com.google.inject.internal.InjectorShell$Builder.build(InjectorShell.java:133)
at com.google.inject.internal.InternalInjectorCreator.build(InternalInjectorCreator.java:103)
at com.google.inject.internal.InjectorImpl.createChildInjector(InjectorImpl.java:217)
at com.netflix.governator.guice.LifecycleInjector.createChildInjector(LifecycleInjector.java:327)
at com.netflix.governator.guice.LifecycleInjector.createInjector(LifecycleInjector.java:394)
at com.netflix.governator.guice.LifecycleInjector.createInjector(LifecycleInjector.java:348)
at com.gordysc.GovernatorInjectorFactory.create(GovernatorInjectorFactory.java:15)
at com.hubspot.dropwizard.guice.GuiceBundle.initInjector(GuiceBundle.java:105)
at com.hubspot.dropwizard.guice.GuiceBundle.initialize(GuiceBundle.java:96)
at io.dropwizard.setup.Bootstrap.addBundle(Bootstrap.java:142)
at com.gordysc.ExampleApplication.initialize(ExampleApplication.java:22)
at io.dropwizard.Application.run(Application.java:71)
at com.gordysc.ExampleApplication.main(ExampleApplication.java:32)

So, dropwizard-guice depends on a method added in Guice 4.0-beta5:
http://grepcode.com/file/repo1.maven.org/maven2/com.google.inject/guice/4.0-beta5/com/google/inject/binder/LinkedBindingBuilder.java#LinkedBindingBuilder.toProvider%28java.lang.Class%29

Integration Test using mocked beans

We have a following scenario,
OurServiceApplication is adding the below bundle during the initialize(Bootstrap...)
GuiceBundle guiceBundle = GuiceBundle.newBuilder()
.addModule(new OurModule())...

OurModule has the bean injection of DatabaseSource etc.

We are writing the integration test as below
DropwizardAppRule RULE = new DropwizardAppRule<>(
OurServiceApplication.class, "our.yml")

Now we want to inject in-memory datasource, can u pls let us know how to inject it?
Please note that TestModule has the InMemoryDatasource beans..

Guice unable to create injector for Singletons depending on Configuration or Environment

Guice is unable to create an injector for eager singletons that depend on Configuration or Environment because we don't immediately have instances of those classes (not until GuiceBundle.run()).

This wasn't really an issue until the default stage was changed to Stage.PRODUCTION (394cffc), which forces all Singletons to be eager.

The simplest fix is to revert the default stage back to Stage.DEVELOPMENT, or encourage people facing this issue to explicitly use the development stage.

Is it a bad thing that we've been defaulting to the development stage for so long?

@eliast @axiak @astubbs

DropWizard 0.9.1 support?

Thanks for creating this library.

I tried to hack around the dependency conflicts between DropWizard-0.9.1 and DropWizard-Guice 0.8.x but didn't managed to succeed.

Is there a plan to release an updated that is compatible with the DropWizard 0.9 series?

Thanks

Instantiating a test configuration instance from a test yaml file.

Hi all, I'm having issues instantiating a test configuration instance for my local dev environment.

after following the example here: https://github.com/HubSpot/dropwizard-guice/blob/master/src/test/java/com/hubspot/dropwizard/guice/GuiceBundleTest.java

(in that example the author does a "new Configuration()" but I interested in loading the test info located at "config-test.yml" instead.

I wrote this class:

@RunWith(MockitoJUnitRunner.class)
public class GuiceBundleTest {

   Environment environment;

    private GuiceBundle<Configuration> guiceBundle;

    @ClassRule
    public static final DropwizardAppRule<APIConfigurationForTest> RULE =
            new DropwizardAppRule<APIConfigurationForTest>(TestApplication.class, ResourceHelpers.resourceFilePath("config-test.yml"));

    @Before
    public void setUp() {
        environment = RULE.getEnvironment();
        guiceBundle = GuiceBundle.newBuilder()
                .addModule(new TestModule(RULE.getConfiguration()))
                .build();
        Bootstrap bootstrap = mock(Bootstrap.class);
        guiceBundle.initialize(bootstrap);
        guiceBundle.run(RULE.getConfiguration(), environment);
    }
    ....

and got a:

java.lang.IllegalStateException: Started
    at org.eclipse.jetty.servlet.BaseHolder.illegalStateIfContextStarted(BaseHolder.java:181)
    at org.eclipse.jetty.servlet.FilterHolder$Registration.addMappingForUrlPatterns(FilterHolder.java:238)
    at com.hubspot.dropwizard.guice.JerseyUtil.registerGuiceFilter(JerseyUtil.java:69)
    at com.hubspot.dropwizard.guice.GuiceBundle.run(GuiceBundle.java:115)
    at io.codigo.guice.GuiceBundleTest.setUp(GuiceBundleTest.java:55)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
    at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.rules.ExternalResource$1.evaluate(ExternalResource.java:48)
    at org.junit.rules.RunRules.evaluate(RunRules.java:20)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37)
    at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:67)

I spend around 2 hours trying to figure this out. If you have any hint on how to get the server to start please let me know.

Thanks

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.