Announcement Announcement Module
Collapse
No announcement yet.
Intercepting all methods of an interface Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Intercepting all methods of an interface

    Hi,

    I want to intercept all methods of an interface. OK, no problem - implement a MethodInterceptor - done.

    But my interceptor should implement this interface too. How can I dispatch the methods of my adviced class to the methods of my interceptor?

    Code:
    interface Foo {
     Object method1(Object o, String s);
     void method2(Date d, int i);
    }
    
    class FooImpl implements Foo {
     Object method1(Object o, String s) {...}
     void method2(Date d, int i) {...}
    }
    
    class FooInterceptor implements MethodInterceptor, Foo {
     Object invoke(MethodInvocation methodinvocation) throws Throwable {
     // how can I dispatch here automatically to method1 and method2?
     }
    
     Object method1(Object o, String s) {...}
     void method2(Date d, int i) {...}
    
    }
    Thank you

  • #2
    Originally posted by spgmx View Post
    Hi,

    I want to intercept all methods of an interface. OK, no problem - implement a MethodInterceptor - done.

    But my interceptor should implement this interface too. How can I dispatch the methods of my adviced class to the methods of my interceptor?

    Code:
    interface Foo {
     Object method1(Object o, String s);
     void method2(Date d, int i);
    }
    
    class FooImpl implements Foo {
     Object method1(Object o, String s) {...}
     void method2(Date d, int i) {...}
    }
    
    class FooInterceptor implements MethodInterceptor, Foo {
     Object invoke(MethodInvocation methodinvocation) throws Throwable {
     // how can I dispatch here automatically to method1 and method2?
     }
    
     Object method1(Object o, String s) {...}
     void method2(Date d, int i) {...}
    
    }
    Thank you
    You are introducing recursion here that will never end... You are intercepting on Foo via interceptor that is also Foo. so you'll just keep recursing without an end in sight...

    Comment


    • #3
      My pointcut will be on FooImpl not on Foo.

      Comment


      • #4
        Originally posted by spgmx View Post
        My pointcut will be on FooImpl not on Foo.
        why is the interceptor implementing Foo interface?

        Comment


        • #5
          Because it shall intercept every Foo method.

          Comment


          • #6
            Originally posted by spgmx View Post
            Because it shall intercept every Foo method.
            just take it out, you just need to implement method interceptor. you'll setup what you are intercepting (Foo) through Spring.

            Comment


            • #7
              OK, I can do this, but the main question is still not answered:

              How can I dispatch the methods of my adviced class to the methods of my interceptor?

              if then else?

              Comment


              • #8
                What is it that your interceptor should do?! Why create an implementation if the real implementation is your interceptor. I don't understand what you are trying to do.

                Comment


                • #9
                  I want to inspect/manipulate the method arguments and then delegate to the impl class or reject the call.

                  But here is still a bug in my concept. This would lead to an endless loop...

                  Hm...

                  Comment


                  • #10
                    So then implement it that way... You are making it way to complex....

                    Your MethodInterceptor can do just that... Have you actually looked at the documentation of the MethodInterceptor and MethodInvocation class?!

                    Code:
                    import org.aopalliance.intercept.MethodInterceptor;
                    import org.aopalliance.intercept.MethodInvocation;
                    import org.springframework.aop.framework.ReflectiveMethodInvocation;
                    
                    
                    public class FooInterceptor implements MethodInterceptor {
                    
                    	@Override
                    	public Object invoke(MethodInvocation invocation) throws Throwable {
                    		ReflectiveMethodInvocation method = (ReflectiveMethodInvocation) invocation;
                    		Object[] arguments = method.getArguments();
                    		//modify arguments
                    		method.setArguments(arguments);
                    		if (ok) {
                    			method.proceed();
                    		} else {
                    			return null; // or throw an exception
                    		}
                    	}
                    
                    }
                    But why do it this way, using an AspectJ aspect would make it much easier.

                    Code:
                    @Aspect
                    public class FooInterceptor {
                    
                    	@Pointcut("execution(* *..Foo+.*(..))")
                    	void fooMethods() {}
                    	
                    	@Around("fooMethods()")
                    	public Object intercept(ProceedingJoinPoint pjp) {
                    		Object[] arguments = pjp.getArgs();
                    		//change arguments
                    		if (ok) {
                    			pjp.proceed(arguments);
                    		} else {
                    			return null; // or throw an exception
                    		}
                    	}
                    }
                    Put it in your application context, include <aop:aspectj-autoproxy /> and presto...

                    Comment


                    • #11
                      Hi all,

                      I need to intercept all the handleRequest method of a webapp controller, but I'm not able to do so even if I tried to follow a lot of example about Spring AOP.

                      Here are my advice class:

                      package it.esel.ge.aop;

                      import org.aspectj.lang.ProceedingJoinPoint;
                      import org.aspectj.lang.annotation.Around;
                      import org.aspectj.lang.annotation.Aspect;
                      import org.aspectj.lang.annotation.Pointcut;

                      @Aspect
                      public class ValidUserSessionAdvice {

                      @Pointcut("execution(* *..handle+.*(..))")
                      public void inControllers() {}

                      @Around("inControllers()")
                      public Object doValidation(ProceedingJoinPoint pjp) throws Throwable {
                      Object[] arguments = pjp.getArgs();
                      System.out.println(arguments[0].getClass().getName());
                      return pjp.proceed(arguments);
                      }

                      }

                      My application context has already the include <aop:aspectj-autoproxy />, but when a controller execute (no matter what the type is) the advice does nothing.

                      I have another aspect tha log every exception and it's work. Here is the code:

                      package it.esel.ge.aop;

                      import java.util.HashMap;
                      import java.util.Map;

                      import it.esel.ge.businessobjects.oggetticondivisi.Generi cClass;
                      import it.esel.ge.utilita.CastUtils;
                      import it.esel.ge.utilita.mail.sender.IAdministrativeMail Sender;

                      import org.apache.velocity.app.VelocityEngine;
                      import org.aspectj.lang.ProceedingJoinPoint;
                      import org.aspectj.lang.annotation.AfterThrowing;
                      import org.aspectj.lang.annotation.Aspect;
                      import org.springframework.ui.velocity.VelocityEngineUtil s;

                      @Aspect
                      public class ExceptionsLoggingAdvice extends GenericClass {

                      private static IAdministrativeMailSender mailService;
                      private static VelocityEngine velocityEngine;

                      private static final String E_MAIL_VELOCITY_TEMPLATE = "supporto/velocity/eMailAlertEccezione.vm";
                      private static final String E_MAIL_SUBJECT_KEY = "mail.admin.eccezione.oggetto";
                      private static final String DEFAULT_EMPTY_STRING = getProperty("visualizzazione.dettagli.valore.non.d isponibile");

                      public void setMailService(IAdministrativeMailSender mailUtils) {
                      ExceptionsLoggingAdvice.mailService = mailUtils;
                      }

                      public void setVelocityEngine(VelocityEngine velocityEngine) {
                      ExceptionsLoggingAdvice.velocityEngine = velocityEngine;
                      }

                      @AfterThrowing(pointcut="within(it.esel.ge..*)", throwing="ex")
                      public void doExceptionLogging(ProceedingJoinPoint pjp, Throwable ex) {
                      Map<String, String> exceptionReport = new HashMap<String, String>();
                      exceptionReport.put("sourceClassName", CastUtils.nullStringToDefaultTemplate(getTargetCla ssName(pjp)));
                      exceptionReport.put("methodSignatureName",
                      ....

                      Could someone help me?

                      Thanks.

                      Riccardo.

                      Comment


                      • #12
                        you pointcut

                        Code:
                        @Pointcut("execution(* *..handle+.*(..))")
                        public void inControllers() {}
                        is not correct. your poincut as written will intercept any method of class called handle and any of the class below it in the hierarchy. try

                        Code:
                        @Pointcut("execution(* *..handleRequest(..))")
                        public void inControllers() {}
                        if you want advice on any handleRequest method invocation (warn: this may include non-web controllers that just happen to have handleRequest() method.

                        Comment


                        • #13
                          Hi bdangubic,

                          Thank you for the reply.

                          I corrected the pointcut, but nothing has changed.

                          Maybe it's my controller definition that it's incorrect?

                          The controller is as follow:
                          package it.esel.ge.controllers;

                          import java.util.HashMap;
                          ...
                          import it.esel.ge.utilita.constants.Constants;

                          public class RicercaController extends AWController {

                          private final static String QUERY_INFO_MESSAGE = "Query ricerca dati: ";

                          private ProfiloRicerca profiloRicerca;
                          private String ricercaLike = null;
                          private String colonnaOrderBy = null;
                          private IJoinsService tableJoinsService;


                          /*
                          * Riccardo Foraf˛
                          * Mar 7, 2008
                          *
                          * (non-Javadoc)
                          * @see it.esel.ge.controllers.base.AWController#handleReq uest(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
                          */
                          public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {

                          Map<Object, Object> model = new HashMap<Object, Object>();
                          ModelAndView modelAndView = null;
                          String ricerca = request.getParameter(getProperty("pagina.utente.cr iteri.ricerca.namePulsanteRicerca"));
                          ...
                          and it's extend the AWController class:
                          public class AWController extends ApplicationObjectSupport implements Controller {

                          protected static ReloadableResourceBundleMessageSource propertiesRepository;
                          protected static MessageSource staticPropertiesRepository;

                          ...

                          protected String sortProperty;
                          protected boolean sortIgnoreCase;
                          protected boolean sortAscending;

                          public AWController() {
                          super();
                          }

                          public void setPropertiesRepository(ReloadableResourceBundleMe ssageSource propertiesRepository) {
                          AWController.propertiesRepository = propertiesRepository;
                          }

                          ...
                          Best regards,

                          Riccardo.

                          Comment


                          • #14
                            Please use [ code][/code ] tags when posting code!!!! That way it remains readable!!!

                            Your pointcut is still flawed.

                            Code:
                            @Pointcut(execution(* *..*Controller+.handleRequest(..))
                            public void handleRequest(){}
                            Also notice that there is onle 1 method you can intercept using Spring AOP, that is handleRequest...

                            Comment


                            • #15
                              Yes of course.
                              But I have to find out which method is called, which ends in somewhat like this:

                              Code:
                              if (methodname.equals("method1")) {
                              ...
                              }
                              else if (methodname.equals("method2")) {
                              ...
                              }
                              What I was looking for was an "automatic" dispatch from invoke to method1, method2, nothing with if-then-else and strings.

                              The problem with the approch above is, that is it not refactorable and not type safe.

                              Comment

                              Working...
                              X