users@hk2.java.net

Re: Question about hk2 interceptors

From: <cdr53x_at_free.fr>
Date: Wed, 24 Sep 2014 16:56:15 +0200 (CEST)

Hi,

Maybe this can help : https://github.com/mycom-int/jersey-guice-aop


----- Mail original -----
De: "Diogo Guerra" <diogoeag_at_gmail.com>
À: users_at_hk2.java.net
Envoyé: Lundi 22 Septembre 2014 17:58:26
Objet: Question about hk2 interceptors




Hi Everyone,

I had to upgrade my jersey -guice project from 1.17 to the latest 2.12 version.

In fact we were not using any special injection from Guice, only interception to do authorization and logging.

However what we had was intercepting all the methods of classes of our resources with the following code in our Guice Module: bindInterceptor(Matchers.inSubpackage("com.company.web.resources"), Matchers.any(), new TracingInterceptor());

With jersey 2 and the new dependency injection system, I couldn’t get the guice incterceptors working. It seems that the hk2-guice bridge is only to injection not to interception.

Then I started to look at the code needed for interception with hk2.

I got to this point:

An interception service: public class MyInterceptionService implements InterceptionService {

    private static List<MethodInterceptor> trace = Arrays.asList(new TracingInterceptor());
    private static String targetPackageName = "com.company.web.resources";

    @Override

    public Filter getDescriptorFilter() {
        return BuilderHelper.allFilter();
    }

    @Override
    public List<MethodInterceptor> getMethodInterceptors(Method method) {
        if (method.isSynthetic()) {
            return null;
        }

        String classPackageName = method.getDeclaringClass().getPackage().getName();
        if (!classPackageName.equals(targetPackageName)
                && !classPackageName.startsWith(targetPackageName + ".")) {
            return null;
        }

        return trace;
    }

    @Override
    public List<ConstructorInterceptor> getConstructorInterceptors(Constructor<?> constructor) {
        return null;
    }

Bind the interception service register(new AbstractBinder() {
            @Override
            protected void configure() {
                bind(MyInterceptionService.class).to(InterceptionService.class).in(Singleton.class);
            }
        });

However I have two questions:

It seems that it is not possible to bind an instance of an InterceptionService but only the class. How can we configure an InterceptionService? In this case, how can we pass the package name to MyInterceptionService? Otherwise Ii will have to write a new class for each of my web applications to use my TracingInterceptor?
Is there any simpler way to do this? With guice set up an Interceptor with 1 linee of code, with HK2 I need 30+ lines of code and I can’t reuse the code.

Thanks,
--Diogo