package me.yamakaja.runtimetransformer;

import java.io.File;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;

/**
 * Created by Yamakaja on 19.05.17.
 */
public class RuntimeTransformer {

    public RuntimeTransformer(Class<?>... transformers) {
        ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();
        if (systemClassLoader instanceof URLClassLoader) {
            URLClassLoader urlClassLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();

            try {
                Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
                method.setAccessible(true);

                File file = new File(new File(System.getProperty("java.home")).getParent(), "lib/tools.jar");
                if (!file.exists())
                    throw new RuntimeException("Not running with JDK!");

                method.invoke(urlClassLoader, file.toURI().toURL());
            } catch (Throwable throwable) {
                throwable.printStackTrace();
            }
        }

        TransformerUtils.attachAgent(TransformerUtils.saveAgentJar(), transformers);
    }

}

@@ -140,16 +140,71 @@
 sLoader;
+%0Aimport java.nio.file.Files;%0Aimport java.nio.file.Path;
 %0A%0A/**%0A *
@@ -276,16 +276,92 @@
 rmer %7B%0A%0A
+    private static final String ATTACH_MOD_PATH = %22jmods/jdk.attach.jmod%22;%0A%0A
     publ
@@ -485,16 +485,84 @@
 oader();
+%0A%0A        File javaHome = new File(System.getProperty(%22java.home%22));
 %0A       
@@ -888,20 +888,24 @@
    File 
-file
+toolsJar
  = new F
@@ -912,61 +912,16 @@
 ile(
-new File(System.getProperty(%22
 java
-.h
+H
 ome
-%22)).getParent()
 , %22l
@@ -957,20 +957,24 @@
    if (!
-file
+toolsJar
 .exists(
@@ -1096,20 +1096,24 @@
 Loader, 
-file
+toolsJar
 .toURI()
@@ -1235,16 +1235,235 @@
        %7D
+ else %7B%0A            Path attachMod = javaHome.toPath().resolve(ATTACH_MOD_PATH);%0A            if (Files.notExists(attachMod)) %7B%0A                throw new RuntimeException(%22Not running with JDK!%22);%0A            %7D%0A        %7D
 %0A%0A      

Verify if the JDK attach mod is installed