fails to instrument threadPoolExecutor by bytebuddy - byte-buddy

I encounter the same problem with this post.
https://stackoverflow.com/questions/49321938/instrument-in-java-level-using-byte-buddy/55032131#55032131
when I use the code instrument threadpoolexecutor,
new AgentBuilder.Default()
.ignore(ElementMatchers.none())
.type(ElementMatchers.nameContains("ThreadPoolExecutor"))
.transform((builder, type, classLoader, module) -> builder
.visit(Advice.to(ThreadPoolExecutorAdvice.class).on(ElementMatchers.any()))
).installOn(instrumentation);
I got this error, How to solve it?
java.lang.IllegalStateException: Cannot represent public org.apache.tomcat.util.threads.ThreadPoolExecutor(int,int,long,java.util.concurrent.TimeUnit,java.util.concurrent.BlockingQueue,java.util.concurrent.RejectedExecutionHandler) as given method constant

You are probably trying to get a Method instance injected while you are instrumenting a Constructor. Switch the parameter type and it should work out.

Related

ByteBuddy - rebase already loaded class

I have the following code working in a SpringBoot application, and it does what's I'm expecting.
TypePool typePool = TypePool.Default.ofClassPath();
ByteBuddyAgent.install();
new ByteBuddy()
.rebase(typePool.describe("com.foo.Bar").resolve(), ClassFileLocator.ForClassLoader.ofClassPath())
.implement(typePool.describe("com.foo.SomeInterface").resolve())
.make()
.load(ClassLoader.getSystemClassLoader());
Its makes is so that the class com.foo.Bar implements the interface com.foo.SomeInterface (which has a default implementation)
I would like to . use the above code by referring to the class as Bar.class, not using the string representation of the name. But if I do that I get the following exception.
java.lang.UnsupportedOperationException: class redefinition failed: attempted to change superclass or interfaces
I believe due to the fact that it cause the class to be loaded, prior to the redefinition. I'm just now learning to use ByteBuddy.
I want to avoid some reflection at runtime, by adding the interface and an implementation using ByteBuddy. I've some other code that checks for this interface.
This is impossible, not because of Byte Buddy but no tool is allowed to do this on a regular VM. (There is the so-called dynamic code evolution VM which is capable of that).
If you want to avoid the problem, use redefine rather then rebase. Whenever you instrument a method, you do now however replace the original.
If this is not acceptable, have a look at the Advice class which you can use by the .visit-API to wrap logic around your original code without replacing it.

Javassist NotFoundException when getting java.io.Serializable with JDK9

I have the following code:
private static CtClass resolveCtClass(String clazz) throws NotFoundException {
ClassPool pool = ClassPool.getDefault();
return pool.get( clazz );
}
When running under JDK8, if this method is called using java.io.Serializable, it works, but when running under the JDK9 environment, it throws the NotFoundException.
Is there something I overlooked here?
This does no longer happen with the current EA builds of Java 9. Class files are now always locatable even if they are encapsulated in a module.
This is a consequence of Java 9's module encapsulation where non-exported resources are no longer available via the ClassLoader API. Under the covers, Javassist calls
ClassLoader.getSystemClassLoader().findResource("java/io/Serializable.class");
to get hold of the class file for Serializable. It then parses this class file and represents the information similarly to the Java reflection API but without loading the class such that it can be edited prior to loading it.
Until Java 8, this class file was accessible as most class loaders rely on looking up a class file before loading it such that the above call returned a URL pointing to the file. Since Java 9, resources of named modules are only available via the new API method findResource(String, String) where the second arguments names the module of that class.
The short answer is: Javassist does no longer work with Java 9 and none of its dependant projects will. This is a known issue with the current Java 9 implementation and will hopefully be fixed prior to release.
(I never used Javassist so I'm just shooting in the dark, here...)
The documentation of ClassPool says:
If get() is called on this object, it searches various sources represented by ClassPath to find a class file and then it creates a CtClass object representing that class file.
This seems to be bound to the concept of the class path. Looking at ClassPath and CtClass supports that assumption.
If that is the case, then Javassist might just not be fit to look into JDK 9's brand new modules.
If my guess is correct, you should not be able to get any JDK class from the pool. This should be easily verifiable.

Ninject MockingKernel with Saboteurs

Is it possible to use MockingKernel so that it generates mock objects automatically that, if interacted with, will throw an exception (a.k.a, saboteurs)?
This is useful when you want to get an object with various dependencies, but you know your code should only be interacting with some of them. If you don't explicitly Bind a dependency (via ToMock, etc.), it should return an object that throws an exception the first time it is interacted with.
This is much better than waiting until the code finishes executing, then writing a bunch of checks to make sure you didn't call into a mock.
Does this already exist?
The answer provided above did not indicate how to setup the Ninject MockingKernel using MOQ so that the default behavior is Strict. For the benefit of others, here is what I found.
The Ninject.MockingKernel.Moq namespace provides the class NinjectSettingsExtensions with the methods SetMockBehavior() and GetMockBehavior() that allow you to specify which mocking behavior to use as the global default. I have NOT been able to find any way to override the default for an individual GetMock() request.
using Ninject;
using Ninject.MockingKernel.Moq;
var kernelSettings = new NinjectSettings();
kernelSettings.SetMockBehavior(MockBehavior.Strict);
using(var kernel = new MoqMockingKernel(kernelSettings))
{
var mockFoo = kernel.GetMock<IFoo>(); // mockFoo.Behavior == MockBehavior.Strict
}
I had been using NSubstitute's implementation of MockingKernel. NSubstitute doesn't really support a "strict" mode and you can't configure it through the NSubstituteMockingKernel class.
However, you can configure Moq to do strict mode. Best of all, the MoqMockingKernel class allows you to change the mock behavior globally. This way, any calls that aren't configured result in an exception being thrown.
This is exactly what I was looking for. The only pain was switching from NSubstitute to Moq.

adapter pattern and dependency

I have little doubt about adapter class. I know what's the goal of adapter class. And when should be used. My doubt is about class construction. I've checked some tutorials and all of them say that I should pass "Adaptee" class as a dependency to my "Adapter".
e.g.
Class SampleAdapter implements MyInterface
{
private AdapteeClass mInstance;
public SampleAdapter(AdapteeClass instance)
{
mInstance=instance;
}
}
This example is copied from wikipedia. As you can see AdapteeClass is passed to my object as dependency. The question is why? If I'm changing interface of an object It's obvious I'm going to use "new" interface and I won't need "old" one. Why I need to create instance of "old" class outside my adapter. Someone may say that I should use dependency injection so I can pass whatever I want, but this is adapter - I need to change interface of concrete class. Personally I think code bellow is better.
Class SampleAdapter implements MyInterface
{
private AdapteeClass mInstance;
public SampleAdapter()
{
mInstance= new AdapteeClass();
}
}
What is your opinion?
I would say that you should always avoid the new operator in a class when it comes to complex objects (except when the class is a Builder or Factory) to reduce coupling and make your code better testable. Off course objects like a List or Dictionary or value objects can be constructed inside a class method (which is probably the purpose of the class method!)
Lets say for example that your AdapteeClass is a Remote Proxy. If you want to use Unit Testing, your unit tests will have to use the real proxy class because there is no way to replace it in your unit tests.
If you use the first approach, you can easily inject a mock or fake into the constructor when running your unit test so you can test all code paths.
Google has a guide on writing testable code which describes this in more detail but some important points are:
Warning Signs for not testable code
new keyword in a constructor or at field declaration
Static method calls in a constructor or at field declaration
Anything more than field assignment in constructors
Object not fully initialized after the constructor finishes (watch out for initialize methods)
Control flow (conditional or looping logic) in a constructor
Code does complex object graph construction inside a constructor rather than using a factory or builder
Adding or using an initialization block
AdapteeClass can have one or more non-trivial constructors. In this case you'll need to duplicate all of them in your SampleAdapter constructor to have the same flexibility. Passing already constructed object is simpler.
I think creating the Adaptee inside the Adapter is limiting. What if some day you want to adapt a pre-existing instance?
To be honest though, I'd do both if at all possible.
Class SampleAdapter implements MyInterface
{
private AdapteeClass mInstance;
public SampleAdapter()
: base (new AdapteeClass())
{
}
public SampleAdapter(AdapteeClass instance)
{
mInstance=instance;
}
}
Let's assume you have an external hard drive with a regular USB port and you are trying to hook it up with a Mac which only has type-c ports. Yes, you can buy a new drive which has a type-c port but what about the data in it?
It's the same for the adapter pattern. There're times you initialize AdapteeClass with tons of flavors. When you do the conversion, you want to keep all the context.

Is it possible to get the Extension class loader object?

I'm learning about ClassLoading concepts in java.
I know that can get the System classLoader with ClassLoader.getSystemClassLoader() method using java.lang.ClassLoader class. Is it possible to get Extension class loader also?
I'm aware that JVM loads the BootStrapClassLoader and we cannot instantiate it. But what about Extension class loader?
Thanks in Advance.
You can try this one sun.net.spi.nameservice.dns.DNSNameService.getClassLoader(). DNSNameService is one the class that exist as the Extension class loader.
Another option is to write something like this:
ClassLoader cl =new Object(){}.getClass().getEnclosingClass().getClassLoader();
ClassLoader prev = null;
while(cl!=null){
prev=cl;
cl=cl.getParent();
}
System.out.println(prev);
prev will contain reference to extension class loader.
Note: You can write besides
new Object(){}.getClass().getEnclosingClass().getClassLoader() idiom Thread.currentThread().getContextClassLoader() or even simpler YourClassName.class.getClassLoader() While these idioms are not identical any of them will do the job.
See http://www.javacodegeeks.com/2011/03/understanding-extending-java.html for some more details.