Java Intercepting the calls to an Interface Method - java

I need to intercept the calls to all the method calls to an Interface. I've gone through the Java Dynamic Proxies however that will not help me. I'm not even sure whether this can be achieved, but thought of confirming.
So basically lets say i have an interface as follows:
public interface Foo {
public String getValue();
}
I would like to intercept all the calls to getValue() from whichever implementations of Foo. Problem is i do not have control over the different implementations of Foo, because of which i cant use Dynamic Proxies.
Is there a way i can do this?
Thanks.

AOP might help, but as you've discovered, it all gets much easier if you're in control of the object creation (even if only through a DI framework like Spring or Guice).
Another alternative is compile-time byte-code weaving - that is, finding all implementations and altering them to have your interception code in them at compile time.
A third alternative would be to look at using either an agent or a custom classloader to do weaving as the classes are loaded into the system. This is load-time weaving. But if you're in, say, a web container where you're not fully in charge of the classloaders, this might be tricky.

The only way to do this would be with a custom classloader that replaces the implementation classes with a proxy.
It might be possible to do this out-of-the-box with Spring AOP's load-time weaving.

Related

Osgi annotation processing

I have a component declared using the #Component annotation, in which there is a set of methods that implement communication with another api, in my product there are operations that are prohibited for a user with an anonymous id. I want to create an annotation, for example #ProhibitedForAnonym, which, every time the method is called, will check the ID of the anonymous customer, with the ID in the method parameter and throw an error if the IDs match. But I don't understand how to do annotation processing in OSGI, maybe some kind of interceptor?
There is no general interception framework in OSGi. However, you could do interception in the following ways:
Don't. Personally, I feel that since we've lambdas a code-based solution has won hands on over a 'magic' annotation check. It is about the same number of characters but a lambda based call allows me to single step, provide context to the security check, does not suffer from the THIS problem, is testable, and requires no complex framework with lots of bug opportunities.
Use the byte code weaving support in OSGi. You need to register a weaver early and then weave any class that has these annotations. You can take a look at https://github.com/aQute-os/biz.aQute.osgi.util/tree/master/biz.aQute.trace for an example of how to use the byte code weaver. Make sure your weaver is there first. If you use bndtools you can add it to the -runpath to run before anybody else. Or use start levels.
Use proxying. You can 'hide' and original service with the Service Hooks and then register a proxy. In the proxy you can then do the annotation check. This also requires that this code runs first and cannot be updated. I think the spec has an example of this
You might want to read: https://www.aqute.biz/appnotes/interceptors.html

Is it a bad idea to use #RequestMapping in interface?

I checked out this SO Post which discusses using RequestMapping in interface. Although the post contains ways to achieve this but it does not mention the pros and cons of doing this.
Architecture wise , is this a bad idea to use controller as interface?
What benefit will we achieve in terms of polymorphism for controller?
There is nothing wrong with putting #RequestMapping on the interface. However make sure you have the right reasons to do it. Polymorphism is probably not a good reason, you will not have a different concrete implementation swapped in at runtime or something like that.
On the other hand, for example, Swagger codegen generates interfaces with #RequestMapping and all the annotations on the methods, fields and return types (together with #Api definitions etc.). Your controller then implements this interface. In this case it makes a lot of sense because it is just enforcing you to respect the Swagger / OpenAPI interface definition originally defined in Yaml. There is a nice side-effect that it makes your controller much cleaner. (Clients can also use the same Yaml to generate their own client stubs for their own language frameworks).
If you opt to do this, make sure you use the latest version of the Spring Framework, because there were some bugs which were fixed only very recently, where not all annotations were being inherited.
https://github.com/spring-projects/spring-framework/issues/15682
If you are stuck with an older Spring version, you might need to repeat the same annotations in your controller.
So, the real reason this would make sense is to enforce the interface contract, and separate the interface definition (together with any information pertaining to the interface) from the actual concrete implementation.
While some arguments against this are that
the request mapping is an implementation detail, or
since you only have one active controller implementation, you might as well put it on the implementation,
(others will probably be provided in different answers soon,)
I was recently faced with the same decision to put jax-rs annotations on the interface or the implementation. So, since everything always "depends" on some context, I want to give you an argument for putting the RequestMapping (or e.g. #Path, etc if not using spring) on the interface:
If you are not using HATEOAS or discovering the endpoints via some other means, the endpoint url, http method, etc. are usually fixed and a static part of your backend API. Therefore, you might as well put it on an interface. This was the case for me because I control both the client and the server side.
The controller usually has only one active implementation, so the reason for doing so is not polymorphism. But your implementation usually has a lot more dependencies than the plain interface. So if you export/provide only your interface to clients (e.g. in a seperate jar/java project/...), you only provide things that the clients really require. In my specific case, I delivered the annotated interface so that a client implementation could can it using a Rest-Client-Library and detect the endpoint paths automatically.

How to configure Spring AOP to use AspectJ

I want to use AOP concept to time execution time of some methods that I mark with an annotation that I created. My problem however is that I refer to the annotated method internally, from within the same class. For example:
public void login(params) {
some logic ...
performLogin();
some logic ...
}
#Measured
public void performLogin() {
some logic ...
}
This is a known issue caused by the fact that Spring AOP is using proxy based approach that does not "see" the internal calls within the same class. Apparently I can solve this situation by using AspectJ instead of Spring AOP. If I understand correctly, it can be configured from within Spring itself. From what I found, it looks like I should include #EnableAspectJAutoProxy annotation to configure Spring to use AspectJ instead of its own AOP. Unfortunately, it did not help and after adding the annotation, the interception of the annotated method did not occur.
There is a lot of information on this topic in Spring reference documentation and I got a bit lost. Is there anything else I am supposed to do so that AspectJ will be used?
P.S. Please note that I cannot refactor the whole class and move the calling method outside.
P.P.S. I also verified my pointcut configuration. I annotated the calling method which is invoked externally and it worked fine.
Proxies can only achieve a sub-set of the full capabilities of the actual AspectJ system, basically advice that wraps methods. Due to their nature proxies have following limitations:
interception on external calls only (while breaching proxy boundary)
interception on public members only (private/protected can't be intercepted)
unawareness to local calls (or calls with this or super)
<aop:aspectj-autoproxy /> is not enough - it only wraps methods, you need something like this: <context:load-time-weaver/>
If you want to be able to advise fields for example, you would need to enable the use of Native AspectJ.

GWT.create(Class<?>) vs. GIN?

It looks like GWT has its own baked-in DI mechanism (GWT.create(Class<?>)). What benefits does GIN offer on top of this? Should you ever use them in conjunction with one another, or are they mutually exclusive? I like Guice so I'm tempted to use GIN, but don't want to introduce it if GWT already does the same stuff right out of the box.
Gin and GWT.create have a few differences - Gin is more about providing dependencies via the #Inject annotation, either on fields, setters, or the constructor, whereas GWT.create is specifically about obtaining an implementation. Gin will use any constructor you provide, but you must specifically provide the replacement type, whereas GWT.create will only work with a default constructor, and your 'rebind rules' don't need to be quite as precise, and can even cause new classes to be created at compile time. It also is able to look at what environment the user is running and select a specific set of rules based on that, which Gin is not able to do.
Gin actually makes use of GWT.create to get these other features - if you don't have a rule defined, Gin will call GWT.create automatically. This means if you have a rule like
#Inject MyRemoteServiceAsync rpcService;
Gin will call GWT.create to build that rpc call. This also works for UiBinder, Editor Drivers, I18n Messages and Constants, etc.
If you already understand and like Guice, Gin shouldn't be a big step for you, and you'll still have the ability to directly invoke GWT.create, or implicitly ask Gin to do it. In fact, in order to even use Gin, you need to call GWT.create(MyGinjector.class) to get the ball rolling.
GWT.create() has nothing to do with dependency injection. It's a factory method.
The only difference between GWT.create(SomeThing.class) and new SomeThing() is that the exact SomeThing class can be replaced or generated using so-called deferred binding. But there's nothing in GWT.create() about providing dependencies to the GWT.create()d object for instance.

Adding validations to Java Beans via Annotations

I want to add validations to a Java Bean. For example, I want to do the following:
#MaxLength(50)
#RequiredField
public void setEmployeeName(String name){
.....
}
I know I can write code that gets the validations for a specific method by calling method.getDeclaredAnnotation after all the bean values have been set. I would like to avoid writing this code
Is there anything in Java6 that gives standard validations via annotations? Do I need aspectj to invoke these annotations?
thanks in advance.
You can use Bean Validation Framework. Here is short overview
http://relation.to/Bloggers/BeanValidationSneakPeekPartI
take a look at JSR 303. The RI (Reference Implementation) is here, with also a nice tutorial. And no, you don't need AspectJ.
The only way you'll be able to do this is through reflections and a custom validation utility/interceptor/proxy. JSR 303 and JSR 305 were proposed to introduce similar functionality, but nothing like this exists.
One of the problems you'll run into is that these annotations need to be handled at some sort of framework level, or at a minimum, intercepted before some sort of invoked action. The two most common sense, brute force ways of doing this would be done either by creating a utility, or by validating pre-invoke in an invocation handler (proxy).
The reality is that unless this is built into Spring, Struts, Guice, Java itself, etc., you're just creating unnecessary overhead and you're better off checking for validation bounds on demand.

Categories