Созданный класс EnhancerByGuice вызывает ошибку с Dropwizard при добавлении пользовательской аннотации и MethodInterceptor - PullRequest
0 голосов
/ 19 июня 2019

У меня есть приложение dropwizard со следующим файлом ресурсов:

@Path("/v1/")
@Api("Static Resources")
@Slf4j
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Singleton
public class StaticResourcesImpl implements StaticResources {

    @Inject private SomeService someService;    

    @GET
    @Path("/help/{id}")
    @ApiOperation(value = "Give a Help page", response = Help.class)
    //@Action(action = "getHelp")
    public Response getHelp(@PathParam("id") String id) {
        try {
            return Response.ok(someService.read(id)).build();
        } catch (NotFoundException e){
            log.warn("Exception in reading Help for id: " + id, e );
            return Response.status(HttpStatus.SC_NOT_FOUND).entity(e.getMessage()).build();
        }
    }

Это было зарегистрировано на jersey как показано ниже:

environment.jersey().register(injector.getInstance(StaticResources.class));

Выше работ.

Но если я создаю одну пользовательскую аннотацию и добавляю к ресурсу (см. Выше комментарий до getHelp метода):

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
/**
 * This annotation is intended to be used on a method with an ActionName
 */
public @interface Action {
    String action();
}

и добавьте метод-перехватчик через bindInterceptor, например:

requestStaticInjection(MyInterceptor.class);
bindInterceptor(Matchers.any(), Matchers.annotatedWith(Action.class), new MyInterceptor());

, где MyInterceptor выглядит следующим образом:

public class MyInterceptor implements MethodInterceptor {
    @Inject
    private static myService MyService;

    @Override
    public Object invoke(MethodInvocation methodInvocation) throws Throwable {
        Action action = methodInvocation.getMethod().getAnnotation(Action.class);            
            if(myService.my Condition(authRequest)) {
                return methodInvocation.proceed();
            }
        }
        return myError;
    }

Когда я пытаюсь запустить это, я получаю следующую ошибку:

[[FATAL] Модель ресурсов имеет неоднозначный (под) метод ресурсов для HTTP-метода GET и входные типы mime, как определено аннотациями "@Consumes" и "@Produces" в методах Java public javax.ws.rs. core.Response com.abc.demo.apis.usecase.resources.impl.StaticResourcesImpl.getHelp () и публичный финал javax.ws.rs.core.Response com.abc.demo.apis.usecase.resources.impl.StaticResourcesImpl $ $ EnhancerByGuice $$ 69175a50.getHelp () при сопоставлении регулярного выражения / содержимого / форматов. Эти два метода производят и потребляют точно такие же mime-типы, поэтому их вызов в качестве методов ресурса всегда будет неудачным.;

подробная трассировка стека:

javax.servlet.ServletException: io.dropwizard.jersey.setup.JerseyServletContainer-e0f2686@72f166ff==io.dropwizard.jersey.setup.JerseyServletContainer,jsp=null,order=1,inst=false
    at org.eclipse.jetty.servlet.ServletHolder.initServlet(ServletHolder.java:691)
    at org.eclipse.jetty.servlet.ServletHolder.initialize(ServletHolder.java:427)
    at org.eclipse.jetty.servlet.ServletHandler.initialize(ServletHandler.java:760)
    at org.eclipse.jetty.servlet.ServletContextHandler.startContext(ServletContextHandler.java:374)
    at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:848)
    at org.eclipse.jetty.servlet.ServletContextHandler.doStart(ServletContextHandler.java:287)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
    at org.eclipse.jetty.util.component.ContainerLifeCycle.start(ContainerLifeCycle.java:138)
    at org.eclipse.jetty.util.component.ContainerLifeCycle.doStart(ContainerLifeCycle.java:108)
    at org.eclipse.jetty.server.handler.AbstractHandler.doStart(AbstractHandler.java:113)
    at com.codahale.metrics.jetty9.InstrumentedHandler.doStart(InstrumentedHandler.java:101)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
    at org.eclipse.jetty.util.component.ContainerLifeCycle.start(ContainerLifeCycle.java:138)
    at org.eclipse.jetty.util.component.ContainerLifeCycle.doStart(ContainerLifeCycle.java:117)
    at org.eclipse.jetty.server.handler.AbstractHandler.doStart(AbstractHandler.java:113)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
    at org.eclipse.jetty.util.component.ContainerLifeCycle.start(ContainerLifeCycle.java:138)
    at org.eclipse.jetty.util.component.ContainerLifeCycle.doStart(ContainerLifeCycle.java:108)
    at org.eclipse.jetty.server.handler.AbstractHandler.doStart(AbstractHandler.java:113)
    at org.eclipse.jetty.server.handler.gzip.GzipHandler.doStart(GzipHandler.java:403)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
    at org.eclipse.jetty.util.component.ContainerLifeCycle.start(ContainerLifeCycle.java:138)
    at org.eclipse.jetty.util.component.ContainerLifeCycle.doStart(ContainerLifeCycle.java:108)
    at org.eclipse.jetty.server.handler.AbstractHandler.doStart(AbstractHandler.java:113)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
    at org.eclipse.jetty.util.component.ContainerLifeCycle.start(ContainerLifeCycle.java:138)
    at org.eclipse.jetty.util.component.ContainerLifeCycle.doStart(ContainerLifeCycle.java:108)
    at org.eclipse.jetty.server.handler.AbstractHandler.doStart(AbstractHandler.java:113)
    at org.eclipse.jetty.server.handler.StatisticsHandler.doStart(StatisticsHandler.java:252)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
    at org.eclipse.jetty.util.component.ContainerLifeCycle.start(ContainerLifeCycle.java:138)
    at org.eclipse.jetty.server.Server.start(Server.java:419)
    at org.eclipse.jetty.util.component.ContainerLifeCycle.doStart(ContainerLifeCycle.java:108)
    at org.eclipse.jetty.server.handler.AbstractHandler.doStart(AbstractHandler.java:113)
    at org.eclipse.jetty.server.Server.doStart(Server.java:386)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
    at io.dropwizard.cli.ServerCommand.run(ServerCommand.java:53)
    at io.dropwizard.cli.EnvironmentCommand.run(EnvironmentCommand.java:44)
    at io.dropwizard.cli.ConfiguredCommand.run(ConfiguredCommand.java:87)
    at io.dropwizard.cli.Cli.run(Cli.java:78)
    at io.dropwizard.Application.run(Application.java:93)
    at com.abc.demo.apis.Boot.main(Boot.java:111)
Caused by: org.glassfish.jersey.server.model.ModelValidationException: Validation of the application resource model has failed during application initialization.
[[FATAL] A resource model has ambiguous (sub-)resource method for HTTP method GET and input mime-types as defined by"@Consumes" and "@Produces" annotations at Java methods public javax.ws.rs.core.Response com.abc.demo.apis.usecase.resources.impl.StaticResourcesImpl.getHelp() and public final javax.ws.rs.core.Response com.abc.demo.apis.usecase.resources.impl.StaticResourcesImpl$$EnhancerByGuice$$69175a50.getHelp() at matching regular expression /contents/formats. These two methods produces and consumes exactly the same mime-types and therefore their invocation as a resource methods will always fail.; 
    source='org.glassfish.jersey.server.model.RuntimeResource@330d557e', source='org.glassfish.jersey.server.model.RuntimeResource@439047ef']
    at org.glassfish.jersey.server.ApplicationHandler.initialize(ApplicationHandler.java:553)
    at org.glassfish.jersey.server.ApplicationHandler.access$500(ApplicationHandler.java:182)
    at org.glassfish.jersey.server.ApplicationHandler$3.call(ApplicationHandler.java:348)
    at org.glassfish.jersey.server.ApplicationHandler$3.call(ApplicationHandler.java:345)

Ниже приведены зависимости:

    <dependency>
        <groupId>com.smoketurner</groupId>
        <artifactId>dropwizard-swagger</artifactId>
        <version>1.3.8-1</version>
        <exclusions>
            <exclusion>
                <groupId>org.apache.httpcomponents</groupId>
                <artifactId>httpclient</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.hibernate</groupId>
                <artifactId>hibernate-validator</artifactId>
            </exclusion>
            <exclusion>
                <groupId>io.dropwizard.metrics</groupId>
                <artifactId>metrics-core</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.slf4j</groupId>
                <artifactId>log4j-over-slf4j</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-log4j12</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.reflections</groupId>
                <artifactId>reflections</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>io.dropwizard</groupId>
        <artifactId>dropwizard-core</artifactId>
        <version>1.3.8</version>
        <exclusions>
            <exclusion>
                <groupId>io.dropwizard.metrics</groupId>
                <artifactId>metrics-annotation</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-api</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.slf4j</groupId>
                <artifactId>log4j-over-slf4j</artifactId>
            </exclusion>
            <exclusion>
                <groupId>com.google.code.findbugs</groupId>
                <artifactId>jsr305</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.21</version>
    </dependency>
    <dependency>
        <groupId>io.dropwizard</groupId>
        <artifactId>dropwizard-migrations</artifactId>
        <version>1.3.8</version>
    </dependency>
    <dependency>
        <groupId>io.dropwizard</groupId>
        <artifactId>dropwizard-hibernate</artifactId>
        <version>1.3.8</version>
    </dependency>
    <dependency>
        <groupId>io.dropwizard</groupId>
        <artifactId>dropwizard-testing</artifactId>
        <version>1.3.8</version>
        <exclusions>
            <exclusion>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.mockito</groupId>
                <artifactId>mockito-core</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.objenesis</groupId>
                <artifactId>objenesis</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.glassfish.jersey.core</groupId>
                <artifactId>jersey-client</artifactId>
            </exclusion>
        </exclusions>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>com.hubspot.dropwizard</groupId>
        <artifactId>dropwizard-guice</artifactId>
        <version>0.8.4.0</version>
        <exclusions>
            <exclusion>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-api</artifactId>
            </exclusion>
            <exclusion>
                <groupId>io.dropwizard</groupId>
                <artifactId>dropwizard-core</artifactId>
            </exclusion>
            <exclusion>
                <groupId>io.dropwizard</groupId>
                <artifactId>dropwizard-jackson</artifactId>
            </exclusion>
            <exclusion>
                <groupId>io.dropwizard</groupId>
                <artifactId>dropwizard-jersey</artifactId>
            </exclusion>
            <exclusion>
                <groupId>io.dropwizard</groupId>
                <artifactId>dropwizard-jetty</artifactId>
            </exclusion>
            <exclusion>
                <groupId>io.dropwizard</groupId>
                <artifactId>dropwizard-lifecycle</artifactId>
            </exclusion>
            <exclusion>
                <groupId>io.dropwizard</groupId>
                <artifactId>dropwizard-servlets</artifactId>
            </exclusion>
            <exclusion>
                <groupId>com.google.inject</groupId>
                <artifactId>guice</artifactId>
            </exclusion>
            <exclusion>
                <groupId>io.dropwizard.metrics</groupId>
                <artifactId>metrics-healthchecks</artifactId>
            </exclusion>
            <exclusion>
                <groupId>com.google.guava</groupId>
                <artifactId>guava</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>com.palominolabs.metrics</groupId>
        <artifactId>metrics-guice</artifactId>
        <version>3.1.3</version>
        <exclusions>
            <exclusion>
                <groupId>io.dropwizard.metrics</groupId>
                <artifactId>metrics-core</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-api</artifactId>
            </exclusion>
            <exclusion>
                <groupId>io.dropwizard.metrics</groupId>
                <artifactId>metrics-healthchecks</artifactId>
            </exclusion>
            <exclusion>
                <groupId>com.google.inject</groupId>
                <artifactId>guice</artifactId>
            </exclusion>
            <exclusion>
                <groupId>com.google.code.findbugs</groupId>
                <artifactId>jsr305</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>io.dropwizard.metrics</groupId>
        <artifactId>metrics-core</artifactId>
        <version>4.0.1</version>
    </dependency>
    <dependency>
        <groupId>io.dropwizard</groupId>
        <artifactId>dropwizard-forms</artifactId>
        <version>0.9.2</version>
    </dependency>
    <dependency>
        <groupId>flipkart.feeds</groupId>
        <artifactId>commons</artifactId>
        <version>1.0.0</version>
        <!--<scope>compile</scope>-->
        <exclusions>
            <exclusion>
                <groupId>com.codahale.metrics</groupId>
                <artifactId>metrics-core</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>com.google.guava</groupId>
        <artifactId>guava</artifactId>
        <version>24.1.1-jre</version>
    </dependency>
    <dependency>
        <groupId>io.dropwizard.metrics</groupId>
        <artifactId>metrics-annotation</artifactId>
        <version>4.0.5</version>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
    </dependency>
    <dependency>

Не в состоянии понять, почему это должно вызывать какие-либо проблемы и как решить эту проблему, изменить кое-что здесь и там, но это не помогло.

1 Ответ

0 голосов
/ 21 июня 2019

Не уверен, что это точно такая же проблема, но я видел некоторые странные вещи с Guice и перехватчиками, где исключения не соответствуют тому, что на самом деле происходит. В моем конкретном случае исключение было другим, но основная проблема заключалась в том, что поля @Inject моего перехватчика не вводились.

Итак, мой перехватчик генерировал исключение NullPointerException, но мой Api видел какое-то другое случайное исключение от другого перехватчика над ним. Мы должны были разрешить базовый (скрытый) NPE, поэтому вместо:

bindInterceptor(Matchers.any(), Matchers.annotatedWith(Action.class), new MyInterceptor());

Я должен был поставить:

ServiceInfoInterceptor siInterceptor = new ServiceInfoInterceptor();
requestInjection(siInterceptor);
bindInterceptor(Matchers.any(), Matchers.annotatedWith(ServiceInfo.class), siInterceptor);

Это привело к тому, что мой ServiceInfoInterceptor имел ненулевые члены, очистив исключение NullPointerException и очистив другое случайное исключение, которое было выброшено на его место.

...