Java JSR-303 Automatic Bean Validation without Byte Code Weaving - java

Is there a way to perform (more or less) "automatic" JSR-303 java bean validation without runtime modification of a class?
Usually I see people using AspectJ to accomplish this, but we have had so many complications when using runtime code weaving (like with cofoja) that I'd like to avoid it. It makes a lot of our build tools fail because the runtime class files were different than the class files on disk.
I've looked at dynamic proxies via reflection which can only proxy interfaces (public methods) AND if you call anything annotated inside "this", you don't go through the proxy anymore so you lose that validation.
I'v also looked at ByteBuddy for a way to possibly intercept method calls by wrapping/redefining a class. There might be something here but I can't figure out how to intercept private methods or accomplish the above without getting back into modifying the original class.
Any ideas?

In theory, you can enforce bean validation by reflection only. But I assume that by automatic, you mean without an explicit call to a validation method.
In this case, instrumentation is probably your only option. With Byte Buddy, you can instrument existing methods, by using redefinition or rebasing. The easiest way to do so is a Java agent using an agent builder or using the Gradle or Maven plugins for build time instrumentation. The documentation provides an example of how to implement an agent and the build instrumentations have a lot of javadoc (documentation in progress).

Related

How can aspectJ pointcuts be used with dynamic selector?

I'm working on a small project that determines code coverage when testing a java application. It basically consists of a plugin for an IDE which finds all the classes and methods in the project and saves them in a database, and an agent with aspectJ pointcuts that weave around all of these methods to log their execution.
The problem I have is that I only want to log the methods that are actually written by the developers of that very project and not those of underlying libraries. So the pointcuts need to be defined in a way that only methods of classes in the actual project packages are woven. On the other hand, since the agent is to be used with all sorts of projects, I can't hardcode those packages.
My attempt so far was to read all the package names from the database and build a string from that. Basically what it looks like is this:
private static final String POINTCUT_STRING = AspectUtil.buildPointcutString();
And then, when defining the pointcut:
#Pointcut(POINTCUT_STRING)
Thing is, this doesn't work because apparently when defining a Pointcut, the
Attribute value needs to be a constant.
So, how can I make it so that i can only weave methods in classes in the packages that I have in my database?
Thanks in advance, have a good one!
I don't think a dynamic aspect approach is going to work as aspectj does not expose the weaver to any state management or changes. Although this would be theoretically possible at runtime it's definitely not possible at compile time (and you have the option to add your aspects at compile time).
But to your issue...
What weave strategy are you using? compile or runtime? I've found compile to work very well and I'm not sure how to use runtime with aspectj. But what I can say is that if you use compile you'll only be weaving the application classes in any case as that is all you'll have access to.
Another comment to make is if you want to do something dynamic you'd be better off putting the condition on whether to monitor that method for code coverage downstream of the aspect. So when the aspect is executed the first thing it will do is decide if this class/method call should be monitored for coverage and then go on from there...
When I asked you:
What do you mean by "runtime weaving"? Load-time weaving (LTW) maybe? I.e. you are using aop.xml? I am asking for a specific reason.
You replied:
Yes, LTW. I am using an aop.xml file.
In that case you have the option of specifying pointcut definitions in aop.xml which is read during JVM start-up when the weaving agent is activated. For refererence, please read the AspectJ Developers Guide, there is a chapter on LTW. You will find sample code and sample XML definitions there, showing how you can extend an abstract aspect with an abstract pointcut in the XML file and specify a concrete pointut for a concrete subclass. That should give you the options you need to keep your pointcut out of the Java code, for whatever reason you think that's a good thing and you need it.
Please note that you cannot expect to modify aop.xml during runtime and re-load it, possibly re-applying the aspect dynamically to all classes. AspectJ LTW works in connection with class-loading, i.e. you only have one shot at JVM start-up before all application classes are loaded. This is not an AspectJ limitation but just how bytecode instrumentation in the JVM works.

Dynamic object registration in Java

I would like to add some dynamic behavior to an application, preferably without resorting to reflection, so I am looking at object registration.
The approach I am thinking is simple: in a class (say Base) which gets to be loaded early enough, a registry (e.g., a HashMap) of plugin objects will be maintained, each of which will later on be used for invoking some of their methods.
The question is, how to register those plugins in Base without any prior knowledge of their existence (so that the application can be dynamically extended via more such plugins). Not knowing them beforehand means a ClassLoader or any reference to their classes cannot be used, thus even with static initialization, registration code cannot be added (since the plugin classes will not be loaded early enough, so the Base class will start executing without knowing them).
Is there any simple solution to the above scenario?
There's several ways of implementing plugin mechanisms, ultimately you need to either scan for implementations of an interface or annotations. Is it important to you that you implement this yourself? There's already libraries that do this (jspf for example).
If you're not interested in reflection, then the code must either adhere to a known interface. Otherwise you'll need to use reflection somewhere to map between what the plugin class(es) provide, and what the "base" code knows how to call.
could you use something like spring and dependency injection ? if you can, each plug in could be a initializing bean so its loaded on start up and in its init method call back to the base to register itself, if not through a direct dependency injection. that obviously uses reflection in background so not sure if that excludes this as your preferred solution...
on another note, typically, looking for classes is not fool proof esp if you could have multiple class loaders :-(

Dynamic proxy for concrete classes

I want to define a method interceptor in a Java program in other words I want to have a behaviour which is executed at each method call.
This application isn't executed in an application server and therefore I can't use the EJB around invoke interceptors.
I have found a nice Proxy API in the standard Java libraries but its limited because it needs an interface in the proxy creation:
Foo f = (Foo) Proxy.newProxyInstance(Foo.class.getClassLoader(),
new Class[] { Foo.class },
handler);
Is there a similar API which doesn't force Foo.class to be declared as an interface?
Why not use CGLIB ? See this article for more information.
What if you want to proxy legacy classes that do not have interfaces?
You can use CGLIB. CGLIB is a powerful, high-performance code
generation library. Under the cover, it uses ASM, a small but fast
bytecode manipulation framework, to transform existing byte code to
generate new classes. CGLIB is faster than the JDK dynamic proxy
approach. Essentially, it dynamically generates a subclass to override
the non-final methods of the proxied class and wires up hooks that
call back to the user-defined interceptors.
Unfortunately there is no such API for classes. Many frameworks are using bytecode generation libraries like CGLIB to achieve this.
You can try one of the mocking classes. The simplest approach may be to sub-class, your class. Or you could use AOP to inject the logging code you want.
sun.misc.ProxyGenerator can be used to generate proxy classes and doesn't check that their "interfaces" are all interfaces. Its generateClassFile method gives you the bytecode as a byte array, which you can save to link into future builds or alter with third-party tools.
Note that if any of the "interfaces" has a final method, you'll get an error when you try to load the class.

Javassist. What is the main idea and where real use?

I know that Javassist is a Java library providing a means to manipulate the Java bytecode of an application.
Ok, but why we need manipulate bytecode?
Any real example?
Any real app, where javassist used?
A common application is to generate proxy classes at runtime, i.e. to create a subclass at runtime that intercepts all method invocations. Examples:
Hibernate uses Proxies to intercept method invocations on entities to implement lazy loading, i.e. fetching the object from the database when it is first accessed.
The Spring Framework uses Proxies to implement its AOP support, which among other things powers its support for declarative transactions. It also uses proxies to enforce proper scoping.
EJB uses proxies to implement container managed transactions, authorization checking, and to apply user-defined interceptors.
CDI implementations must also proxy the managed beans to ensure proper scoping. I suspect they use a byte code engineering library, too.
I recently used Javassist to implement a transparent cache for method return values, by intercepting all method invocations and only delegating to the super implementation on the first invocation.
Note that java.lang.reflect.Proxy can generate proxy classes at runtime, but can only implement interfaces, not extend a class. All of the above use cases require the proxying of classes.
Bytecode manipulation is useful and necessary, especially when you do not have source code for certain projects. Say you only have the bytecode (like a jar file) for some project, but you want somehow change the behavior of the code, the bytecode manipulation library can help in such cases. The advantage of bytecode manipulation is that you don't need to recompile your code and can directly execute it after manipulation.
I have used bytecode manipulation to do some program analysis. Given a library, I want to know during the runtime what methods in the library have been invoked. I can use bytecode manipulation to insert a System.out.println("method_name"); statement in the beginning of a method. So during the runtime, it will print out what methods have been invoked.
Some bytecode manipulation libraries are:
ASM
ByteBuddy
BCEL
To extend Meriton answer and to provide a real example of use :
Hibernate-core (5.2.8.Final) use javaassit (3.20.0-GA):
https://mvnrepository.com/artifact/org.hibernate/hibernate-core/5.2.8.Final
Users page of the ASM project lists several dozen widely used Java projects and frameworks using ASM for bytecode analysis and manipulation. http://asm.ow2.org/users.html

How is AOP being implemented to Change Java interface content?

I am current using Seasar2 Framework on a project that I am in. The framework is quite popular here in Japan but I am having problem in finding English documentations. Even on their official English translation site, they just discuss that the framework use Dependency Injection and AOP.
I was intrigued with the way they use it in one of their component S2Dao. Basically you only need to create interface DAO class and the framework automatically, changes the code on runtime and creates intermediate class that get called in the middle. Hence DB transactions codes are automatically added to the class. I was wondering, is there any step by step explanation on how this is done? Can java change code on runtime and change the method on runtime?
Are good reference on how this is done? I just want to know how the framework is doing this.
Yes, it is possible to do dynamic implementations of an interface at runtime, and to manipulate the compiled bytecode also.
Java provides a built-in mechanism to implement interfaces at run-time, called dynamic proxy classes.
There are also good libraries like cglib or javassist, that allow you not only to implement interfaces, but also to extend classes and to manipulate bytecode at run-time (to change the behavior of a method, for example). Frameworks like Spring and Hibernate use libraries like these to make their magic, so your framework may be using some of these also.
NOTE: If you are curious, these libraries can "tweak" the bytecode because instead of using the default ClassLoader of the JVM, they load your classes using their own ClassLoader, so they have total control of every single byte of the loaded class, and they can do whatever they want with them :).

Categories