NoClassDefFoundError for a private Enum from a helper class used in Advice - byte-buddy

i'm trying to intercept a handler method from a class using this agent builder
File temp = Files.createTempDirectory("tmp").toFile();
Map<TypeDescription, byte[]> map = new HashMap<>();
map.put(new TypeDescription.ForLoadedType(LambdaHandlerRuntime.class), ClassFileLocator.ForClassLoader.read(LambdaHandlerRuntime.class));
map.put(new TypeDescription.ForLoadedType(Interface.class), ClassFileLocator.ForClassLoader.read(Interface.class));
map.put(new TypeDescription.ForLoadedType(MyLogger.class), ClassFileLocator.ForClassLoader.read(MyLogger.class));
map.put(new TypeDescription.ForLoadedType(Utils.class), ClassFileLocator.ForClassLoader.read(Utils.class));
ClassInjector.UsingInstrumentation.of(temp, ClassInjector.UsingInstrumentation.Target.BOOTSTRAP, instrumentation).inject(map);
AgentBuilder.Transformer methodsTransformer = new AgentBuilder.Transformer() {
#Override
public DynamicType.Builder<?> transform(DynamicType.Builder<?> builder, TypeDescription typeDescription,
ClassLoader classLoader, JavaModule javaModule) {
return builder.method(ElementMatchers.named("handleRequest"))
.intercept(MethodDelegation.to(LambdaHandlerRuntime.class));
}
};
AgentBuilder.Listener listener = new AgentBuilder.Listener.WithTransformationsOnly(
new AgentBuilder.Listener.StreamWriting(System.out));
new AgentBuilder.Default().type(ElementMatchers.named(handler)).transform(methodsTransformer)
.with(listener).installOn(instrumentation);
i'm injecting the Helper classes needed into bootstrap loader as you can see.
but MyLogger.class has a private enum private enum LogLevel { ERROR, WARNING, INFO, DEBUG }
for which i'm getting NoClassDefFoundError java.lang.NoClassDefFoundError: io/protego/fsp/utils/MyLogger$LogLevel
i guess there is a way to handle enum. any help will be appreciated.
Thanks.

Advice inlines code into target methods. From their inlined location, the code will have to respect the same restrictions as code that would be written at these locations. If you can control the class loaders of these methods, you can refer to code outside of the advice, but you have to make the classes visible. Otherwise, these errors will occur.
From the no class def found error, it does however seem that you instrument a class that cannot see the enum. In this case, consider injecting it into the bootstrap loader (via Instrumentation, for example), and making it public.

Related

how to transform interface to abstract by using javassist

I am using javassist library for modify class files.
I want to modify interface to abstract class
for example,
original :
public interface javax.servlet.Servlet {
public void init(ServletConfig config) throws ServletException;
}
modified :
public abstract javax.servlet.Servlet {
public void init(ServletConfig config) throws ServletException {
System.out.println(config.getServletContext().getServerInfo());
callMethod(); // this is implemented original method
}
}
How can i apply this solution like aop(before, after)?
I think the first problem with your approach is that when you try to modify your interface using Javassist you are attempting to redefine an interface that has been already loaded by the class loader.
One option might be to do a bit of classloader tricks: create a new classloader that doesn't have your existing interface loaded (parent is the system classloader) and have Javassist load through that (use aCtClass.toClass() method that takes a ClassLoader argument). However is not really something I would do since to manage properly more than one ClassLoader is not that easy.
There might be a better way to achieve your goal, and creating new classes might be a better design. You could create a new class that implements everything you need and then extends the required interface.
Moreover I suggest you to take also a look at dynamic proxies that could be an option as well. Their biggest advantage is that you don't need any 3rd party libraries to create them.

Guice Names.bindProperties(binder(), properties) on output of a module?

I use an external service to provide properties, but want to make those properties available as #Named(..) vars. Trying to do this in a configure method fails with npe:
Names.bindProperties(binder(), myPropRetriever.getProperties());
is failing because the myPropRetriever isn't appearing until guice has done it's work. I can see why this makes sense - anyone know of any funky hacks that might work around though? Would be handy in this instance..
Thanks to durron597 for the pointer to the related question which gave me enough to figure out. The answer is to use a child injector to take action on the previous injectors output. Example below:
Injector propInjector = Guice.createInjector(new PropertiesModule());
PropertiesService propService = propInjector.getInstance(PropertiesService.class);
Injector injector = propInjector.createChildInjector(new MyModule(Objects.firstNonNull(propService.getProperties(), new Properties())));
Injector is now your injector for the remainder of the app.
And then in MyModule you can take action on the created objects:
public class MyModule extends AbstractModule {
private final Properties properties;
public MyModule(Properties properties){
this.properties=properties;
}
#Override
protected void configure() {
// export all the properties as bindings
Names.bindProperties(binder(), properties);
// move on to bindings
// bind(..);
}
}
In case it helps anyone else..!

wicket and AtUnit

I've started playing with Wicket and I've chosen Guice as dependency injection framework. Now I'm trying to learn how to write a unit test for a WebPage object.
I googled a bit and I've found this post but it mentioned AtUnit so I decided to give it a try.
My WebPage class looks like this
public class MyWebPage extends WebPage
{
#Inject MyService service;
public MyWebPage()
{
//here I build my components and use injected object.
service.get(id);
....
}
}
I created mock to replace any production MyServiceImpl with it and I guess that Guice in hand with AtUnit should inject it.
Now the problems are:
AtUnit expects that I mark target object with #Unit - that is all right as I can pass already created object to WicketTester
#Unit MyWebPage page = new MyWebPage();
wicketTester.startPage(page);
but usually I would call startPage with class name.
I think AtUnit expects as well that a target object is market with #Inject so AtUnit can create and manage it - but I get an org.apache.wicket.WicketRuntimeException: There is no application attached to current thread main. Can I instruct AtUnit to use application from wicketTester?
Because I don't use #Inject at MyWebPage (I think) all object that should be injected by Guice are null (in my example the service reference is null)
I really can't find anything about AtUnit inside Wicket environment. Am I doing something wrong, am I missing something?
I don't know AtUnit but I use wicket with guice and TestNG. I imagine that AtUnit should work the same way. The important point is the creation of the web application with the use of guice.
Here how I bind all this stuff together for my tests.
I have an abstract base class for all my tests:
public abstract class TesterWicket<T extends Component> {
#BeforeClass
public void buildMockedTester() {
System.out.println("TesterWww.buildMockedTester");
injector = Guice.createInjector(buildModules());
CoachWebApplicationFactory instance =
injector.getInstance(CoachWebApplicationFactory.class);
WebApplication application = instance.buildWebApplication();
tester = new WicketTester(application);
}
protected abstract List<Module> buildModules();
The initialization is done for every test class. The subclass defines the necessary modules for the test in the buildModules method.
In my IWebApplicationFactory I add the GuiceComponentInjector. That way, after all component instantiation, the fields annotated with #Inject are filled by Guice:
public class CoachWebApplicationFactory implements IWebApplicationFactory {
private static Logger LOG = LoggerFactory.getLogger(CoachWebApplicationFactory.class);
private final Injector injector;
#Inject
public CoachWebApplicationFactory(Injector injector) {
this.injector = injector;
}
public WebApplication createApplication(WicketFilter filter) {
WebApplication app = injector.getInstance(WebApplication.class);
Application.set(app);
app.addComponentInstantiationListener(new GuiceComponentInjector(app, injector));
return app;
}
}

Dozer BeanFactory: How to implement it?

I have looked at the Dozer's FAQs and docs, including the SourceForge forum, but I didn't see any good tutorial or even a simple example on how to implement a custom BeanFactory.
Everyone says, "Just implement a BeanFactory". How exactly do you implement it?
I've Googled and all I see are just jars and sources of jars.
Here is one of my BeanFactories, I hope it helps to explain the common pattern:
public class LineBeanFactory implements BeanFactory {
#Override
public Object createBean(final Object source, final Class<?> sourceClass, final String targetBeanId) {
final LineDto dto = (LineDto) source;
return new Line(dto.getCode(), dto.getElectrified(), dto.getName());
}
}
And the corresponding XML mapping:
<mapping>
<class-a bean-factory="com.floyd.nav.web.ws.mapping.dozer.LineBeanFactory">com.floyd.nav.core.model.Line</class-a>
<class-b>com.floyd.nav.web.contract.dto.LineDto</class-b>
</mapping>
This way I declare that when a new instance of Line is needed then it should create it with my BeanFactory. Here is a unit test, that can explain it:
#Test
public void Line_is_created_with_three_arg_constructor_from_LineDto() {
final LineDto dto = createTransientLineDto();
final Line line = (Line) this.lineBeanFactory.createBean(dto, LineDto.class, null);
assertEquals(dto.getCode(), line.getCode());
assertEquals(dto.getElectrified(), line.isElectrified());
assertEquals(dto.getName(), line.getName());
}
So Object source is the source bean that is mapped, Class sourceClass is the class of the source bean (I'm ignoring it, 'cause it will always be a LineDto instance). String targetBeanId is the ID of the destination bean (too ignored).
A custom bean factory is a class that has a method that creates a bean. There are two "flavours"
a) static create method
SomeBean x = SomeBeanFactory.createSomeBean();
b) instance create method
SomeBeanFactory sbf = new SomeBeanFactory();
SomeBean x = sbf.createSomeBean();
You would create a bean factory if creating and setting up your bean requires some tricky logic, like for example initial value of certain properties depend on external configuration file. A bean factory class allows you to centralize "knowledge" about how to create such a tricky bean. Other classes just call create method without worying how to correctly create such bean.
Here is an actual implementation. Obviously it does not make a lot of sense, since Dozer would do the same without the BeanFactory, but instead of just returning an object, you could initialized it somehow differently.
public class ComponentBeanFactory implements BeanFactory {
#Override
public Object createBean(Object source, Class<?> sourceClass,
String targetBeanId) {
return new ComponentDto();
}
}
Why do you need a BeanFactory anyways? Maybe that would help understanding your question.

Late binding with Ninject

I'm working on a framework extension which handles dynamic injection using Ninject as the IoC container, but I'm having some trouble trying to work out how to achieve this.
The expectation of my framework is that you'll pass in the IModule(s) so it can easily be used in MVC, WebForms, etc. So I have the class structured like this:
public class NinjectFactory : IFactory, IDisposable {
readonly IKernel kernel;
public NinjectFactory(IModule[] modules) {
kernel = new StandardKernel(modules);
}
}
This is fine, I can create an instance in a Unit Test and pass in a basic implementation of IModule (using the build in InlineModule which seems to be recommended for testing).
The problem is that it's not until runtime that I know the type(s) I need to inject, and they are requested through the framework I'm extending, in a method like this:
public IInterface Create(Type neededType) {
}
And here's where I'm stumped, I'm not sure the best way to check->create (if required)->return, I have this so far:
public IInterface Create(Type neededType) {
if(!kernel.Components.Has(neededType)) {
kernel.Components.Connect(neededType, new StandardBindingFactory());
}
}
This adds it to the components collection, but I can't work out if it's created an instance or how I create an instance and pass in arguments for the .ctor.
Am I going about this the right way, or is Ninject not even meant to be be used that way?
Unless you want to alter or extend the internals of Ninject, you don't need to add anything to the Components collection on the kernel. To determine if a binding is available for a type, you can do something like this:
Type neededType = ...;
IKernel kernel = ...;
var registry = kernel.Components.Get<IBindingRegistry>();
if (registry.Has(neededType)) {
// Ninject can activate the type
}
Very very late answer but Microsoft.Practices.Unity allows Late Binding via App.Config
Just in case someone comes across this question