public void install(@Observes(precedence = 1) BeforeSuite event)
{
try
{
BytemanConfiguration config = BytemanConfiguration.from(descriptorInst.get());
if(!config.autoInstallAgent())
{
return;
}
try
{
// Not only load it, but also attempt to check firstTime variable, since in embedded containers this might be the same jvm
Class<?> mainClass = Thread.currentThread().getContextClassLoader().loadClass("org.jboss.byteman.agent.Main");
if(!(Boolean)mainClass.getDeclaredField("firstTime").get(null))
{
return;
}
}
catch (ClassNotFoundException e)
{
// Agent not loaded yet, move on
}
String pid = ManagementFactory.getRuntimeMXBean().getName().split("@")[0];
File bytemanHome = File.createTempFile("byteman", "agent");
bytemanHome.delete();
bytemanHome.mkdir();
File bytemanLib = new File(bytemanHome, "lib");
bytemanLib.mkdirs();
InputStream bytemanInputJar = ShrinkWrap.create(JavaArchive.class)
.addPackages(true, "org.jboss.byteman")
.setManifest(
new StringAsset("Manifest-Version: 1.0\n"
+ "Created-By: Arquillian\n"
+ "Implementation-Version: 0.0.0.Arq\n"
+ "Premain-Class: org.jboss.byteman.agent.Main\n"
+ "Agent-Class: org.jboss.byteman.agent.Main\n"
+ "Can-Redefine-Classes: true\n"
+ "Can-Retransform-Classes: true\n")).as(ZipExporter.class).exportAsInputStream();
File bytemanJar = new File(bytemanLib, BytemanConfiguration.BYTEMAN_JAR);
GenerateScriptUtil.copy(bytemanInputJar, new FileOutputStream(bytemanJar));
VirtualMachine vm = VirtualMachine.attach(pid);
String agentProperties = config.agentProperties();
vm.loadAgent(bytemanJar.getAbsolutePath(), "listener:true,port:" + config.clientAgentPort() + (agentProperties != null ? ",prop:" + agentProperties:""));
vm.detach();
}
catch (IOException e)
{
throw new RuntimeException("Could not write byteman.jar to disk", e);