Can homebody help me please to give me a hint how to redefine static methods using byte-buddy 1.6.9 ?
I have tried this :
public class Source {
public static String hello(String name) {return null;}
}
public class Target {
public static String hello(String name) {
return "Hello" + name+ "!";
}
}
String helloWorld = new ByteBuddy()
.redefine(Source.class)
.method(named("hello"))
.intercept(MethodDelegation.to(Target.class))
.make()
.load(getClass().getClassLoader())
.getLoaded()
.newInstance()
.hello("World");
I got following Exception :
Exception in thread "main" java.lang.IllegalStateException: Cannot inject already loaded type: class delegation.Source
Thanks
Classes can only be loaded once by each class loader. In order to replace a method, you would need to use a Java agent to hook into the JVM's HotSwap feature.
Byte Buddy provides a class loading strategy that uses such an agent, use:
.load(Source.class.getClassLoader(),
ClassReloadingStrategy.fromInstalledAgent());
This does however require you to install a Java agent. On a JDK, you can do so programmatically, by ByteBuddyAgent.install() (included in the byte-buddy-agent artifact). On a JVM, you have to specify the agent on the command line.
Related
Javassist proxyFactory can create proxy at runtime with method interceptor. But how to add method interceptor to a class statically by modifying the class file?
For example, class Foo has 100 methods, before calling any method on an instance of Foo, need to check if the Foo instance is initialized.
public class Foo {
public void methodA() {
...
}
public void methodB() {
...
}
public void methodC() {
...
}
....
}
How to modify the class file to add such method interceptor? One way is to add code at the beginning of each method. Is there a better way?
How about other bytecode tools such as cglib, ....?
There are two options with ByteBuddy to achive this:
use redefine/rebase feature - You can check the details on ByteBuddy tutorial under 'type redefinition'/'type rebasing' tags. Limitation here is that this kind of transformation needs to be done before a target class is loaded.
Java Agent - agents run before class is loaded so they are allowed to modify existing classes. ByteBuddy comes with nice AgentBuilder (tutorial - 'Creating Java agents'). There is also posiblity to install special ByteBuddy agent at runtime (example from mentioned tutorial).
class Foo {
String m() { return "foo"; }
}
class Bar {
String m() { return "bar"; }
}
ByteBuddyAgent.install();
Foo foo = new Foo();
new ByteBuddy()
.redefine(Bar.class)
.name(Foo.class.getName())
.make()
.load(Foo.class.getClassLoader(), ClassReloadingStrategy.fromInstalledAgent());
assertThat(foo.m(), is("bar"));
I have been trying out Frege and one of the first things I would like to do is implement a Java interface.
How is that done?
Here's my example in Java:
package mypkg;
import frege.repl.FregeRepl;
import frege.runtime.Concurrent;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
public class FregeMain implements BundleActivator {
public FregeMain() {
}
#Override
public void start( BundleContext context ) throws Exception {
System.out.println( "Frege Bundle activated" );
new Thread( () -> FregeRepl.main( new String[ 0 ] ) ).start();
}
#Override
public void stop( BundleContext context ) throws Exception {
System.out.println( "Frege stopping. Goodbye!" );
Concurrent.shutDownIfExists();
}
}
To implement this in Frege, I would need to know:
how to declare something that will be visible as a class called mypkg.FregeMain implementing BundleActivator in JVM bytecode (notice that this is important as the OSGi framework will scan the jar for classes implementing that interface, and call them automatically).
How to implement a Runnable (as a Haskell lambda, probably) and pass it on to the Thread constructor. Also same issue: implement a Java interface, but this time with an anonymous class or lambda.
I tried to understand the Calling Java from Frege post, but probably due to my lack of experience in Frege/Haskell, I just don't understand most of that.
Thanks for any input.
The simplest way to implement Java interface in Frege is possibly to use an inline module definition. Some thorough examples are in https://github.com/Frege/FregeFX/blob/master/fregefx/src/main/frege/fregefx/JavaFxUtils.fr
I'm writing a progressive downloader as a Portable Class Library (Profile=24). It will support partial downloads of target files in chunks of bytes. HttpClient not being available, I'm going with HttpWebRequest, which has the AddRange method for partial downloads. But the method doesn't seem to be available from inside the PCL. So I set HttpWebRequest.Headers["Range"], but doing so throws the following ArgumentException:
"The 'Range' header must be modified using the appropriate property or method.\r\nParameter name: name"
That "appropriate property" seems to be HttpWebRequest.AddRange, but as I said it doesn't seem to be exposed from inside PCL. So I'm quite confused: what would be the right way of specifying the HttpWebRequest.Headers["Range"] in a PCL?
Thanks,
Simon
I didn't find the answer, but the following interface workaround worked for me:
Instead of creating the HttpWebRequest in my portable code, I defined the following custom interfaces:
public interface IMyRequest {
[...]
void AddRange(long from, long to);
}
public interface IMyRequestFactory {
IMyRequest Create(string url);
}
Then, in my non-portable code, I created classes that implemented those interfaces:
public class MyRequestImp : IMyRequest {
private readonly HttpWebRequest request;
public MyRequestImp (string url) {
request = (HttpWebRequest)WebRequest.Create(url);
}
[...]
public void AddRange(long from, long to) {
request.AddRange(from, to);
}
}
public class MyRequestFactoryImp: IMyRequestFactory {
public IMyRequest Create(string url) {
return new MyRequestImp(url);
}
}
At some point at initialization time, my non-portable code is passing a MyRequestFactoryImp object to my portable library through the IMyRequestFactory interface. Since the HttpWebRequest was created outside the PCL, you have access to the full functionalities of the class.
To cross the language boundary in Java side the class to be serialized needs to implement the DataSerializable interface; and in order to let the deserializer in c# know what class it is , we need to register a classID. Following the example, I write my class in Java like this:
public class Stuff implements DataSerializable{
static { // note that classID (7) must match C#
Instantiator.register(new Instantiator(Stuff.class,(byte)0x07) {
#Override
public DataSerializable newInstance() {
return new Stuff();
}
});
}
private Stuff(){}
public boolean equals(Object obj) {...}
public int hashCode() {...}
public void toData(DataOutput dataOutput) throws IOException {...}
public void fromData(DataInput dataInput) throws IOException, ClassNotFoundException { ...}
}
It looks OK but when I run it I get this exception:
[warning 2012/03/30 15:06:00.239 JST tid=0x1] Error registering
instantiator on pool:
com.gemstone.gemfire.cache.client.ServerOperationException: : While
performing a remote registerInstantiators at
com.gemstone.gemfire.cache.client.internal.AbstractOp.processAck(AbstractOp.java:247)
at
com.gemstone.gemfire.cache.client.internal.RegisterInstantiatorsOp$RegisterInstantiatorsOpImpl.processResponse(RegisterInstantiatorsOp.java:76)
at
com.gemstone.gemfire.cache.client.internal.AbstractOp.attemptReadResponse(AbstractOp.java:163)
at
com.gemstone.gemfire.cache.client.internal.AbstractOp.attempt(AbstractOp.java:363)
at
com.gemstone.gemfire.cache.client.internal.ConnectionImpl.execute(ConnectionImpl.java:229)
at
com.gemstone.gemfire.cache.client.internal.pooling.PooledConnection.execute(PooledConnection.java:321)
at
com.gemstone.gemfire.cache.client.internal.OpExecutorImpl.executeWithPossibleReAuthentication(OpExecutorImpl.java:646)
at
com.gemstone.gemfire.cache.client.internal.OpExecutorImpl.execute(OpExecutorImpl.java:108)
at
com.gemstone.gemfire.cache.client.internal.PoolImpl.execute(PoolImpl.java:624)
at
com.gemstone.gemfire.cache.client.internal.RegisterInstantiatorsOp.execute(RegisterInstantiatorsOp.java:39)
at
com.gemstone.gemfire.internal.cache.PoolManagerImpl.allPoolsRegisterInstantiator(PoolManagerImpl.java:216)
at
com.gemstone.gemfire.internal.InternalInstantiator.sendRegistrationMessageToServers(InternalInstantiator.java:188)
at
com.gemstone.gemfire.internal.InternalInstantiator._register(InternalInstantiator.java:143)
at
com.gemstone.gemfire.internal.InternalInstantiator.register(InternalInstantiator.java:71)
at com.gemstone.gemfire.Instantiator.register(Instantiator.java:168)
at Stuff.(Stuff.java)
Caused by: java.lang.ClassNotFoundException: Stuff$1
I could not figure out why, is there anyone who has experience can help? Thanks in advance!
In most configurations GemFire servers need to deserialize objects in order to index them, run queries and call listeners. So when you register instantiator the class will be registered on all machines in the Distributed System. Hence, the class itself must be available for loading everywhere in the cluster.
As exception stack trace says the error happens on a remote node.
Check if you have the class Stuff on all machines participating in the cluster. At least on cache servers.
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;
}
}