proj_name
stringclasses
157 values
relative_path
stringlengths
30
228
class_name
stringlengths
1
68
func_name
stringlengths
1
49
masked_class
stringlengths
68
9.82k
func_body
stringlengths
46
9.61k
len_input
int64
27
2.01k
len_output
int64
14
1.94k
total
int64
55
2.05k
relevant_context
stringlengths
0
38.4k
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-owb-plugin/src/main/java/org/hotswap/agent/plugin/owb/transformer/BeansDeployerTransformer.java
BeansDeployerTransformer
transform
class BeansDeployerTransformer { private static AgentLogger LOGGER = AgentLogger.getLogger(BeansDeployerTransformer.class); /** * Basic CdiArchive transformation. * * @param clazz * @param classPool * @throws NotFoundException * @throws CannotCompileException */ @OnClassLoadEvent(classNameRegexp = "org.apache.webbeans.config.BeansDeployer") public static void transform(CtClass clazz, ClassPool classPool) throws NotFoundException, CannotCompileException {<FILL_FUNCTION_BODY>} }
if (HaCdiCommons.isJakarta(classPool)) { return; } StringBuilder src = new StringBuilder(" if (deployed) {"); src.append("ClassLoader curCl = Thread.currentThread().getContextClassLoader();"); src.append(PluginManagerInvoker.buildInitializePlugin(OwbPlugin.class, "curCl")); src.append(PluginManagerInvoker.buildCallPluginMethod("curCl", OwbPlugin.class, "init")); src.append(PluginManagerInvoker.buildCallPluginMethod("curCl", OwbPlugin.class, "registerBeansXmls", "$1.getBeanXmls()", "java.util.Set")); src.append("}"); CtMethod startApplication = clazz.getDeclaredMethod("deploy"); startApplication.insertAfter(src.toString()); LOGGER.debug("Class '{}' patched with OwbPlugin registration.", clazz.getName());
159
242
401
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-owb-plugin/src/main/java/org/hotswap/agent/plugin/owb/transformer/CdiContextsTransformer.java
CdiContextsTransformer
transformOwbContexts
class CdiContextsTransformer { private static AgentLogger LOGGER = AgentLogger.getLogger(CdiContextsTransformer.class); @OnClassLoadEvent(classNameRegexp = "(org.apache.webbeans.context.AbstractContext)|" + "(org.apache.myfaces.flow.cdi.FlowScopedContextImpl)|" + "(org.apache.myfaces.cdi.view.ViewScopeContextImpl)") public static void transformOwbContexts(CtClass clazz, ClassPool classPool, ClassLoader cl) throws NotFoundException, CannotCompileException {<FILL_FUNCTION_BODY>} /* static void addDestroyMethod(CtClass clazz, ClassPool classPool) { CtMethod destroy = null; try { destroy = clazz.getDeclaredMethod("destroy", new CtClass[] {classPool.get("javax.enterprise.context.spi.Contextual")}); } catch (NotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } if(destroy == null) { try { clazz.addMethod(CtMethod.make(// "public void destroy(javax.enterprise.context.spi.Contextual c) {\n"+// ContextualReloadHelper.class.getName() +".reinitialize(this, c);\n"+ "}\n", clazz)); } catch (CannotCompileException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } */ @OnClassLoadEvent(classNameRegexp = "org.apache.webbeans.context.AbstractContext") public static void transformAbstractContext(ClassPool classPool, CtClass ctClass) throws NotFoundException, CannotCompileException { if (HaCdiCommons.isJakarta(classPool)) { return; } HaCdiCommons.transformContext(classPool, ctClass); } }
if (HaCdiCommons.isJakarta(classPool)) { return; } CtClass superClass = clazz.getSuperclass(); while (superClass != null) { if ("org.apache.webbeans.context.AbstractContext".equals(superClass.getName())) { return; } superClass = superClass.getSuperclass(); } LOGGER.debug("Adding interface {} to {}.", OwbHotswapContext.class.getName(), clazz.getName()); clazz.addInterface(classPool.get(OwbHotswapContext.class.getName())); CtField toReloadFld = CtField.make("public transient java.util.Set $$ha$toReloadOwb = null;", clazz); clazz.addField(toReloadFld); CtField reloadingFld = CtField.make("public transient boolean $$ha$reloadingOwb = false;", clazz); clazz.addField(reloadingFld); CtMethod addBeanToReload = CtMethod.make( "public void $$ha$addBeanToReloadOwb(javax.enterprise.context.spi.Contextual bean){" + "if ($$ha$toReloadOwb == null)" + "$$ha$toReloadOwb = new java.util.HashSet();" + "$$ha$toReloadOwb.add(bean);" + "}", clazz ); clazz.addMethod(addBeanToReload); CtMethod getBeansToReload = CtMethod.make("public java.util.Set $$ha$getBeansToReloadOwb(){return $$ha$toReloadOwb;}", clazz); clazz.addMethod(getBeansToReload); CtMethod reload = CtMethod.make("public void $$ha$reloadOwb() {" + ContextualReloadHelper.class.getName() +".reload(this);}", clazz); clazz.addMethod(reload); CtMethod isActive = clazz.getDeclaredMethod("isActive"); isActive.insertAfter( "if($_ && !$$ha$reloadingOwb ) { " + "$$ha$reloadingOwb = true;" + "$$ha$reloadOwb();" + "$$ha$reloadingOwb = false;" + "}" + "return $_;" ); //addDestroyMethod(clazz, classPool); LOGGER.debug("Class '{}' patched with hot-swapping support", clazz.getName() );
510
681
1,191
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-owb-plugin/src/main/java/org/hotswap/agent/plugin/owb/transformer/ProxyFactoryTransformer.java
ProxyFactoryTransformer
patchProxyFactory
class ProxyFactoryTransformer { /** * Patch AbstractProxyFactory class. * - add factory registration into constructor * - changes call classLoader.loadClass(...) in getProxyClass() to ProxyClassLoadingDelegate.loadClass(classLoader, ...) * - changes call ClassFileUtils.toClass() in createProxyClass() to ProxyClassLoadingDelegate.loadClass(...) * * @param ctClass the ProxyFactory class * @param classPool the class pool * @throws NotFoundException the not found exception * @throws CannotCompileException the cannot compile exception */ @OnClassLoadEvent(classNameRegexp = "org.apache.webbeans.proxy.AbstractProxyFactory") public static void patchProxyFactory(CtClass ctClass, ClassPool classPool) throws NotFoundException, CannotCompileException {<FILL_FUNCTION_BODY>} }
if (HaCdiCommons.isJakarta(classPool)) { return; } CtMethod getProxyClassMethod = ctClass.getDeclaredMethod("getUnusedProxyClassName"); getProxyClassMethod.instrument( new ExprEditor() { public void edit(MethodCall m) throws CannotCompileException { if (m.getClassName().equals(Class.class.getName()) && m.getMethodName().equals("forName")) m.replace("{ $_ = org.hotswap.agent.plugin.owb.command.ProxyClassLoadingDelegate.forName($$); }"); } }); CtMethod createProxyClassMethod = ctClass.getDeclaredMethod("createProxyClass", new CtClass[] { classPool.get(ClassLoader.class.getName()), classPool.get(String.class.getName()), classPool.get(Class.class.getName()), classPool.get(Method.class.getName() + "[]"), classPool.get(Method.class.getName() + "[]"), classPool.get(Constructor.class.getName()) } ); createProxyClassMethod.instrument( new ExprEditor() { public void edit(MethodCall m) throws CannotCompileException { if (m.getMethodName().equals("defineAndLoadClass")) if ("org.apache.webbeans.proxy.Unsafe".equals(m.getClassName())) { // OWB >= 2.0.8 m.replace("{ $_ = org.hotswap.agent.plugin.owb.command.ProxyClassLoadingDelegate.defineAndLoadClassWithUnsafe(this.unsafe, $$); }"); } else { // OWB < 2.0.8 m.replace("{ $_ = org.hotswap.agent.plugin.owb.command.ProxyClassLoadingDelegate.defineAndLoadClass(this, $$); }"); } } });
223
492
715
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-proxy-plugin/src/main/java/org/hotswap/agent/plugin/proxy/ProxyClassSignatureHelper.java
ProxyClassSignatureHelper
isPoolClassOrParentDifferent
class ProxyClassSignatureHelper { private static AgentLogger LOGGER = AgentLogger.getLogger(ProxyClassSignatureHelper.class); private static final ClassSignatureElement[] SIGNATURE_WITH_ANNO_ELEMENTS = { ClassSignatureElement.SUPER_CLASS, ClassSignatureElement.INTERFACES, ClassSignatureElement.METHOD, ClassSignatureElement.METHOD_ANNOTATION, ClassSignatureElement.METHOD_PARAM_ANNOTATION, ClassSignatureElement.METHOD_EXCEPTION, }; private static final ClassSignatureElement[] SIGNATURE_ELEMENTS = { ClassSignatureElement.SUPER_CLASS, ClassSignatureElement.INTERFACES, ClassSignatureElement.METHOD, ClassSignatureElement.METHOD_EXCEPTION, }; public static String getJavaClassSignature(Class<?> clazz) throws Exception { return ClassSignatureComparerHelper.getJavaClassSignature(clazz, SIGNATURE_WITH_ANNO_ELEMENTS); } private static void addSignaturesToMap(Class<?> clazz, Map<String, String> signatureMap) { if (clazz != null && clazz != Object.class) { try { String signature = getJavaClassSignature(clazz); signatureMap.put(clazz.getName(), signature); } catch (Exception e) { LOGGER.error("Error reading signature", e); } for (Class<?> interfaceClazz : clazz.getInterfaces()) { addSignaturesToMap(interfaceClazz, signatureMap); } } } public static Map<String, String> getNonSyntheticSignatureMap(Class<?> clazz) { Map<String, String> signatureMap = new HashMap<>(); Class<?> parentClass = clazz.getSuperclass(); while (parentClass.isSynthetic()) { parentClass = parentClass.getSuperclass(); } addSignaturesToMap(parentClass, signatureMap); for (Class<?> intr : clazz.getInterfaces()) { addSignaturesToMap(intr, signatureMap); } return signatureMap; } public static boolean isPoolClassDifferent(Class<?> clazz, ClassPool cp) { return ClassSignatureComparerHelper.isPoolClassDifferent(clazz, cp, SIGNATURE_ELEMENTS); } /** * Checks if the CtClass or one of its parents signature differs from the one already loaded by Java. * * @param clazz * @param cp * @return */ public static boolean isPoolClassOrParentDifferent(Class<?> clazz, ClassPool cp) {<FILL_FUNCTION_BODY>} /** * Checks if the CtClass or one of its parents signature differs from the one already loaded by Java. Ignores * synthetic classes * * @param classBeingRedefined * @param cp * @return */ public static boolean isNonSyntheticPoolClassOrParentDifferent(Class<?> classBeingRedefined, ClassPool cp) { Class<?> clazz = classBeingRedefined.getSuperclass(); while (clazz.isSynthetic() || clazz.getName().contains("$Enhancer")) { clazz = clazz.getSuperclass(); } if (isPoolClassOrParentDifferent(clazz, cp)) return true; Class<?>[] interfaces = classBeingRedefined.getInterfaces(); for (Class<?> intr : interfaces) { if (isPoolClassOrParentDifferent(intr, cp)) return true; } return false; } /** * Checks if the CtClass or one of its parents signature differs from the one already loaded by Java. * * @param clazz * @param cc * @return */ public static boolean isPoolClassOrParentDifferent(Class<?> clazz, CtClass cc) { return isPoolClassDifferent(clazz, cc.getClassPool()); } /** * Class arrays need to be in the same order. Check if a signature of class differs from aonther. Useful for * checking difference in different classloaders. * * @param classesA * @param classesB * @return */ public static boolean isDifferent(Class<?>[] classesA, Class<?>[] classesB) { for (int i = 0; i < classesB.length; i++) { Class<?> class1 = classesA[i]; Class<?> class2 = classesB[i]; if (ClassSignatureComparerHelper.isDifferent(class1, class2, SIGNATURE_ELEMENTS)) { return true; } } return false; } private static boolean isPoolClassDifferent(Class<?> clazz, ClassLoader cp) { try { return ClassSignatureComparerHelper.isDifferent(clazz, cp.loadClass(clazz.getName()), SIGNATURE_ELEMENTS); } catch (ClassNotFoundException e) { LOGGER.error("Error reading signature", e); return false; } } /** * Checks if the Class or one of its parents signature differs from the one in the classloader. * * @param clazz * @param cp * @return */ public static boolean isPoolClassOrParentDifferent(Class<?> clazz, ClassLoader cp) { if (isPoolClassDifferent(clazz, cp)) return true; Class<?> superclass = clazz.getSuperclass(); if (superclass != null) { if (isPoolClassOrParentDifferent(superclass, cp)) { return true; } } Class<?>[] interfaces = clazz.getInterfaces(); for (Class<?> interfaceClazz : interfaces) { if (isPoolClassOrParentDifferent(interfaceClazz, cp)) { return true; } } return false; } }
if (isPoolClassDifferent(clazz, cp)) return true; Class<?> superclass = clazz.getSuperclass(); if (superclass != null) { if (isPoolClassOrParentDifferent(superclass, cp)) { return true; } } Class<?>[] interfaces = clazz.getInterfaces(); for (Class<?> interfaceClazz : interfaces) { if (isPoolClassOrParentDifferent(interfaceClazz, cp)) { return true; } } return false;
1,538
145
1,683
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-proxy-plugin/src/main/java/org/hotswap/agent/plugin/proxy/ProxyPlugin.java
ProxyPlugin
transformJavaProxy
class ProxyPlugin { private static AgentLogger LOGGER = AgentLogger.getLogger(ProxyPlugin.class); static boolean isJava8OrNewer = WatcherFactory.JAVA_VERSION >= 18; /** * Flag to check reload status. In unit test we need to wait for reload * finish before the test can continue. Set flag to true in the test class * and wait until the flag is false again. */ public static boolean reloadFlag = false; private static Set<String> proxyRedefiningMap = ConcurrentHashMap.newKeySet(); @OnClassLoadEvent(classNameRegexp = "(jdk.proxy\\d+.\\$Proxy.*)|(com.sun.proxy.\\$Proxy.*)", events = LoadEvent.REDEFINE, skipSynthetic = false) public static void transformJavaProxy(final Class<?> classBeingRedefined, final ClassLoader classLoader) {<FILL_FUNCTION_BODY>} public static void removeProxyDefiningClassName(String className) { proxyRedefiningMap.remove(className); } @OnClassLoadEvent(classNameRegexp = ".*", events = LoadEvent.REDEFINE, skipSynthetic = false) public static byte[] transformCglibProxy(final Class<?> classBeingRedefined, final byte[] classfileBuffer, final ClassLoader loader, final ClassPool cp) throws Exception { GeneratorParams generatorParams = GeneratorParametersTransformer.getGeneratorParams(loader, classBeingRedefined.getName()); if (generatorParams == null) { return classfileBuffer; } if (!ClassLoaderHelper.isClassLoderStarted(loader)) { return classfileBuffer; } loader.loadClass("java.beans.Introspector").getMethod("flushCaches").invoke(null); if (generatorParams.getParam().getClass().getName().endsWith(".Enhancer")) { try { return CglibEnhancerProxyTransformer.transform(classBeingRedefined, cp, classfileBuffer, loader, generatorParams); } catch (Exception e) { LOGGER.error("Error redifining Cglib Enhancer proxy {}", e, classBeingRedefined.getName()); } } // Multistep transformation crashed jvm in java8 u05 if (!isJava8OrNewer) { try { return CglibProxyTransformer.transform(classBeingRedefined, cp, classfileBuffer, generatorParams); } catch (Exception e) { LOGGER.error("Error redifining Cglib proxy {}", e, classBeingRedefined.getName()); } } return classfileBuffer; } /** * Modifies Cglib bytecode generators to store the parameters for this plugin * * @throws Exception */ @OnClassLoadEvent(classNameRegexp = ".*/cglib/.*", skipSynthetic = false) public static CtClass transformDefinitions(CtClass cc) throws Exception { try { return GeneratorParametersTransformer.transform(cc); } catch (Exception e) { LOGGER.error("Error modifying class for cglib proxy creation parameter recording", e); } return cc; } }
/* * Proxy can't be redefined directly in this method (and return new proxy class bytes), since the classLoader contains * OLD definition of proxie's interface. Therefore proxy is defined in deferred command (after some delay) * after proxied interface is redefined in DCEVM. */ Object proxyCache = ReflectionHelper.getNoException(null, java.lang.reflect.Proxy.class, "proxyCache"); if (proxyCache != null) { try { ReflectionHelper.invoke(proxyCache, proxyCache.getClass().getSuperclass(), "removeAll", new Class[] { ClassLoader.class }, classLoader); } catch (IllegalArgumentException e) { LOGGER.error("Reflection proxy cache flush failed. {}", e.getMessage()); } } if (!ClassLoaderHelper.isClassLoderStarted(classLoader)) { return; } final String className = classBeingRedefined.getName(); if (proxyRedefiningMap.contains(className)) { proxyRedefiningMap.remove(className); return; } proxyRedefiningMap.add(className); final Map<String, String> signatureMapOrig = ProxyClassSignatureHelper.getNonSyntheticSignatureMap(classBeingRedefined); reloadFlag = true; // TODO: can be single command if scheduler guarantees the keeping execution order in the order of redefinition PluginManager.getInstance().getScheduler().scheduleCommand(new ReloadJavaProxyCommand(classLoader, className, signatureMapOrig), 50);
817
396
1,213
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-proxy-plugin/src/main/java/org/hotswap/agent/plugin/proxy/ProxyTransformationUtils.java
ProxyTransformationUtils
getClassPool
class ProxyTransformationUtils { private static AgentLogger LOGGER = AgentLogger.getLogger(ProxyTransformationUtils.class); private static Map<ClassLoader, ClassPool> classPoolMap = new WeakHashMap<>(3); /** * Creates one ClassPool per ClassLoader and caches it * * @param classLoader * @return */ public static ClassPool getClassPool(ClassLoader classLoader) {<FILL_FUNCTION_BODY>} /** * Creates a ClassPool with supplied ClassLoader * * @param classLoader * @return */ public static ClassPool createClassPool(final ClassLoader classLoader) { ClassPool cp = new ClassPool() { @Override public ClassLoader getClassLoader() { return classLoader; } }; cp.appendSystemPath(); if (classLoader != null) { LOGGER.trace("Adding loader classpath " + classLoader); cp.appendClassPath(new LoaderClassPath(classLoader)); } return cp; } private static final int BUFFER_SIZE = 8192; public static byte[] copyToByteArray(InputStream in) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(BUFFER_SIZE); try { byte[] buffer = new byte[BUFFER_SIZE]; int bytesRead = -1; while ((bytesRead = in.read(buffer)) != -1) { out.write(buffer, 0, bytesRead); } out.flush(); return out.toByteArray(); } finally { try { in.close(); } catch (IOException ex) { } try { out.close(); } catch (IOException ex) { } } } }
ClassPool classPool = classPoolMap.get(classLoader); if (classPool == null) { synchronized (classPoolMap) { classPool = classPoolMap.get(classLoader); if (classPool == null) { classPool = createClassPool(classLoader); classPoolMap.put(classLoader, classPool); } } } return classPool;
459
104
563
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-proxy-plugin/src/main/java/org/hotswap/agent/plugin/proxy/RedefinitionScheduler.java
RedefinitionScheduler
run
class RedefinitionScheduler implements Runnable { private MultistepProxyTransformer transformer; @Init private static Instrumentation instrumentation; public RedefinitionScheduler(MultistepProxyTransformer transformer) { this.transformer = transformer; } @Override public void run() {<FILL_FUNCTION_BODY>} public static void schedule(MultistepProxyTransformer multistepProxyTransformer) { new Thread(new RedefinitionScheduler(multistepProxyTransformer)).start(); } }
try { instrumentation.redefineClasses(new ClassDefinition(transformer.getClassBeingRedefined(), transformer .getClassfileBuffer())); } catch (Throwable t) { transformer.removeClassState(); throw new RuntimeException(t); }
141
70
211
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-proxy-plugin/src/main/java/org/hotswap/agent/plugin/proxy/ReloadJavaProxyCommand.java
ReloadJavaProxyCommand
executeSingleCommand
class ReloadJavaProxyCommand extends MergeableCommand { private static AgentLogger LOGGER = AgentLogger.getLogger(ReloadJavaProxyCommand.class); private ClassLoader classLoader; private String className; private Map<String, String> signatureMapOrig; public ReloadJavaProxyCommand(ClassLoader classLoader, String className, Map<String, String> signatureMapOrig) { this.classLoader = classLoader; this.className = className; this.signatureMapOrig = signatureMapOrig; } @Override public void executeCommand() { try { executeSingleCommand(); List<Command> commands = new ArrayList<>(getMergedCommands()); for (Command command: commands) { ((ReloadJavaProxyCommand) command).executeSingleCommand(); } } finally { ProxyPlugin.reloadFlag = false; } } public void executeSingleCommand() {<FILL_FUNCTION_BODY>} // Whether all methods of the interface are implemented private boolean isImplementInterface(Map<String, String> signatureMap, Class<?> clazz) { String clazzSignature = ""; try { clazzSignature = ProxyClassSignatureHelper.getJavaClassSignature(clazz).replaceAll("final ", ""); LOGGER.debug("clazzSignature: {}", clazzSignature); } catch (Exception e) { LOGGER.error("Error getJavaClassSignature {}", clazz, e); return true; } for (Map.Entry<String, String> entry : signatureMap.entrySet()) { if(clazzSignature.contains(entry.getKey()) && entry.getValue().contains("public abstract")) { LOGGER.debug("{} Signature: {}", entry.getKey(), entry.getValue()); String[] methodSignatures = entry.getValue().replaceAll("abstract ", "").split(";"); for (String methodSignature : methodSignatures) { if(!clazzSignature.contains(methodSignature)) { return false; } } } } return true; } public boolean shiftScheduleTime() { return false; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ReloadJavaProxyCommand that = (ReloadJavaProxyCommand) o; if (!classLoader.equals(that.classLoader)) return false; return true; } @Override public int hashCode() { int result = classLoader.hashCode(); return result; } @Override public String toString() { return "ReloadJavaProxyCommand{" + "classLoader=" + classLoader + '}'; } }
try { Class<?> clazz = classLoader.loadClass(className); Map<String, String> signatureMap = ProxyClassSignatureHelper.getNonSyntheticSignatureMap(clazz); LOGGER.debug("executeSingleCommand class:{}, signature equals:{}", className, signatureMap.equals(signatureMapOrig)); if (!signatureMap.equals(signatureMapOrig) || !isImplementInterface(signatureMap, clazz)) { byte[] generateProxyClass = ProxyGenerator.generateProxyClass(className, clazz.getInterfaces()); Map<Class<?>, byte[]> reloadMap = new HashMap<>(); reloadMap.put(clazz, generateProxyClass); PluginManager.getInstance().hotswap(reloadMap); LOGGER.reload("Class '{}' has been reloaded.", className); } } catch (ClassNotFoundException e) { LOGGER.error("Error redefining java proxy {}", e, className); }
703
242
945
<methods>public non-sealed void <init>() ,public List<org.hotswap.agent.command.Command> getMergedCommands() ,public org.hotswap.agent.command.Command merge(org.hotswap.agent.command.Command) ,public List<org.hotswap.agent.command.Command> popMergedCommands() <variables>List<org.hotswap.agent.command.Command> mergedCommands
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-proxy-plugin/src/main/java/org/hotswap/agent/plugin/proxy/api/AbstractProxyBytecodeTransformer.java
AbstractProxyBytecodeTransformer
addInitCallToMethods
class AbstractProxyBytecodeTransformer implements ProxyBytecodeTransformer { private ClassPool classPool; /** * * @param classPool * Classpool used to make a CtClass */ public AbstractProxyBytecodeTransformer(ClassPool classPool) { this.classPool = classPool; } public byte[] transform(byte[] byteCode) throws Exception { CtClass cc = classPool.makeClass(new ByteArrayInputStream(byteCode), false); try { String initFieldName = INIT_FIELD_PREFIX + generateRandomString(); addStaticInitStateField(cc, initFieldName); String initCode = getInitCall(cc, initFieldName); addInitCallToMethods(cc, initFieldName, initCode); return cc.toBytecode(); } finally { cc.detach(); } } /** * Builds the Java code String which should be executed to initialize the proxy * * @param cc * CtClass from new definition * @param random * randomly generated String * @return Java code to call init the proxy */ protected abstract String getInitCall(CtClass cc, String random) throws Exception; protected String generateRandomString() { return UUID.randomUUID().toString().replace("-", ""); } /** * Adds the initCall as Java code to all the non static methods of the class. The initialization is only done if * clinitFieldName is false. Responsibility to set the clinitFieldName is on the initCall. * * @param cc * CtClass to be modified * @param clinitFieldName * field name in CtClass * @param initCall * Java code to initialize the Proxy * @throws Exception */ protected void addInitCallToMethods(CtClass cc, String clinitFieldName, String initCall) throws Exception {<FILL_FUNCTION_BODY>} /** * Adds a static boolean field to the class indicating the state of initialization * * @param cc * CtClass to be modified * @param clinitFieldName * field name in CtClass * @throws Exception */ protected void addStaticInitStateField(CtClass cc, String clinitFieldName) throws Exception { CtField f = new CtField(CtClass.booleanType, clinitFieldName, cc); f.setModifiers(Modifier.PRIVATE | Modifier.STATIC); // init value "true" will be inside clinit, so the field wont actually be initialized on redefinition cc.addField(f, "true"); } }
CtMethod[] methods = cc.getDeclaredMethods(); for (CtMethod ctMethod : methods) { if (!ctMethod.isEmpty() && !Modifier.isStatic(ctMethod.getModifiers())) { ctMethod.insertBefore("if(!" + clinitFieldName + "){synchronized(" + cc.getName() + ".class){if(!" + clinitFieldName + "){" + initCall + "}}}"); } }
681
117
798
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-proxy-plugin/src/main/java/org/hotswap/agent/plugin/proxy/api/AbstractProxyTransformer.java
AbstractProxyTransformer
getTransformer
class AbstractProxyTransformer implements ProxyTransformer { public AbstractProxyTransformer(Class<?> classBeingRedefined, ClassPool classPool) { super(); this.classBeingRedefined = classBeingRedefined; this.classPool = classPool; } protected ProxyBytecodeGenerator generator; protected ProxyBytecodeTransformer transformer; protected Class<?> classBeingRedefined; protected ClassPool classPool; protected ProxyBytecodeGenerator getGenerator() { if (generator == null) { generator = createGenerator(); } return generator; } protected ProxyBytecodeTransformer getTransformer() {<FILL_FUNCTION_BODY>} /** * creates a new ProxyBytecodeGenerator insatance for use in this transformer * * @return */ protected abstract ProxyBytecodeGenerator createGenerator(); /** * creates a new ProxyBytecodeTransformer insatance for use in this transformer * * @return */ protected abstract ProxyBytecodeTransformer createTransformer(); /** * Checks if there were changes that require the redefinition of the proxy * * @return true if there wre changes that require redefinition */ protected boolean isTransformingNeeded() { return ProxyClassSignatureHelper.isNonSyntheticPoolClassOrParentDifferent(classBeingRedefined, classPool); } }
if (transformer == null) { transformer = createTransformer(); } return transformer;
363
29
392
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-proxy-plugin/src/main/java/org/hotswap/agent/plugin/proxy/api/MultistepProxyTransformer.java
MultistepProxyTransformer
transformRedefine
class MultistepProxyTransformer extends AbstractProxyTransformer { private static final AgentLogger LOGGER = AgentLogger.getLogger(MultistepProxyTransformer.class); public static boolean addThirdStep = false; protected byte[] classfileBuffer; protected Map<Class<?>, TransformationState> transformationStates; protected ProxyBytecodeGenerator generator; protected ProxyBytecodeTransformer transformer; public MultistepProxyTransformer(Class<?> classBeingRedefined, ClassPool classPool, byte[] classfileBuffer, Map<Class<?>, TransformationState> transformationStates) { super(classBeingRedefined, classPool); this.classPool = classPool; this.transformationStates = transformationStates; this.classfileBuffer = classfileBuffer; } /** * Handles the current transformation state * * @return * @throws Exception */ public byte[] transformRedefine() throws Exception {<FILL_FUNCTION_BODY>} /** * @return Current transformation state of the classBeingRedefined */ protected TransformationState getTransformationstate() { TransformationState transformationState = transformationStates.get(classBeingRedefined); if (transformationState == null) transformationState = TransformationState.NEW; return transformationState; } /** * Generate new redefinition event for current classBeingRedefined */ protected void scheduleRedefinition() { RedefinitionScheduler.schedule(this); } /** * Set classBeingRedefined as waiting * * @return */ protected TransformationState setClassAsWaiting() { return transformationStates.put(classBeingRedefined, TransformationState.WAITING); } /** * Set classBeingRedefined as finished * * @return */ protected TransformationState setClassAsFinished() { return transformationStates.put(classBeingRedefined, TransformationState.FINISHED); } /** * Remove any state associated with classBeingRedefined * * @return */ public TransformationState removeClassState() { return transformationStates.remove(classBeingRedefined); } /** * The Class this instance is redefining * * @return */ public Class<?> getClassBeingRedefined() { return classBeingRedefined; } /** * Bytecode of the Class this instance is redefining. * * @return */ public byte[] getClassfileBuffer() { return classfileBuffer; } }
switch (getTransformationstate()) { case NEW: if (!isTransformingNeeded()) { return classfileBuffer; } setClassAsWaiting(); // We can't do the transformation in this event, because we can't see the changes in the class // definitons. Schedule a new redefinition event. scheduleRedefinition(); return classfileBuffer; case WAITING: classfileBuffer = getTransformer().transform(getGenerator().generate()); LOGGER.reload("Class '{}' has been reloaded.", classBeingRedefined.getName()); if (addThirdStep) { setClassAsFinished(); scheduleRedefinition(); } else removeClassState(); return classfileBuffer; case FINISHED: removeClassState(); return classfileBuffer; default: throw new RuntimeException("Unhandeled TransformationState!"); }
684
235
919
<methods>public void <init>(Class<?>, org.hotswap.agent.javassist.ClassPool) <variables>protected Class<?> classBeingRedefined,protected org.hotswap.agent.javassist.ClassPool classPool,protected org.hotswap.agent.plugin.proxy.api.ProxyBytecodeGenerator generator,protected org.hotswap.agent.plugin.proxy.api.ProxyBytecodeTransformer transformer
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-proxy-plugin/src/main/java/org/hotswap/agent/plugin/proxy/api/SinglestepProxyTransformer.java
SinglestepProxyTransformer
transformRedefine
class SinglestepProxyTransformer extends AbstractProxyTransformer { private static final AgentLogger LOGGER = AgentLogger.getLogger(SinglestepProxyTransformer.class); protected byte[] classfileBuffer; public SinglestepProxyTransformer(Class<?> classBeingRedefined, ClassPool classPool, byte[] classfileBuffer) { super(classBeingRedefined, classPool); this.classfileBuffer = classfileBuffer; } /** * Handles the current transformation state * * @return * @throws Exception */ public byte[] transformRedefine() throws Exception {<FILL_FUNCTION_BODY>} }
if (!isTransformingNeeded()) { return classfileBuffer; } classfileBuffer = getTransformer().transform(getGenerator().generate()); LOGGER.reload("Class '{}' has been reloaded.", classBeingRedefined.getName()); return classfileBuffer;
168
73
241
<methods>public void <init>(Class<?>, org.hotswap.agent.javassist.ClassPool) <variables>protected Class<?> classBeingRedefined,protected org.hotswap.agent.javassist.ClassPool classPool,protected org.hotswap.agent.plugin.proxy.api.ProxyBytecodeGenerator generator,protected org.hotswap.agent.plugin.proxy.api.ProxyBytecodeTransformer transformer
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-proxy-plugin/src/main/java/org/hotswap/agent/plugin/proxy/hscglib/CglibEnhancerProxyBytecodeGenerator.java
FieldState
loadFromClassloader
class FieldState { public FieldState(Field field, Object fieldValue) { this.field = field; this.fieldValue = fieldValue; } private Field field; private Object fieldValue; } /** * Generates bytecode for the proxy class * * @return bytecode of the new proxy class * @throws Exception */ @Override public byte[] generate() throws Exception { Collection<FieldState> oldClassValues = getFieldValuesWithClasses(); ClassLoader oldClassLoader = (ClassLoader) ReflectionHelper .get(generator, "classLoader"); Boolean oldUseCache = (Boolean) ReflectionHelper.get(generator, "useCache"); try { ReflectionHelper.set(generator, abstractGeneratorClass, "classLoader", classLoader); ReflectionHelper.set(generator, abstractGeneratorClass, "useCache", Boolean.FALSE); setFieldValuesWithNewLoadedClasses(oldClassValues); byte[] invoke = (byte[]) ReflectionHelper.invoke( param.getGenerator(), param.getGenerator().getClass(), "generate", new Class[] { getGeneratorInterfaceClass() }, generator); return invoke; } finally { ReflectionHelper.set(generator, abstractGeneratorClass, "classLoader", oldClassLoader); ReflectionHelper.set(generator, abstractGeneratorClass, "useCache", oldUseCache); setFieldValues(oldClassValues); } } /** * * @return ClassGenerator interface Class instance */ private Class<?> getGeneratorInterfaceClass() { Class<?>[] interfaces = abstractGeneratorClass.getInterfaces(); for (Class<?> iClass : interfaces) { if (iClass.getName().endsWith(".ClassGenerator")) return iClass; } return null; } private void setFieldValues(Collection<FieldState> fieldStates) throws IllegalAccessException { for (FieldState fieldState : fieldStates) { fieldState.field.set(generator, fieldState.fieldValue); } } /** * replaces fields with Class values with new classes loaded by a * ParentLastClassLoader * * @param fieldStates * @throws IllegalAccessException * @throws ClassNotFoundException */ private void setFieldValuesWithNewLoadedClasses( Collection<FieldState> fieldStates) throws IllegalAccessException, ClassNotFoundException { for (FieldState fieldState : fieldStates) { fieldState.field.set(generator, loadFromClassloader(fieldState.fieldValue)); } } private Collection<FieldState> getFieldValuesWithClasses() throws IllegalAccessException { Collection<FieldState> classValueFields = new ArrayList<FieldState>(); Field[] fields = generatorClass.getDeclaredFields(); for (Field field : fields) { if (!Modifier.isStatic(field.getModifiers()) && (field.getType().isInstance(Class.class) || field.getType().isInstance(Class[].class))) { field.setAccessible(true); classValueFields .add(new FieldState(field, field.get(generator))); } } return classValueFields; } /** * Load classes from ParentLastClassLoader * * @param fieldState * @return * @throws ClassNotFoundException */ private Object loadFromClassloader(Object fieldState) throws ClassNotFoundException {<FILL_FUNCTION_BODY>
if (fieldState instanceof Class[]) { Class<?>[] classes = ((Class[]) fieldState); Class<?>[] newClasses = new Class[classes.length]; for (int i = 0; i < classes.length; i++) { Class<?> loadClass = classLoader .loadClass(classes[i].getName()); newClasses[i] = loadClass; } return newClasses; } else { if (fieldState instanceof Class) { return classLoader.loadClass(((Class<?>) fieldState).getName()); } } return fieldState;
893
156
1,049
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-proxy-plugin/src/main/java/org/hotswap/agent/plugin/proxy/hscglib/CglibProxyBytecodeGenerator.java
CglibProxyBytecodeGenerator
generate
class CglibProxyBytecodeGenerator implements ProxyBytecodeGenerator { private GeneratorParams params; public CglibProxyBytecodeGenerator(GeneratorParams params) { super(); this.params = params; } public byte[] generate() throws Exception {<FILL_FUNCTION_BODY>} /** * Retrieves the actual Method that generates and returns the bytecode * * @param generator * GeneratorStrategy instance * @return Method that generates and returns the bytecode */ private Method getGenerateMethod(Object generator) { Method[] methods = generator.getClass().getMethods(); for (Method method : methods) { if (method.getName().equals("generate") && method.getReturnType().getSimpleName().equals("byte[]") && method.getParameterTypes().length == 1) { return method; } } return null; } }
Method genMethod = getGenerateMethod(params.getGenerator()); if (genMethod == null) throw new RuntimeException( "No generation Method found for redefinition!"); return (byte[]) genMethod.invoke(params.getGenerator(), params.getParam());
234
71
305
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-proxy-plugin/src/main/java/org/hotswap/agent/plugin/proxy/hscglib/CglibProxyBytecodeTransformer.java
CglibProxyBytecodeTransformer
getInitCall
class CglibProxyBytecodeTransformer extends AbstractProxyBytecodeTransformer { public CglibProxyBytecodeTransformer(ClassPool classPool) { super(classPool); } @Override protected String getInitCall(CtClass cc, String initFieldName) throws Exception {<FILL_FUNCTION_BODY>} }
CtMethod[] methods = cc.getDeclaredMethods(); StringBuilder strB = new StringBuilder(); for (CtMethod ctMethod : methods) { if (ctMethod.getName().startsWith("CGLIB$STATICHOOK")) { ctMethod.insertAfter(initFieldName + "=true;"); strB.insert(0, ctMethod.getName() + "();"); break; } } if (strB.length() == 0) throw new RuntimeException( "Could not find CGLIB$STATICHOOK method"); return strB.toString() + "CGLIB$BIND_CALLBACKS(this);";
90
173
263
<methods>public void <init>(org.hotswap.agent.javassist.ClassPool) ,public byte[] transform(byte[]) throws java.lang.Exception<variables>private org.hotswap.agent.javassist.ClassPool classPool
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-proxy-plugin/src/main/java/org/hotswap/agent/plugin/proxy/hscglib/GeneratorParametersRecorder.java
GeneratorParametersRecorder
getClassName
class GeneratorParametersRecorder { // this Map is used in the App ClassLoader public static ConcurrentHashMap<String, GeneratorParams> generatorParams = new ConcurrentHashMap<>(); private static AgentLogger LOGGER = AgentLogger .getLogger(GeneratorParametersRecorder.class); /** * * @param generatorStrategy * Cglib generator strategy instance that generated the bytecode * @param classGenerator * parameter used to generate the bytecode with generatorStrategy * @param bytes * generated bytecode */ public static void register(Object generatorStrategy, Object classGenerator, byte[] bytes) { try { generatorParams.putIfAbsent(getClassName(bytes), new GeneratorParams(generatorStrategy, classGenerator)); } catch (Exception e) { LOGGER.error( "Error saving parameters of a creation of a Cglib proxy", e); } } /** * http://stackoverflow.com/questions/1649674/resolve-class-name-from-bytecode * * @param bytes * @return * @throws Exception */ public static String getClassName(byte[] bytes) throws Exception {<FILL_FUNCTION_BODY>} }
DataInputStream dis = new DataInputStream( new ByteArrayInputStream(bytes)); dis.readLong(); // skip header and class version int cpcnt = (dis.readShort() & 0xffff) - 1; int[] classes = new int[cpcnt]; String[] strings = new String[cpcnt]; for (int i = 0; i < cpcnt; i++) { int t = dis.read(); if (t == 7) classes[i] = dis.readShort() & 0xffff; else if (t == 1) strings[i] = dis.readUTF(); else if (t == 5 || t == 6) { dis.readLong(); i++; } else if (t == 8) dis.readShort(); else dis.readInt(); } dis.readShort(); // skip access flags return strings[classes[(dis.readShort() & 0xffff) - 1] - 1].replace('/', '.');
319
259
578
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-proxy-plugin/src/main/java/org/hotswap/agent/plugin/proxy/hscglib/GeneratorParametersTransformer.java
GeneratorParametersTransformer
transform
class GeneratorParametersTransformer { private static AgentLogger LOGGER = AgentLogger.getLogger(GeneratorParametersTransformer.class); private static Map<ClassLoader, WeakReference<Map<String, Object>>> classLoaderMaps = new WeakHashMap<ClassLoader, WeakReference<Map<String, Object>>>(); /** * Adds bytecode generation call parameter recording * * @param cc * @return * @throws Exception */ public static CtClass transform(CtClass cc) throws Exception {<FILL_FUNCTION_BODY>} /** * Determines if a Class is a Cglib GeneratorStrategy subclass * * @param cc * @return */ private static boolean isGeneratorStrategy(CtClass cc) { String[] interfaces = cc.getClassFile2().getInterfaces(); for (String interfaceName : interfaces) { // We use class name strings because some libraries repackage cglib to a different namespace to avoid // conflicts. if (interfaceName.endsWith(".GeneratorStrategy")) { List<MethodInfo> methodInfos = cc.getClassFile2().getMethods(); for (MethodInfo method : methodInfos) { if (method.getName().equals("generate") && method.getDescriptor().endsWith("[B")) { return true; } } } } return false; } /** * Retrieves GeneratorParams Map from within a ClassLoader * * @param loader * @return Map of Class names and parameters used for Proxy creation */ @SuppressWarnings("unchecked") private static Map<String, Object> getGeneratorParamsMap(ClassLoader loader) { try { WeakReference<Map<String, Object>> mapRef; synchronized (classLoaderMaps) { mapRef = classLoaderMaps.get(loader); if (mapRef == null) { if (ClassLoaderHelper.isClassLoderStarted(loader)) { Map<String, Object> map = (Map<String, Object>) loader .loadClass(GeneratorParametersRecorder.class.getName()).getField("generatorParams") .get(null); mapRef = new WeakReference<Map<String, Object>>(map); classLoaderMaps.put(loader, mapRef); } } } Map<String, Object> map = mapRef != null ? mapRef.get() : null; if (map == null) { return new HashMap<>(); } return map; } catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException | ClassNotFoundException e) { LOGGER.error("Unable to access field with proxy generation parameters. Proxy redefinition failed."); throw new RuntimeException(e); } } /** * Retrieves GeneratorParams from within a ClassLoader * * @param loader * @param name * Class name * @return GeneratorParams instance in this ClassLoader */ public static GeneratorParams getGeneratorParams(ClassLoader loader, String name) { Object generatorParams = getGeneratorParamsMap(loader).get(name); if (generatorParams != null) { try { return GeneratorParams.valueOf(generatorParams); } catch (Exception e) { throw new RuntimeException(e); } } return null; } }
if (isGeneratorStrategy(cc)) { for (CtMethod method : cc.getDeclaredMethods()) { if (!Modifier.isAbstract(method.getModifiers()) && method.getName().equals("generate") && method.getMethodInfo().getDescriptor().endsWith(";)[B")) { cc.defrost(); method.insertAfter("org.hotswap.agent.plugin.proxy.hscglib.GeneratorParametersRecorder.register($0, $1, $_);"); } } } return cc;
858
139
997
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-proxy-plugin/src/main/java/org/hotswap/agent/plugin/proxy/hscglib/GeneratorParams.java
GeneratorParams
valueOf
class GeneratorParams { private Object generator; private Object param; public GeneratorParams(Object generator, Object param) { this.generator = generator; this.param = param; } public Object getGenerator() { return generator; } public void setGenerator(Object generator) { this.generator = generator; } public Object getParam() { return param; } public void setParam(Object params) { this.param = params; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((generator == null) ? 0 : generator.hashCode()); result = prime * result + ((param == null) ? 0 : param.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; GeneratorParams other = (GeneratorParams) obj; if (generator == null) { if (other.generator != null) return false; } else if (!generator.equals(other.generator)) return false; if (param == null) { if (other.param != null) return false; } else if (!param.equals(other.param)) return false; return true; } /** * Return an instance in this classloader * * @param paramsFromOtherClassLoader * instamce in another classlaoder * @return instance in this classloader * @throws Exception */ public static GeneratorParams valueOf(Object paramsFromOtherClassLoader) throws Exception {<FILL_FUNCTION_BODY>} }
if (paramsFromOtherClassLoader.getClass() .getClassLoader() == GeneratorParams.class.getClassLoader()) { return (GeneratorParams) paramsFromOtherClassLoader; } Object params = ReflectionHelper.get(paramsFromOtherClassLoader, "param"); Object generator = ReflectionHelper.get(paramsFromOtherClassLoader, "generator"); return new GeneratorParams(generator, params);
478
107
585
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-proxy-plugin/src/main/java/org/hotswap/agent/plugin/proxy/hscglib/ParentLastClassLoader.java
ParentLastClassLoader
loadClass
class ParentLastClassLoader extends ClassLoader { public static final String[] EXCLUDED_PACKAGES = new String[] { "java.", "javax.", "sun.", "oracle." }; public ParentLastClassLoader(ClassLoader parent) { super(parent); } @Override protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {<FILL_FUNCTION_BODY>} protected Class<?> loadClassFromThisClassLoader(String name) throws ClassNotFoundException { Class<?> result = findLoadedClass(name); if (result != null) { return result; } byte[] bytes = readClass(name); if (bytes != null) { return defineClass(name, bytes, 0, bytes.length); } return null; } protected byte[] readClass(String name) throws ClassNotFoundException { InputStream is = getParent().getResourceAsStream(name.replace('.', '/') + ".class"); if (is == null) { return null; } try { return ProxyTransformationUtils.copyToByteArray(is); } catch (IOException ex) { throw new ClassNotFoundException("Could not read: " + name, ex); } } }
for (String excludedPackage : EXCLUDED_PACKAGES) { if (name.startsWith(excludedPackage)) return super.loadClass(name, resolve); } Class<?> clazz = loadClassFromThisClassLoader(name); if (clazz == null) return super.loadClass(name, resolve); if (resolve) { resolveClass(clazz); } return clazz;
325
115
440
<methods>public void clearAssertionStatus() ,public final java.lang.Package getDefinedPackage(java.lang.String) ,public final java.lang.Package[] getDefinedPackages() ,public java.lang.String getName() ,public final java.lang.ClassLoader getParent() ,public static java.lang.ClassLoader getPlatformClassLoader() ,public java.net.URL getResource(java.lang.String) ,public java.io.InputStream getResourceAsStream(java.lang.String) ,public Enumeration<java.net.URL> getResources(java.lang.String) throws java.io.IOException,public static java.lang.ClassLoader getSystemClassLoader() ,public static java.net.URL getSystemResource(java.lang.String) ,public static java.io.InputStream getSystemResourceAsStream(java.lang.String) ,public static Enumeration<java.net.URL> getSystemResources(java.lang.String) throws java.io.IOException,public final java.lang.Module getUnnamedModule() ,public final boolean isRegisteredAsParallelCapable() ,public Class<?> loadClass(java.lang.String) throws java.lang.ClassNotFoundException,public Stream<java.net.URL> resources(java.lang.String) ,public void setClassAssertionStatus(java.lang.String, boolean) ,public void setDefaultAssertionStatus(boolean) ,public void setPackageAssertionStatus(java.lang.String, boolean) <variables>static final boolean $assertionsDisabled,final java.lang.Object assertionLock,Map<java.lang.String,java.lang.Boolean> classAssertionStatus,private volatile ConcurrentHashMap<?,?> classLoaderValueMap,private final ArrayList<Class<?>> classes,private boolean defaultAssertionStatus,private final java.security.ProtectionDomain defaultDomain,private final jdk.internal.loader.NativeLibraries libraries,private final java.lang.String name,private final java.lang.String nameAndId,private static final java.security.cert.Certificate[] nocerts,private final ConcurrentHashMap<java.lang.String,java.security.cert.Certificate[]> package2certs,private Map<java.lang.String,java.lang.Boolean> packageAssertionStatus,private final ConcurrentHashMap<java.lang.String,java.lang.NamedPackage> packages,private final ConcurrentHashMap<java.lang.String,java.lang.Object> parallelLockMap,private final java.lang.ClassLoader parent,private static volatile java.lang.ClassLoader scl,private final java.lang.Module unnamedModule
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-resteasy-registry-plugin/src/main/java/org/hotswap/agent/plugin/resteasy/RefreshRegistryCommand.java
RefreshRegistryCommand
executeCommand
class RefreshRegistryCommand extends MergeableCommand { private static AgentLogger LOGGER = AgentLogger.getLogger(RefreshRegistryCommand.class); private ClassLoader classLoader; private ServletContext context; private String className; private ServletContainerDispatcher servletContainerDispatcher; private Class<?> original; public void setupCmd(ClassLoader classLoader, Object context, Object servletContainerDispatcher, String className, Class<?> original) { this.classLoader = classLoader; this.context = (ServletContext) context; this.servletContainerDispatcher = (ServletContainerDispatcher) servletContainerDispatcher; this.className = className; this.original = original; } @Override public void executeCommand() {<FILL_FUNCTION_BODY>} @SuppressWarnings("unchecked") private <T> T get(ResourceMethodRegistry rm, String field) { Class<?> c; try { c = classLoader.loadClass(ResourceMethodRegistry.class.getName()); Field f = c.getField(field); return (T) f.get(rm); } catch (ClassNotFoundException | NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) { LOGGER.error("Could not get field {}", e, field); } return null; } private void removeRegistration(ResourceMethodRegistry rm, String path, Method method) { try { if (rm.isWiderMatching()) { RootNode rootNode = get(rm, "rootNode"); rootNode.removeBinding(path, method); } else { String methodpath = method.getAnnotation(Path.class).value(); String classExpression = path.replace(methodpath, ""); if (classExpression.endsWith("/")) { classExpression.substring(0, classExpression.length() - 1); } RootClassNode root = get(rm, "root"); root.removeBinding(classExpression, path, method); } } catch (Exception e) { LOGGER.error("Could not remove method registration from path {}, {}", e, path, method); } } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((classLoader == null) ? 0 : classLoader.hashCode()); result = prime * result + ((className == null) ? 0 : className.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; RefreshRegistryCommand other = (RefreshRegistryCommand) obj; if (classLoader == null) { if (other.classLoader != null) return false; } else if (!classLoader.equals(other.classLoader)) return false; if (className == null) { if (other.className != null) return false; } else if (!className.equals(other.className)) return false; return true; } @Override public String toString() { return "RefreshRegistryCommand [classLoader=" + classLoader + ", className=" + className + "]"; } }
ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader(); LOGGER.debug("Re-Loading class: {} , {} , {}", className, oldClassLoader, classLoader); Thread.currentThread().setContextClassLoader(classLoader); try { Registry registry = (Registry) context.getAttribute(Registry.class.getName()); if (registry == null) { registry = servletContainerDispatcher.getDispatcher().getRegistry(); } //Does original actually represent the... original class???? if(original != null) { registry.removeRegistrations(original); } Class<?> c = classLoader.loadClass(className); //Remove all matching registrations (between old and new class..) registry.removeRegistrations(c); //Iterate over all known methods for this className if (registry instanceof ResourceMethodRegistry) { ResourceMethodRegistry rm = ResourceMethodRegistry.class.cast(registry); Map<String, List<ResourceInvoker>> bounded = rm.getBounded(); for (Entry<String, List<ResourceInvoker>> e : bounded.entrySet()) { LOGGER.debug("Examining {}", e.getKey()); for (ResourceInvoker r : e.getValue()) { if(LOGGER.isLevelEnabled(Level.DEBUG)){ LOGGER.debug("Examining {} for method {} in class {}", e.getKey(), r.getMethod().getName(), r.getMethod().getDeclaringClass()); } if (r.getMethod().getDeclaringClass().getName().equals(className)) { removeRegistration(rm, e.getKey(), r.getMethod()); } } } } //Add the new resource registry.addPerRequestResource(c); } catch (Exception e) { LOGGER.error("Could not reload rest class {}", e, className); } finally { Thread.currentThread().setContextClassLoader(oldClassLoader); }
857
498
1,355
<methods>public non-sealed void <init>() ,public List<org.hotswap.agent.command.Command> getMergedCommands() ,public org.hotswap.agent.command.Command merge(org.hotswap.agent.command.Command) ,public List<org.hotswap.agent.command.Command> popMergedCommands() <variables>List<org.hotswap.agent.command.Command> mergedCommands
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-resteasy-registry-plugin/src/main/java/org/hotswap/agent/plugin/resteasy/ResteasyRegistryPlugin.java
ResteasyRegistryPlugin
refreshClass
class ResteasyRegistryPlugin { private static AgentLogger LOGGER = AgentLogger.getLogger(ResteasyRegistryPlugin.class); private static final String PATH_ANNOTATION = "javax.ws.rs.Path"; @Init ClassLoader appClassLoader; @Init Scheduler scheduler; Object servletContext; Object servletContainerDispatcher; /** * Patch ResourceMethodRegistry, make rootNode && root fields public * * @param ctClass * @param classPool */ @OnClassLoadEvent(classNameRegexp = "org.jboss.resteasy.core.ResourceMethodRegistry") public static void patchResourceMethodRegistry(CtClass ctClass, ClassPool classPool) { try { // Make ResourceMethodRegistry root nodes readable ctClass.getField("rootNode").setModifiers(AccessFlag.PUBLIC); ctClass.getField("root").setModifiers(AccessFlag.PUBLIC); } catch (NotFoundException e) { LOGGER.error("Error patching FilterDispatcher", e); } } /** * * @param ctClass * @param classPool */ @OnClassLoadEvent(classNameRegexp = "org.jboss.resteasy.plugins.server.servlet.FilterDispatcher") public static void patchFilterDispatcher(CtClass ctClass, ClassPool classPool) { try{ CtMethod init = ctClass.getDeclaredMethod("init"); init.insertAfter(""// +"java.lang.ClassLoader $$cl = Thread.currentThread().getContextClassLoader();" // +"java.lang.Object $$servletContext = servletConfig.getServletContext();"// + PluginManagerInvoker.buildInitializePlugin(ResteasyRegistryPlugin.class, "$$cl")// + PluginManagerInvoker.buildCallPluginMethod("$$cl", ResteasyRegistryPlugin.class, "registerContext", "$$servletContext", "java.lang.Object")// + PluginManagerInvoker.buildCallPluginMethod("$$cl", ResteasyRegistryPlugin.class, "registerServletContainerDispatcher", "servletContainerDispatcher", "java.lang.Object")// ); } catch(NotFoundException | CannotCompileException e){ LOGGER.error("Error patching FilterDispatcher", e); } } @OnClassLoadEvent(classNameRegexp = "org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher") public static void patchServletDispatcher(CtClass ctClass, ClassPool classPool){ try{ CtMethod init = ctClass.getDeclaredMethod("init"); init.insertAfter(""// + "java.lang.Object $$servletContext = servletConfig.getServletContext();" // + "java.lang.ClassLoader $$cl = Thread.currentThread().getContextClassLoader();"// + PluginManagerInvoker.buildInitializePlugin(ResteasyRegistryPlugin.class, "$$cl") // + PluginManagerInvoker.buildCallPluginMethod("$$cl", ResteasyRegistryPlugin.class, "registerContext", "$$servletContext", "java.lang.Object") // + PluginManagerInvoker.buildCallPluginMethod("$$cl", ResteasyRegistryPlugin.class, "registerServletContainerDispatcher", "servletContainerDispatcher", "java.lang.Object")// ); } catch(NotFoundException | CannotCompileException e){ LOGGER.error("Error patching HttpServletDispatcher", e); } } public void registerContext(Object servletContext) { this.servletContext = servletContext; LOGGER.info("Registered ServletContext {} ", servletContext); } public void registerServletContainerDispatcher(Object servletContainerDispatcher) { this.servletContainerDispatcher = servletContainerDispatcher; LOGGER.info("Registered ServletContainerDispatcher {} ", servletContainerDispatcher); } @OnClassLoadEvent(classNameRegexp = ".*", events = LoadEvent.REDEFINE) public void entityReload(ClassLoader classLoader, CtClass clazz, Class<?> original) { if (AnnotationHelper.hasAnnotation(original, PATH_ANNOTATION) || AnnotationHelper.hasAnnotation(clazz, PATH_ANNOTATION)) { if(LOGGER.isLevelEnabled(Level.TRACE)) { LOGGER.trace("Reload @Path annotated class {}", clazz.getName()); } refreshClass(classLoader, clazz.getName(), original, 250); } } @OnClassFileEvent(classNameRegexp = ".*", events = { FileEvent.CREATE }) public void newEntity(ClassLoader classLoader, CtClass clazz) throws Exception { if (AnnotationHelper.hasAnnotation(clazz, PATH_ANNOTATION)) { if(LOGGER.isLevelEnabled(Level.TRACE)) { LOGGER.trace("Load @Path annotated class {}", clazz.getName()); } refreshClass(classLoader, clazz.getName(), null, 500); } } private void refreshClass(ClassLoader classLoader, String name, Class<?> original, int timeout) {<FILL_FUNCTION_BODY>} @Init public void initializeInstance(PluginConfiguration pluginConfiguration) { LOGGER.info("ResteasyRegistry plugin initializing"); } }
try { Class<?> cmdClass = Class.forName(RefreshRegistryCommand.class.getName(), true, appClassLoader); Command cmd = (Command) cmdClass.newInstance(); ReflectionHelper.invoke(cmd, cmdClass, "setupCmd", new Class[] { ClassLoader.class, Object.class, Object.class, String.class, java.lang.Class.class }, classLoader, servletContext, servletContainerDispatcher, name, original); scheduler.scheduleCommand(cmd, timeout); } catch (Exception e) { LOGGER.error("refreshClass() exception {}.", e.getMessage()); }
1,379
160
1,539
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-spring-boot-plugin/src/main/java/org/hotswap/agent/plugin/spring/boot/SpringBootPlugin.java
SpringBootPlugin
register
class SpringBootPlugin { private static final AgentLogger LOGGER = AgentLogger.getLogger(SpringBootPlugin.class); @Init Scheduler scheduler; @Init ClassLoader appClassLoader; private final AtomicBoolean isInit = new AtomicBoolean(false); public void init() { if (isInit.compareAndSet(false, true)) { LOGGER.info("Spring Boot plugin initialized"); } } public void init(String version) throws ClassNotFoundException { if (isInit.compareAndSet(false, true)) { LOGGER.info("Spring Boot plugin initialized - Spring Boot core version '{}'", version); } } @OnClassLoadEvent(classNameRegexp = "org.springframework.boot.SpringApplication") public static void register(ClassLoader appClassLoader, CtClass clazz, ClassPool classPool) throws CannotCompileException, NotFoundException {<FILL_FUNCTION_BODY>} }
StringBuilder src = new StringBuilder("{"); // init a spring plugin with every appclassloader src.append(PluginManagerInvoker.buildInitializePlugin(SpringBootPlugin.class)); src.append(PluginManagerInvoker.buildCallPluginMethod(SpringBootPlugin.class, "init", "org.springframework.boot.SpringBootVersion.getVersion()", String.class.getName())); src.append("}"); for (CtConstructor constructor : clazz.getDeclaredConstructors()) { constructor.insertBeforeBody(src.toString()); } CtMethod method = clazz.getDeclaredMethod("createApplicationContext"); method.insertAfter( "{org.hotswap.agent.plugin.spring.boot.listener.PropertySourceChangeListener.register($_);}");
252
203
455
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-spring-boot-plugin/src/main/java/org/hotswap/agent/plugin/spring/boot/env/HotswapSpringProperties.java
HotswapSpringProperties
update
class HotswapSpringProperties extends Properties implements HotswapSpringPropertiesReloader<Properties> { public HotswapSpringProperties() { super(); } public HotswapSpringProperties(Properties properties) { super(); this.putAll(properties); } @Override public void update(Properties newValue) {<FILL_FUNCTION_BODY>} @Override public Properties get() { return this; } }
if (newValue == null || newValue.isEmpty()) { this.clear(); return; } this.clear(); this.putAll(newValue);
129
47
176
<methods>public void <init>() ,public void <init>(int) ,public void <init>(java.util.Properties) ,public synchronized void clear() ,public synchronized java.lang.Object clone() ,public synchronized java.lang.Object compute(java.lang.Object, BiFunction<? super java.lang.Object,? super java.lang.Object,?>) ,public synchronized java.lang.Object computeIfAbsent(java.lang.Object, Function<? super java.lang.Object,?>) ,public synchronized java.lang.Object computeIfPresent(java.lang.Object, BiFunction<? super java.lang.Object,? super java.lang.Object,?>) ,public boolean contains(java.lang.Object) ,public boolean containsKey(java.lang.Object) ,public boolean containsValue(java.lang.Object) ,public Enumeration<java.lang.Object> elements() ,public Set<Entry<java.lang.Object,java.lang.Object>> entrySet() ,public synchronized boolean equals(java.lang.Object) ,public synchronized void forEach(BiConsumer<? super java.lang.Object,? super java.lang.Object>) ,public java.lang.Object get(java.lang.Object) ,public java.lang.Object getOrDefault(java.lang.Object, java.lang.Object) ,public java.lang.String getProperty(java.lang.String) ,public java.lang.String getProperty(java.lang.String, java.lang.String) ,public synchronized int hashCode() ,public boolean isEmpty() ,public Set<java.lang.Object> keySet() ,public Enumeration<java.lang.Object> keys() ,public void list(java.io.PrintStream) ,public void list(java.io.PrintWriter) ,public synchronized void load(java.io.Reader) throws java.io.IOException,public synchronized void load(java.io.InputStream) throws java.io.IOException,public synchronized void loadFromXML(java.io.InputStream) throws java.io.IOException, java.util.InvalidPropertiesFormatException,public synchronized java.lang.Object merge(java.lang.Object, java.lang.Object, BiFunction<? super java.lang.Object,? super java.lang.Object,?>) ,public Enumeration<?> propertyNames() ,public synchronized java.lang.Object put(java.lang.Object, java.lang.Object) ,public synchronized void putAll(Map<?,?>) ,public synchronized java.lang.Object putIfAbsent(java.lang.Object, java.lang.Object) ,public synchronized java.lang.Object remove(java.lang.Object) ,public synchronized boolean remove(java.lang.Object, java.lang.Object) ,public synchronized java.lang.Object replace(java.lang.Object, java.lang.Object) ,public synchronized boolean replace(java.lang.Object, java.lang.Object, java.lang.Object) ,public synchronized void replaceAll(BiFunction<? super java.lang.Object,? super java.lang.Object,?>) ,public void save(java.io.OutputStream, java.lang.String) ,public synchronized java.lang.Object setProperty(java.lang.String, java.lang.String) ,public int size() ,public void store(java.io.Writer, java.lang.String) throws java.io.IOException,public void store(java.io.OutputStream, java.lang.String) throws java.io.IOException,public void storeToXML(java.io.OutputStream, java.lang.String) throws java.io.IOException,public void storeToXML(java.io.OutputStream, java.lang.String, java.lang.String) throws java.io.IOException,public void storeToXML(java.io.OutputStream, java.lang.String, java.nio.charset.Charset) throws java.io.IOException,public Set<java.lang.String> stringPropertyNames() ,public synchronized java.lang.String toString() ,public Collection<java.lang.Object> values() <variables>private static final jdk.internal.misc.Unsafe UNSAFE,protected volatile java.util.Properties defaults,private volatile transient ConcurrentHashMap<java.lang.Object,java.lang.Object> map,private static final long serialVersionUID
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-spring-boot-plugin/src/main/java/org/hotswap/agent/plugin/spring/boot/env/HotswapSpringReloadMap.java
HotswapSpringReloadMap
update
class HotswapSpringReloadMap<K, V> implements Map<K, V>, HotswapSpringPropertiesReloader<Map<K, V>> { private Map<K, V> value; public HotswapSpringReloadMap(Map<K, V> value) { this.value = value; } public HotswapSpringReloadMap() { this.value = new HashMap<>(); } @Override public int size() { return this.value.size(); } @Override public boolean isEmpty() { return this.value.isEmpty(); } @Override public boolean containsKey(Object key) { return this.value.containsKey(key); } @Override public boolean containsValue(Object value) { return this.value.containsValue(value); } @Override public V get(Object key) { return this.value.get(key); } @Override public V put(K key, V value) { throw new UnsupportedOperationException("put is not supported"); } @Override public V remove(Object key) { throw new UnsupportedOperationException("put is not supported"); } @Override public void putAll(Map<? extends K, ? extends V> m) { throw new UnsupportedOperationException("put is not supported"); } @Override public void clear() { throw new UnsupportedOperationException("put is not supported"); } @Override public Set<K> keySet() { return this.value.keySet(); } @Override public Collection<V> values() { return this.value.values(); } @Override public Set<Entry<K, V>> entrySet() { return this.value.entrySet(); } @SuppressWarnings("unchecked") @Override public void update(Map<K, V> newValue) {<FILL_FUNCTION_BODY>} @Override public Map<K, V> get() { return this; } }
if (newValue == null || newValue.isEmpty()) { this.value = (newValue == null ? Collections.EMPTY_MAP : newValue); return; } this.value = newValue;
555
58
613
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-spring-boot-plugin/src/main/java/org/hotswap/agent/plugin/spring/boot/env/ListPropertySourceReloader.java
ListPropertySourceReloader
update
class ListPropertySourceReloader<T> implements HotswapSpringPropertiesReloader<List<Map<String, T>>> { private static AgentLogger LOGGER = AgentLogger.getLogger(ListPropertySourceReloader.class); protected final String name; protected final Resource resource; protected List<Map<String, T>> hotswapMapList; public ListPropertySourceReloader(String name, Resource resource) { this.name = name; this.resource = resource; } Map<String, T> createMap(Map map) { return new HotswapSpringReloadMap<>(map); } void updateItemValue(Map hotswapMap, Map newHotswapMap) { if (hotswapMap instanceof HotswapSpringReloadMap) { ((HotswapSpringReloadMap) hotswapMap).update(newHotswapMap); } } @Override public void update(List<Map<String, T>> newValue) {<FILL_FUNCTION_BODY>} @Override public List<Map<String, T>> get() { return hotswapMapList; } }
if (newValue == null || newValue.isEmpty()) { hotswapMapList = (newValue == null ? Collections.emptyList() : newValue); return; } if (hotswapMapList == null) { synchronized (this) { if (hotswapMapList == null) { hotswapMapList = new ArrayList<>(newValue.size()); for (Map<String, ?> map : newValue) { hotswapMapList.add(createMap(map)); } return; } } } for (int i = 0; i < hotswapMapList.size(); i++) { Map<String, ?> hotswapMap = hotswapMapList.get(i); Map<String, ?> newHotswapMap = newValue.get(i); updateItemValue(hotswapMap, newHotswapMap); }
311
245
556
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-spring-boot-plugin/src/main/java/org/hotswap/agent/plugin/spring/boot/env/v1/PropertiesPropertySourceLoader.java
PropertiesPropertySourceLoader
doLoad
class PropertiesPropertySourceLoader extends BasePropertiesPropertySourceLoader<Properties> { private static AgentLogger LOGGER = AgentLogger.getLogger(PropertiesPropertySourceLoader.class); final String name; final Resource resource; final String profile; public PropertiesPropertySourceLoader(String name, Resource resource, String profile) { super(new HotswapSpringProperties()); this.name = name; this.resource = resource; this.profile = profile; } protected Properties doLoad() {<FILL_FUNCTION_BODY>} }
try { Class clazz = Class.forName("org.springframework.core.io.support.PropertiesLoaderUtils"); return (Properties) ReflectionHelper.invoke(null, clazz, "loadProperties", new Class[]{Resource.class}, resource); } catch (ClassNotFoundException e) { throw new RuntimeException(e); }
139
87
226
<methods>public void <init>(HotswapSpringPropertiesReloader<java.util.Properties>) ,public final java.util.Properties load() ,public final void reload() <variables>protected HotswapSpringPropertiesReloader<java.util.Properties> properties
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-spring-boot-plugin/src/main/java/org/hotswap/agent/plugin/spring/boot/env/v1/YamlPropertySourceLoader.java
YamlPropertySourceLoader
doLoad
class YamlPropertySourceLoader extends BasePropertiesPropertySourceLoader<Map<String, Object>> { private static AgentLogger LOGGER = AgentLogger.getLogger(YamlPropertySourceLoader.class); final String profile; final Resource resource; public YamlPropertySourceLoader(String name, Resource resource, String profile) { super(new HotswapSpringReloadMap()); this.profile = profile; this.resource = resource; } protected Map<String, Object> doLoad() {<FILL_FUNCTION_BODY>} }
try { Object target = ReflectionHelper.invokeConstructor("org.springframework.boot.env.YamlPropertySourceLoader$Processor", this.getClass().getClassLoader(), new Class[]{Resource.class, String.class}, resource, profile); return (Map<String, Object>) ReflectionHelper.invoke(target, "process"); } catch (Exception e) { throw new RuntimeException(e); }
140
104
244
<methods>public void <init>(HotswapSpringPropertiesReloader<Map<java.lang.String,java.lang.Object>>) ,public final Map<java.lang.String,java.lang.Object> load() ,public final void reload() <variables>protected HotswapSpringPropertiesReloader<Map<java.lang.String,java.lang.Object>> properties
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-spring-boot-plugin/src/main/java/org/hotswap/agent/plugin/spring/boot/env/v2/LowVersionPropertiesPropertySourceLoader.java
LowVersionPropertiesPropertySourceLoader
doLoad
class LowVersionPropertiesPropertySourceLoader extends BasePropertiesPropertySourceLoader<Map<String, ?>> { private static AgentLogger LOGGER = AgentLogger.getLogger(LowVersionPropertiesPropertySourceLoader.class); private PropertiesPropertySourceLoader propertiesPropertySourceLoader; private HotswapSpringReloadMap hotswapSpringReloadMap; private Resource resource; public LowVersionPropertiesPropertySourceLoader(PropertiesPropertySourceLoader propertiesPropertySourceLoader, String name, Resource resource) { super(new HotswapSpringReloadMap()); this.propertiesPropertySourceLoader = propertiesPropertySourceLoader; this.resource = resource; } /** * spring boot 2.0 lower version * * @return */ protected Map<String, ?> doLoad() {<FILL_FUNCTION_BODY>} }
return (Map<String, ?>) ReflectionHelper.invoke(propertiesPropertySourceLoader, PropertiesPropertySourceLoader.class, "loadProperties", new Class[]{Resource.class}, resource);
212
47
259
<methods>public void <init>(HotswapSpringPropertiesReloader<Map<java.lang.String,?>>) ,public final Map<java.lang.String,?> load() ,public final void reload() <variables>protected HotswapSpringPropertiesReloader<Map<java.lang.String,?>> properties
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-spring-boot-plugin/src/main/java/org/hotswap/agent/plugin/spring/boot/env/v2/PropertiesPropertySourceLoader.java
PropertiesPropertySourceLoader
doLoad
class PropertiesPropertySourceLoader extends BasePropertiesPropertySourceLoader<List<Map<String, ?>>> { private static AgentLogger LOGGER = AgentLogger.getLogger(PropertiesPropertySourceLoader.class); private org.springframework.boot.env.PropertiesPropertySourceLoader propertiesPropertySourceLoader; private Resource resource; public PropertiesPropertySourceLoader( org.springframework.boot.env.PropertiesPropertySourceLoader propertiesPropertySourceLoader, String name, Resource resource) { super(new ListPropertySourceReloader(name, resource)); this.propertiesPropertySourceLoader = propertiesPropertySourceLoader; this.resource = resource; } /** * spring boot 2.x higher version * * @return */ protected List<Map<String, ?>> doLoad() {<FILL_FUNCTION_BODY>} }
return (List<Map<String, ?>>) ReflectionHelper.invoke(propertiesPropertySourceLoader, org.springframework.boot.env.PropertiesPropertySourceLoader.class, "loadProperties", new Class[]{Resource.class}, resource);
207
57
264
<methods>public void <init>(HotswapSpringPropertiesReloader<List<Map<java.lang.String,?>>>) ,public final List<Map<java.lang.String,?>> load() ,public final void reload() <variables>protected HotswapSpringPropertiesReloader<List<Map<java.lang.String,?>>> properties
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-spring-boot-plugin/src/main/java/org/hotswap/agent/plugin/spring/boot/env/v2/YamlPropertySourceLoader.java
YamlPropertySourceLoader
doLoad
class YamlPropertySourceLoader extends BasePropertiesPropertySourceLoader<List<Map<String, Object>>> { private static AgentLogger LOGGER = AgentLogger.getLogger(YamlPropertySourceLoader.class); private Resource resource; public YamlPropertySourceLoader(String name, Resource resource) { super(new ListPropertySourceReloader(name, resource)); this.resource = resource; } protected List<Map<String, Object>> doLoad() {<FILL_FUNCTION_BODY>} }
try { Object yamlLoader = ReflectionHelper.invokeConstructor( "org.springframework.boot.env.OriginTrackedYamlLoader", this.getClass().getClassLoader(), new Class[]{Resource.class}, resource); return (List<Map<String, Object>>) ReflectionHelper.invoke(yamlLoader, "load"); } catch (Exception e) { LOGGER.error("load yaml error, resource: {}", e, resource); } return null;
128
122
250
<methods>public void <init>(HotswapSpringPropertiesReloader<List<Map<java.lang.String,java.lang.Object>>>) ,public final List<Map<java.lang.String,java.lang.Object>> load() ,public final void reload() <variables>protected HotswapSpringPropertiesReloader<List<Map<java.lang.String,java.lang.Object>>> properties
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-spring-boot-plugin/src/main/java/org/hotswap/agent/plugin/spring/boot/listener/PropertySourceChangeListener.java
PropertySourceChangeListener
equals
class PropertySourceChangeListener implements SpringListener<SpringEvent<?>> { private final static AgentLogger LOGGER = AgentLogger.getLogger(PropertySourceChangeListener.class); private final DefaultListableBeanFactory beanFactory; public static void register(ConfigurableApplicationContext context) { ConfigurableListableBeanFactory configurableListableBeanFactory = context.getBeanFactory(); if (!(configurableListableBeanFactory instanceof DefaultListableBeanFactory)) { LOGGER.debug( "beanFactory is not DefaultListableBeanFactory, skip register PropertySourceChangeBootListener, {}", ObjectUtils.identityToString(configurableListableBeanFactory)); return; } LOGGER.debug("register PropertySourceChangeBootListener, {}", ObjectUtils.identityToString(configurableListableBeanFactory)); PropertySourceChangeListener propertySourceChangeListener = new PropertySourceChangeListener( (DefaultListableBeanFactory)configurableListableBeanFactory); // add instance to map and instance SpringEventSource.INSTANCE.addListener(propertySourceChangeListener); } public PropertySourceChangeListener(DefaultListableBeanFactory beanFactory) { this.beanFactory = beanFactory; } @Override public DefaultListableBeanFactory beanFactory() { return beanFactory; } @Override public void onEvent(SpringEvent<?> event) { if (event instanceof PropertiesChangeEvent) { refreshConfigurationProperties(event.getBeanFactory()); } } private void refreshConfigurationProperties(ConfigurableListableBeanFactory eventBeanFactory) { for (String singleton : beanFactory.getSingletonNames()) { Object bean = beanFactory.getSingleton(singleton); Class<?> beanClass = ClassUtils.getUserClass(bean.getClass()); if (AnnotationHelper.hasAnnotation(beanClass, ConfigurationProperties.class.getName())) { LOGGER.debug("refresh configuration properties: {}", beanClass); String[] beanNames = beanFactory.getBeanNamesForType(beanClass); if (beanNames != null && beanNames.length > 0) { SpringEventSource.INSTANCE.fireEvent(new BeanChangeEvent(beanNames, eventBeanFactory)); } } } } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hash(beanFactory); } }
if (this == o) {return true;} if (!(o instanceof PropertySourceChangeListener)) {return false;} PropertySourceChangeListener that = (PropertySourceChangeListener)o; return Objects.equals(beanFactory, that.beanFactory);
603
63
666
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-spring-boot-plugin/src/main/java/org/hotswap/agent/plugin/spring/boot/transformers/PropertySourceTransformer.java
PropertySourceTransformer
transformPropertySource
class PropertySourceTransformer { private static AgentLogger LOGGER = AgentLogger.getLogger(PropertySourceTransformer.class); @OnClassLoadEvent(classNameRegexp = "org.springframework.core.env.MapPropertySource") public static void transformMapPropertySource(CtClass clazz, ClassPool classPool) throws NotFoundException, CannotCompileException { transformPropertySource(clazz, classPool); LOGGER.debug("Patch org.springframework.boot.env.MapPropertySource success"); } @OnClassLoadEvent(classNameRegexp= "org.springframework.boot.env.OriginTrackedMapPropertySource") public static void transformOriginTrackedMapPropertySource(CtClass clazz, ClassPool classPool) throws NotFoundException, CannotCompileException { transformPropertySource(clazz, classPool); LOGGER.debug("Patch org.springframework.boot.env.OriginTrackedMapPropertySource success"); } private static void transformPropertySource(CtClass clazz, ClassPool classPool) throws NotFoundException, CannotCompileException {<FILL_FUNCTION_BODY>} }
clazz.addInterface(classPool.get("org.hotswap.agent.plugin.spring.transformers.api.ReloadablePropertySource")); clazz.addField(CtField.make("private org.hotswap.agent.plugin.spring.api.PropertySourceReloader reload;", clazz)); clazz.addMethod(CtMethod.make("public void setReload(org.hotswap.agent.plugin.spring.api.PropertySourceReloader r) { this.reload = r; }", clazz)); clazz.addMethod(CtMethod.make("public void reload() { if (this.reload != null) {this.reload.reload();} }", clazz));
274
183
457
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-spring-plugin/src/main/java/org/hotswap/agent/plugin/spring/SpringBeanClassFileTransformer.java
SpringBeanClassFileTransformer
transform
class SpringBeanClassFileTransformer implements HaClassFileTransformer { private ClassLoader appClassLoader; private Scheduler scheduler; private String basePackage; public SpringBeanClassFileTransformer(ClassLoader appClassLoader, Scheduler scheduler, String basePackage) { this.appClassLoader = appClassLoader; this.scheduler = scheduler; this.basePackage = basePackage; } @Override public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) {<FILL_FUNCTION_BODY>} @Override public boolean isForRedefinitionOnly() { return true; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SpringBeanClassFileTransformer that = (SpringBeanClassFileTransformer) o; return Objects.equals(appClassLoader, that.appClassLoader) && Objects.equals(basePackage, that.basePackage); } @Override public int hashCode() { return Objects.hash(appClassLoader, basePackage); } }
if (classBeingRedefined != null) { SpringChangesAnalyzer analyzer = new SpringChangesAnalyzer(appClassLoader); if (analyzer.isReloadNeeded(classBeingRedefined, classfileBuffer)) { scheduler.scheduleCommand(new ClassPathBeanRefreshCommand(classBeingRedefined.getClassLoader(), basePackage, className, classfileBuffer, scheduler)); } } return classfileBuffer;
321
116
437
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-spring-plugin/src/main/java/org/hotswap/agent/plugin/spring/SpringChangesAnalyzer.java
SpringChangesAnalyzer
isSyntheticClass
class SpringChangesAnalyzer { private static AgentLogger LOGGER = AgentLogger.getLogger(SpringPlugin.class); private ClassPool cp; public SpringChangesAnalyzer(final ClassLoader classLoader) { this.cp = new ClassPool() { @Override public ClassLoader getClassLoader() { return classLoader; } }; cp.appendSystemPath(); cp.appendClassPath(new LoaderClassPath(classLoader)); } public boolean isReloadNeeded(Class<?> classBeingRedefined, byte[] classfileBuffer) { if (classBeingRedefined.isSynthetic() || isSyntheticClass(classBeingRedefined)) return false; return classChangeNeedsReload(classBeingRedefined, classfileBuffer); } private boolean classChangeNeedsReload(Class<?> classBeingRedefined, byte[] classfileBuffer) { CtClass makeClass = null; try { makeClass = cp.makeClass(new java.io.ByteArrayInputStream(classfileBuffer)); return ClassSignatureComparer.isPoolClassDifferent(classBeingRedefined, cp); } catch (Exception e) { LOGGER.error("Error analyzing class {} for reload necessity. Defaulting to yes.", e, classBeingRedefined.getName()); } finally { if (makeClass != null) { makeClass.detach(); } } return true; } protected boolean isSyntheticClass(Class<?> classBeingRedefined) {<FILL_FUNCTION_BODY>} }
return classBeingRedefined.getSimpleName().contains("$$_javassist") || classBeingRedefined.getName().startsWith("com.sun.proxy.$Proxy") || classBeingRedefined.getSimpleName().contains("$$Enhancer") || classBeingRedefined.getSimpleName().contains("$$_jvst") // javassist proxy || classBeingRedefined.getSimpleName().contains("$HibernateProxy$") ;
409
119
528
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-spring-plugin/src/main/java/org/hotswap/agent/plugin/spring/core/AutowiredAnnotationProcessor.java
AutowiredAnnotationProcessor
processSingletonBeanInjection
class AutowiredAnnotationProcessor { private static AgentLogger LOGGER = AgentLogger.getLogger(AutowiredAnnotationProcessor.class); public static void processSingletonBeanInjection(DefaultListableBeanFactory beanFactory) {<FILL_FUNCTION_BODY>} }
try { Map<String, AutowiredAnnotationBeanPostProcessor> postProcessors = beanFactory.getBeansOfType( AutowiredAnnotationBeanPostProcessor.class); if (postProcessors.isEmpty()) { LOGGER.debug("AutowiredAnnotationProcessor not exist"); return; } AutowiredAnnotationBeanPostProcessor postProcessor = postProcessors.values().iterator().next(); boolean postProcessPropertyValuesNotExists = false; for (String beanName : beanFactory.getBeanDefinitionNames()) { Object object = beanFactory.getSingleton(beanName); if (object != null) { if (postProcessPropertyValuesNotExists) { // spring 6.x postProcessor.postProcessProperties(null, object, beanName); continue; } try { // from spring 3.2.x to 5.x postProcessor.postProcessPropertyValues(null, null, object, beanName); } catch (NoSuchMethodError e) { // spring 6.x postProcessor.postProcessProperties(null, object, beanName); postProcessPropertyValuesNotExists = true; } } } } catch (Throwable e) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("AutowiredAnnotationProcessor maybe not exist", e); } else { LOGGER.warning("AutowiredAnnotationProcessor maybe not exist : " + e.getMessage()); } }
68
366
434
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-spring-plugin/src/main/java/org/hotswap/agent/plugin/spring/core/BeanDefinitionProcessor.java
BeanDefinitionProcessor
registerBeanDefinition
class BeanDefinitionProcessor { private static final AgentLogger LOGGER = AgentLogger.getLogger(BeanDefinitionProcessor.class); public static void registerBeanDefinition(DefaultListableBeanFactory defaultListableBeanFactory, String beanName, BeanDefinition beanDefinition) {<FILL_FUNCTION_BODY>} public static void removeBeanDefinition(DefaultListableBeanFactory defaultListableBeanFactory, String beanName) { LOGGER.debug("remove BeanDefinition '{}' from '{}'", beanName, ObjectUtils.identityToString(defaultListableBeanFactory)); } }
LOGGER.debug("register new BeanDefinition '{}' into '{}'", beanName, ObjectUtils.identityToString(defaultListableBeanFactory)); org.hotswap.agent.plugin.spring.files.XmlBeanDefinitionScannerAgent.registerBean(beanName, beanDefinition);
141
73
214
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-spring-plugin/src/main/java/org/hotswap/agent/plugin/spring/core/BeanFactoryProcessor.java
BeanFactoryProcessor
isAllowBeanDefinitionOverriding
class BeanFactoryProcessor { private static AgentLogger LOGGER = AgentLogger.getLogger(BeanFactoryProcessor.class); public static void removeBeanDefinition(DefaultListableBeanFactory beanFactory, String beanName) { resetEmbeddedValueResolvers(beanFactory, beanName); beanFactory.removeBeanDefinition(beanName); } public static void destroySingleton(DefaultListableBeanFactory beanFactory, String beanName) { // remove embeddedValueResolvers cache in PlaceholderConfigurerSupport resetEmbeddedValueResolvers(beanFactory, beanName); beanFactory.destroySingleton(beanName); } /** * invoked by @see org.hotswap.agent.plugin.spring.transformers.BeanFactoryTransformer * @param beanFactory * @param beanName */ public static void postProcessDestroySingleton(DefaultSingletonBeanRegistry beanFactory, String beanName) { // check if reload , then log if (beanFactory instanceof ConfigurableListableBeanFactory && BeanFactoryAssistant.getBeanFactoryAssistant((ConfigurableListableBeanFactory)beanFactory).isReload()) { LOGGER.info("destroy bean '{}' from '{}'", beanName, ObjectUtils.identityToString(beanFactory)); } if (beanFactory instanceof BeanFactoryLifecycle) { ((BeanFactoryLifecycle)beanFactory).hotswapAgent$destroyBean(beanName); } } /** * invoked by @see org.hotswap.agent.plugin.spring.transformers.BeanFactoryTransformer * * @param beanFactory * @param beanName */ public static void postProcessCreateBean(AbstractAutowireCapableBeanFactory beanFactory, String beanName, RootBeanDefinition mbd) { // check if reload , then log if (beanFactory instanceof ConfigurableListableBeanFactory && BeanFactoryAssistant.getBeanFactoryAssistant((ConfigurableListableBeanFactory)beanFactory).isReload() && mbd.isSingleton()) { LOGGER.info("create new singleton bean '{}' from '{}'", beanName, ObjectUtils.identityToString(beanFactory)); } } public static boolean needReloadOnConstructor(DefaultListableBeanFactory beanFactory, AbstractBeanDefinition currentBeanDefinition, String beanName, Predicate<Constructor<?>[]> predicate) { Constructor<?>[] constructors = determineConstructors(beanFactory, beanName); if (constructors != null && constructors.length > 0) { return predicate.test(constructors); } return false; } private static Constructor<?>[] determineConstructors(DefaultListableBeanFactory beanFactory, String beanName) { Class<?> beanClass = resolveBeanClass(beanFactory, beanName); if (beanClass == null) { return null; } Method method = ReflectionUtils.findMethod(beanFactory.getClass(), "determineConstructorsFromBeanPostProcessors", Class.class, String.class); if (method == null) { return null; } try { method.setAccessible(true); return (Constructor<?>[]) method.invoke(beanFactory, beanClass, beanName); } catch (Exception e) { LOGGER.error("determineConstructorsFromBeanPostProcessors error", e); } return null; } private static Class<?> resolveBeanClass(DefaultListableBeanFactory beanFactory, String beanName) { Method resolveBeanClassMethod = ReflectionUtils.findMethod(beanFactory.getClass(), "resolveBeanClass", RootBeanDefinition.class, String.class, Class[].class); if (resolveBeanClassMethod != null) { resolveBeanClassMethod.setAccessible(true); Class<?> beanClass = null; BeanDefinition rBeanDefinition = beanFactory.getMergedBeanDefinition(beanName); try { if (rBeanDefinition != null) { beanClass = (Class<?>) resolveBeanClassMethod.invoke(beanFactory, rBeanDefinition, beanName, new Class[]{}); } return beanClass; } catch (Exception e) { LOGGER.warning("resolveBeanClass error", e); } } return null; } private static void resetEmbeddedValueResolvers(DefaultListableBeanFactory beanFactory, String beanName) { Object target = beanFactory.getSingleton(beanName); if (target != null && target instanceof PlaceholderConfigurerSupport && target instanceof ValueResolverSupport) { ValueResolverSupport placeholderConfigurerSupport = (ValueResolverSupport) target; Field field = ReflectionUtils.findField(beanFactory.getClass(), "embeddedValueResolvers"); if (field != null) { ReflectionUtils.makeAccessible(field); List<StringValueResolver> embeddedValueResolvers = ReflectionUtils.getField(field, beanFactory); embeddedValueResolvers.removeAll(placeholderConfigurerSupport.valueResolvers()); } } } public static boolean isAllowBeanDefinitionOverriding(DefaultListableBeanFactory beanFactory) {<FILL_FUNCTION_BODY>} public static void setAllowBeanDefinitionOverriding(DefaultListableBeanFactory beanFactory, boolean allowEagerClassLoading) { beanFactory.setAllowBeanDefinitionOverriding(allowEagerClassLoading); } public static BeanDefinition getBeanDefinition(ConfigurableListableBeanFactory beanFactory, String beanName) { if (beanName.startsWith("&")) { beanName = beanName.substring(1); } return beanFactory.getBeanDefinition(beanName); } }
// org.springframework.beans.factory.support.DefaultListableBeanFactory.isAllowBeanDefinitionOverriding is introduced in spring 4.1.2 Object target = ReflectionHelper.getNoException(beanFactory, beanFactory.getClass(), "allowBeanDefinitionOverriding"); if (target == null) { return false; } return (boolean) target;
1,422
94
1,516
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-spring-plugin/src/main/java/org/hotswap/agent/plugin/spring/core/ConfigurationClassPostProcessorEnhance.java
ConfigurationClassPostProcessorEnhance
postProcess
class ConfigurationClassPostProcessorEnhance { private static final AgentLogger LOGGER = AgentLogger.getLogger(ConfigurationClassPostProcessorEnhance.class); private static final Map<BeanDefinitionRegistry,ConfigurationClassPostProcessorEnhance> INSTANCES = new ConcurrentHashMap<>(4); private static final String CONFIGURATION_CLASS_ATTRIBUTE = Conventions.getQualifiedAttributeName(ConfigurationClassPostProcessor.class, "configurationClass"); private volatile ConfigurationClassPostProcessor processor; public static ConfigurationClassPostProcessorEnhance getInstance(BeanDefinitionRegistry registry) { ConfigurationClassPostProcessorEnhance result = INSTANCES.putIfAbsent(registry, new ConfigurationClassPostProcessorEnhance()); if (result == null) { result = INSTANCES.get(registry); } return result; } private ConfigurationClassPostProcessorEnhance() { } public void setProcessor(ConfigurationClassPostProcessor processor) { LOGGER.trace("ConfigurationClassPostProcessorAgent.setProcessor({})", processor); this.processor = processor; } public ConfigurationClassPostProcessor getProcessor() { return processor; } public void resetConfigurationClassPostProcessor(BeanDefinitionRegistry registry) { LOGGER.trace("ConfigurationClassPostProcessorAgent.resetConfigurationClassPostProcessor({})"); if (processor == null) { return; } resetCachingMetadataReaderFactoryCache(); resetBeanNameCache(); resetBeanFactoryCache(registry); } public void postProcess(BeanDefinitionRegistry registry, String beanName) { if (processor == null) { return; } resetCachingMetadataReaderFactoryCache(); resetBeanNameCache(); resetBeanFactoryCache(registry); removeBeanAttribute(registry, beanName); processor.processConfigBeanDefinitions(registry); } public void postProcess(BeanDefinitionRegistry registry) {<FILL_FUNCTION_BODY>} private MetadataReaderFactory getMetadataReaderFactory() { return (MetadataReaderFactory) ReflectionHelper.getNoException(processor, ConfigurationClassPostProcessor.class, "metadataReaderFactory"); } private void resetCachingMetadataReaderFactoryCache() { LOGGER.trace("Clearing MetadataReaderFactory cache"); MetadataReaderFactory metadataReaderFactory = getMetadataReaderFactory(); if (metadataReaderFactory != null) { try { ReflectionHelper.invoke(metadataReaderFactory, "clearCache"); } catch (Exception e) { LOGGER.debug("Unable to clear MetadataReaderFactory cache"); } } } private void resetBeanFactoryCache(BeanDefinitionRegistry registry) { LOGGER.trace("Clearing BeanFactory cache"); DefaultListableBeanFactory beanFactory = RegistryUtils.maybeRegistryToBeanFactory(registry); if (beanFactory == null) { return; } beanFactory.setAllowBeanDefinitionOverriding(true); resetFactoryMethodCandidateCache(beanFactory); } private void removeBeanAttribute(BeanDefinitionRegistry registry, String beanName) { BeanDefinition bd = registry.getBeanDefinition(beanName); if (bd.hasAttribute(CONFIGURATION_CLASS_ATTRIBUTE)) { LOGGER.trace("Removing attribute '{}' from bean definition '{}'", CONFIGURATION_CLASS_ATTRIBUTE, beanName); bd.removeAttribute(CONFIGURATION_CLASS_ATTRIBUTE); } } private void resetFactoryMethodCandidateCache(DefaultListableBeanFactory factory) { Map<Class<?>, Method[]> cache = (Map<Class<?>, Method[]>) ReflectionHelper.getNoException(factory, AbstractAutowireCapableBeanFactory.class, "factoryMethodCandidateCache"); if (cache != null) { LOGGER.trace("Cache cleared: AbstractAutowireCapableBeanFactory.factoryMethodCandidateCache"); cache.clear(); } } private void resetBeanNameCache() { Map<Method, String> cache = (Map<Method, String>) ReflectionHelper.getNoException(null, "org.springframework.context.annotation.BeanAnnotationHelper", processor.getClass().getClassLoader(), "beanNameCache"); if (cache != null) { LOGGER.trace("Cache cleared: BeanAnnotationHelper.beanNameCache"); cache.clear(); } } }
LOGGER.trace("ConfigurationClassPostProcessorAgent.postProcess({})", ObjectUtils.identityToString(registry)); if (processor == null) { return; } resetCachingMetadataReaderFactoryCache(); resetBeanNameCache(); resetBeanFactoryCache(registry); processor.processConfigBeanDefinitions(registry);
1,109
89
1,198
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-spring-plugin/src/main/java/org/hotswap/agent/plugin/spring/core/ResetAnnotationCache.java
ResetAnnotationCache
resetAnnotationScanner
class ResetAnnotationCache { private static AgentLogger LOGGER = AgentLogger.getLogger(ResetAnnotationCache.class); /** * Reset Spring annotation scanner. * @since 5.x */ public static void resetAnnotationScanner(DefaultListableBeanFactory defaultListableBeanFactory) {<FILL_FUNCTION_BODY>} }
Map<Method, String> declaredAnnotationCache = (Map<Method, String>) ReflectionHelper.getNoException(null, "org.springframework.core.annotation.AnnotationsScanner", defaultListableBeanFactory.getClass().getClassLoader(), "declaredAnnotationCache"); if (declaredAnnotationCache != null) { LOGGER.trace("Cache cleared: AnnotationsScanner.beanNameCache"); declaredAnnotationCache.clear(); } Map<Method, String> baseTypeMethodsCache = (Map<Method, String>) ReflectionHelper.getNoException(null, "org.springframework.core.annotation.AnnotationsScanner", defaultListableBeanFactory.getClass().getClassLoader(), "baseTypeMethodsCache"); if (baseTypeMethodsCache != null) { LOGGER.trace("Cache cleared: BeanAnnotationHelper.baseTypeMethodsCache"); baseTypeMethodsCache.clear(); }
90
227
317
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-spring-plugin/src/main/java/org/hotswap/agent/plugin/spring/core/ResetBeanFactoryPostProcessorCaches.java
ResetBeanFactoryPostProcessorCaches
clearSetFieldOfConfigurationClassPostProcessor
class ResetBeanFactoryPostProcessorCaches { private static final AgentLogger LOGGER = AgentLogger.getLogger(ResetBeanFactoryPostProcessorCaches.class); public static void reset(DefaultListableBeanFactory beanFactory) { resetConfigurationClassPostProcessorCache(beanFactory); } private static void resetConfigurationClassPostProcessorCache(DefaultListableBeanFactory beanFactory) { LOGGER.trace("Resetting ConfigurationClassPostProcessor caches"); int factoryId = System.identityHashCode(beanFactory); try { ConfigurationClassPostProcessor ccpp = beanFactory.getBean(ConfigurationClassPostProcessor.class); clearSetFieldOfConfigurationClassPostProcessor(ccpp, "factoriesPostProcessed", factoryId); clearSetFieldOfConfigurationClassPostProcessor(ccpp, "registriesPostProcessed", factoryId); } catch (NoSuchBeanDefinitionException e) { LOGGER.trace("ConfigurationClassPostProcessor bean doesn't present"); } } private static void clearSetFieldOfConfigurationClassPostProcessor(ConfigurationClassPostProcessor ccpp, String fieldName, int factoryId) {<FILL_FUNCTION_BODY>} }
try { Field field = ConfigurationClassPostProcessor.class.getDeclaredField(fieldName); field.setAccessible(true); Set<Integer> set = (Set<Integer>) field.get(ccpp); set.remove(factoryId); } catch (Exception e) { LOGGER.debug("Error while resetting ConfigurationClassPostProcessor caches", e); }
281
99
380
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-spring-plugin/src/main/java/org/hotswap/agent/plugin/spring/core/ResetBeanPostProcessorCaches.java
ResetBeanPostProcessorCaches
reset
class ResetBeanPostProcessorCaches { private static final AgentLogger LOGGER = AgentLogger.getLogger(ResetBeanPostProcessorCaches.class); private static Class<?> getReflectionUtilsClassOrNull() { try { //This is probably a bad idea as Class.forName has lots of issues but this was easiest for now. return Class.forName("org.springframework.util.ReflectionUtils"); } catch (ClassNotFoundException e) { LOGGER.trace("Spring 4.1.x or below - ReflectionUtils class not found"); return null; } } /** * Reset all post processors associated with a bean factory. * * @param beanFactory beanFactory to use */ public static void reset(DefaultListableBeanFactory beanFactory) {<FILL_FUNCTION_BODY>} public static void resetInitDestroyAnnotationBeanPostProcessorCache(InitDestroyAnnotationBeanPostProcessor bpp) { try { Field field = InitDestroyAnnotationBeanPostProcessor.class.getDeclaredField("lifecycleMetadataCache"); field.setAccessible(true); Map lifecycleMetadataCache = (Map) field.get(bpp); lifecycleMetadataCache.clear(); LOGGER.trace("Cache cleared: InitDestroyAnnotationBeanPostProcessor.lifecycleMetadataCache"); } catch (Exception e) { throw new IllegalStateException("Unable to clear InitDestroyAnnotationBeanPostProcessor.lifecycleMetadataCache", e); } } // @Autowired cache public static void resetAutowiredAnnotationBeanPostProcessorCache(AutowiredAnnotationBeanPostProcessor bpp) { try { Field field = AutowiredAnnotationBeanPostProcessor.class.getDeclaredField("candidateConstructorsCache"); field.setAccessible(true); // noinspection unchecked Map<Class<?>, Constructor<?>[]> candidateConstructorsCache = (Map<Class<?>, Constructor<?>[]>) field.get(bpp); candidateConstructorsCache.clear(); LOGGER.trace("Cache cleared: AutowiredAnnotationBeanPostProcessor.candidateConstructorsCache"); } catch (Exception e) { throw new IllegalStateException("Unable to clear AutowiredAnnotationBeanPostProcessor.candidateConstructorsCache", e); } resetAnnotationBeanPostProcessorCache(bpp, AutowiredAnnotationBeanPostProcessor.class); } /** * deal injectionMetadataCache field of * @see org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor * @see org.springframework.context.annotation.CommonAnnotationBeanPostProcessor */ private static void resetAnnotationBeanPostProcessorCache(Object object, Class<?> clazz) { try { Field field = clazz.getDeclaredField("injectionMetadataCache"); field.setAccessible(true); //noinspection unchecked Map<Class<?>, InjectionMetadata> injectionMetadataCache = (Map<Class<?>, InjectionMetadata>) field.get(object); injectionMetadataCache.clear(); // noinspection unchecked LOGGER.trace("Cache cleared: AutowiredAnnotationBeanPostProcessor/CommonAnnotationBeanPostProcessor" + " injectionMetadataCache"); } catch (Exception e) { throw new IllegalStateException("Unable to clear " + "AutowiredAnnotationBeanPostProcessor/CommonAnnotationBeanPostProcessor injectionMetadataCache", e); } } }
Class<?> c = getReflectionUtilsClassOrNull(); if (c != null) { try { Method m = c.getDeclaredMethod("clearCache"); m.invoke(null); LOGGER.trace("Cleared Spring 4.2+ internal method/field cache."); } catch (Exception version42Failed) { LOGGER.debug("Failed to clear internal method/field cache, it's normal with spring 4.1.x or lower", version42Failed); // spring 4.0.x, 4.1.x without clearCache method, clear manually Object declaredMethodsCache = ReflectionHelper.getNoException(null, c, "declaredMethodsCache"); if (declaredMethodsCache != null) { ((Map<?, ?>) declaredMethodsCache).clear(); } Object declaredFieldsCache1 = ReflectionHelper.getNoException(null, c, "declaredFieldsCache"); if (declaredFieldsCache1 != null) { ((Map<?, ?>) declaredFieldsCache1).clear(); } } } for (BeanPostProcessor bpp : beanFactory.getBeanPostProcessors()) { if (bpp instanceof AutowiredAnnotationBeanPostProcessor) { resetAutowiredAnnotationBeanPostProcessorCache((AutowiredAnnotationBeanPostProcessor) bpp); } else if (bpp instanceof CommonAnnotationBeanPostProcessor) { resetAnnotationBeanPostProcessorCache(bpp, CommonAnnotationBeanPostProcessor.class); } else if (bpp instanceof InitDestroyAnnotationBeanPostProcessor) { resetInitDestroyAnnotationBeanPostProcessorCache((InitDestroyAnnotationBeanPostProcessor) bpp); } }
858
413
1,271
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-spring-plugin/src/main/java/org/hotswap/agent/plugin/spring/core/ResetRequestMappingCaches.java
ResetRequestMappingCaches
reset
class ResetRequestMappingCaches { private static AgentLogger LOGGER = AgentLogger.getLogger(ResetRequestMappingCaches.class); private static Class<?> getHandlerMethodMappingClassOrNull() { try { //This is probably a bad idea as Class.forName has lots of issues but this was easiest for now. return Class.forName("org.springframework.web.servlet.handler.AbstractHandlerMethodMapping"); } catch (ClassNotFoundException e) { LOGGER.trace("HandlerMethodMapping class not found"); return null; } } public static void reset(DefaultListableBeanFactory beanFactory) {<FILL_FUNCTION_BODY>} }
Class<?> c = getHandlerMethodMappingClassOrNull(); if (c == null) return; Map<String, ?> mappings = BeanFactoryUtils.beansOfTypeIncludingAncestors(beanFactory, c, true, false); if (mappings.isEmpty()) { LOGGER.trace("Spring: no HandlerMappings found"); } try { for (Entry<String, ?> e : mappings.entrySet()) { Object am = e.getValue(); LOGGER.trace("Spring: clearing HandlerMapping for {}", am.getClass()); try { Field f = c.getDeclaredField("handlerMethods"); f.setAccessible(true); ((Map<?,?>)f.get(am)).clear(); f = c.getDeclaredField("urlMap"); f.setAccessible(true); ((Map<?,?>)f.get(am)).clear(); try { f = c.getDeclaredField("nameMap"); f.setAccessible(true); ((Map<?,?>)f.get(am)).clear(); } catch(NoSuchFieldException nsfe) { LOGGER.trace("Probably using Spring 4.0 or below: {}", nsfe.getMessage()); } } catch(NoSuchFieldException nsfe) { LOGGER.trace("Probably using Spring 4.2+", nsfe.getMessage()); Method m = c.getDeclaredMethod("getHandlerMethods", new Class[0]); Class<?>[] parameterTypes = new Class[1]; parameterTypes[0] = Object.class; Method u = c.getDeclaredMethod("unregisterMapping", parameterTypes); Map<?,?> unmodifiableHandlerMethods = (Map<?,?>) m.invoke(am); Object[] keys = unmodifiableHandlerMethods.keySet().toArray(); unmodifiableHandlerMethods = null; for (Object key : keys) { LOGGER.trace("Unregistering handler method {}", key); u.invoke(am, key); } } if (am instanceof InitializingBean) { ((InitializingBean) am).afterPropertiesSet(); } } } catch (Exception e) { LOGGER.error("Failed to clear HandlerMappings", e); }
172
585
757
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-spring-plugin/src/main/java/org/hotswap/agent/plugin/spring/core/ResetSpringStaticCaches.java
ResetSpringStaticCaches
resetBeanNamesByType
class ResetSpringStaticCaches { private static AgentLogger LOGGER = AgentLogger.getLogger(ResetSpringStaticCaches.class); /** * Spring bean by type cache. * * Cache names change between versions, call via reflection and ignore errors. */ public static void resetBeanNamesByType(DefaultListableBeanFactory defaultListableBeanFactory) {<FILL_FUNCTION_BODY>} /** * Reset all caches. */ public static void reset() { resetTypeVariableCache(); resetAnnotationUtilsCache(); resetReflectionUtilsCache(); resetResolvableTypeCache(); resetPropertyCache(); CachedIntrospectionResults.clearClassLoader(ResetSpringStaticCaches.class.getClassLoader()); } private static void resetResolvableTypeCache() { ReflectionHelper.invokeNoException(null, "org.springframework.core.ResolvableType", ResetSpringStaticCaches.class.getClassLoader(), "clearCache", new Class<?>[] {}); } private static void resetTypeVariableCache() { try { Field field = GenericTypeResolver.class.getDeclaredField("typeVariableCache"); field.setAccessible(true); // noinspection unchecked Map<Class, Map> typeVariableCache = (Map<Class, Map>) field.get(null); typeVariableCache.clear(); LOGGER.trace("Cache cleared: GenericTypeResolver.typeVariableCache"); } catch (Exception e) { throw new IllegalStateException("Unable to clear GenericTypeResolver.typeVariableCache", e); } } private static void resetReflectionUtilsCache() { ReflectionHelper.invokeNoException(null, "org.springframework.util.ReflectionUtils", ResetSpringStaticCaches.class.getClassLoader(), "clearCache", new Class<?>[] {}); Map declaredMethodsCache = (Map) ReflectionHelper.getNoException(null, ReflectionUtils.class, "declaredMethodsCache"); if (declaredMethodsCache != null) { declaredMethodsCache.clear(); LOGGER.trace("Cache cleared: ReflectionUtils.declaredMethodsCache"); } else { LOGGER.trace("Cache NOT cleared: ReflectionUtils.declaredMethodsCache not exists"); } } private static void resetAnnotationUtilsCache() { ReflectionHelper.invokeNoException(null, "org.springframework.core.annotation.AnnotationUtils", ResetSpringStaticCaches.class.getClassLoader(), "clearCache", new Class<?>[] {}); Map annotatedInterfaceCache = (Map) ReflectionHelper.getNoException(null, AnnotationUtils.class, "annotatedInterfaceCache"); if (annotatedInterfaceCache != null) { annotatedInterfaceCache.clear(); LOGGER.trace("Cache cleared: AnnotationUtils.annotatedInterfaceCache"); } else { LOGGER.trace("Cache NOT cleared: AnnotationUtils.annotatedInterfaceCache not exists in target Spring verion (pre 3.1.x)"); } Map findAnnotationCache = (Map) ReflectionHelper.getNoException(null, AnnotationUtils.class, "findAnnotationCache"); if (findAnnotationCache != null) { findAnnotationCache.clear(); LOGGER.trace("Cache cleared: AnnotationUtils.findAnnotationCache"); } else { LOGGER.trace("Cache NOT cleared: AnnotationUtils.findAnnotationCache not exists in target Spring version (pre 4.1)"); } } private static void resetPropertyCache() { try { ClassLoader classLoader = ResetSpringStaticCaches.class.getClassLoader(); Map annotationCache = (Map) ReflectionHelper.get(null, classLoader.loadClass("org.springframework.core.convert.Property"), "annotationCache"); annotationCache.clear(); LOGGER.trace("Cache cleared: Property.annotationCache"); } catch (Exception e) { LOGGER.trace("Unable to clear Property.annotationCache (ok before Spring 3.2.x)", e); } } }
try { Field field = DefaultListableBeanFactory.class.getDeclaredField("singletonBeanNamesByType"); field.setAccessible(true); // noinspection unchecked Map singletonBeanNamesByType = (Map) field.get(defaultListableBeanFactory); singletonBeanNamesByType.clear(); } catch (Exception e) { LOGGER.trace("Unable to clear DefaultListableBeanFactory.singletonBeanNamesByType cache (is Ok for pre 3.1.2 Spring version)", e); } try { Field field = DefaultListableBeanFactory.class.getDeclaredField("allBeanNamesByType"); field.setAccessible(true); // noinspection unchecked Map allBeanNamesByType = (Map) field.get(defaultListableBeanFactory); allBeanNamesByType.clear(); } catch (Exception e) { LOGGER.trace("Unable to clear allBeanNamesByType cache (is Ok for pre 3.2 Spring version)"); } try { Field field = DefaultListableBeanFactory.class.getDeclaredField("nonSingletonBeanNamesByType"); field.setAccessible(true); // noinspection unchecked Map nonSingletonBeanNamesByType = (Map) field.get(defaultListableBeanFactory); nonSingletonBeanNamesByType.clear(); } catch (Exception e) { LOGGER.debug("Unable to clear nonSingletonBeanNamesByType cache (is Ok for pre 3.2 Spring version)"); }
1,023
387
1,410
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-spring-plugin/src/main/java/org/hotswap/agent/plugin/spring/core/ResetTransactionAttributeCaches.java
ResetTransactionAttributeCaches
reset
class ResetTransactionAttributeCaches { private static final AgentLogger LOGGER = AgentLogger.getLogger(ResetTransactionAttributeCaches.class); private static Map<Object, TransactionAttribute> attributeCache; private static boolean tried = false; public static void reset(DefaultListableBeanFactory beanFactory) {<FILL_FUNCTION_BODY>} }
if (!beanFactory.containsBean("transactionAttributeSource")) { return; } try { if (attributeCache == null && !tried) { //only try once tried = true; final AbstractFallbackTransactionAttributeSource transactionAttributeSource = beanFactory.getBean("transactionAttributeSource", AbstractFallbackTransactionAttributeSource.class); Field attributeCacheField = AbstractFallbackTransactionAttributeSource.class.getDeclaredField("attributeCache"); attributeCacheField.setAccessible(true); attributeCache = (Map<Object, TransactionAttribute>) attributeCacheField.get(transactionAttributeSource); } if (attributeCache != null) { attributeCache.clear(); } } catch (Exception e) { LOGGER.error("Failed to reset @Transactional cache", e); }
89
204
293
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-spring-plugin/src/main/java/org/hotswap/agent/plugin/spring/getbean/DetachableBeanHolder.java
DetachableBeanHolder
getBean
class DetachableBeanHolder implements Serializable { private static final long serialVersionUID = -7443802320153815102L; private Object bean; private Object beanFactory; private Class<?>[] paramClasses; private Object[] paramValues; private static List<WeakReference<DetachableBeanHolder>> beanProxies = Collections.synchronizedList(new ArrayList<WeakReference<DetachableBeanHolder>>()); private static AgentLogger LOGGER = AgentLogger.getLogger(DetachableBeanHolder.class); /** * * @param bean * Spring Bean this object holds * @param beanFactry * Spring factory that produced the bean with a ProxyReplacer.FACTORY_METHOD_NAME method * @param paramClasses * @param paramValues */ public DetachableBeanHolder(Object bean, Object beanFactry, Class<?>[] paramClasses, Object[] paramValues) { if (bean == null) { LOGGER.error("Bean is null. The param value: {}", Arrays.toString(paramValues)); } this.bean = bean; this.beanFactory = beanFactry; this.paramClasses = paramClasses; this.paramValues = paramValues; beanProxies.add(new WeakReference<DetachableBeanHolder>(this)); } /** * Clears the bean references inside all of the proxies */ public static void detachBeans() { int i = 0; synchronized (beanProxies) { while (i < beanProxies.size()) { DetachableBeanHolder beanHolder = beanProxies.get(i).get(); if (beanHolder != null) { beanHolder.detach(); i++; } else { beanProxies.remove(i); } } } if (i > 0) { LOGGER.info("{} Spring proxies reset", i); } else { LOGGER.debug("No spring proxies reset"); } } /** * Clear the bean for this proxy */ public void detach() { bean = null; } /** * Sets current target bean. * @return current target bean. */ public void setTarget(Object bean) { this.bean = bean; } /** * Returns current target bean. * @return current target bean. */ public Object getTarget() { return bean; } /** * Returns an existing bean instance or retrieves and stores new bean from the Spring BeanFactory * * @return Bean this instance holds * @throws IllegalAccessException * @throws InvocationTargetException */ public Object getBean() throws IllegalAccessException, InvocationTargetException {<FILL_FUNCTION_BODY>} protected boolean isBeanLoaded(){ return bean != null; } }
Object beanCopy = bean; if (beanCopy == null) { Method[] methods = beanFactory.getClass().getMethods(); for (Method factoryMethod : methods) { if (ProxyReplacer.FACTORY_METHOD_NAME.equals(factoryMethod.getName()) && Arrays.equals(factoryMethod.getParameterTypes(), paramClasses)) { Object freshBean = factoryMethod.invoke(beanFactory, paramValues); // Factory returns HA proxy, but current method is invoked from HA proxy! // It might be the same object (if factory returns same object - meaning // that although clearAllProxies() was called, this bean did not change) // Unwrap the target bean, it is always available // see org.hotswap.agent.plugin.spring.getbean.EnhancerProxyCreater.create() if (freshBean instanceof SpringHotswapAgentProxy) { freshBean = ((SpringHotswapAgentProxy) freshBean).$$ha$getTarget(); } bean = freshBean; beanCopy = bean; if (beanCopy == null) { LOGGER.debug("Bean of '{}' not loaded, {} ", bean.getClass().getName(), paramValues); break; } LOGGER.info("Bean '{}' loaded", bean.getClass().getName()); break; } } } return beanCopy;
767
349
1,116
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-spring-plugin/src/main/java/org/hotswap/agent/plugin/spring/getbean/HotswapSpringInvocationHandler.java
HotswapSpringInvocationHandler
doInvoke
class HotswapSpringInvocationHandler extends DetachableBeanHolder implements InvocationHandler { private static final long serialVersionUID = 8037007940960065166L; /** * @param beanFactry Spring beanFactory * @param bean Spring bean * @param paramClasses Parameter Classes of the Spring beanFactory method which returned the bean. The method is named * ProxyReplacer.FACTORY_METHOD_NAME * @param paramValues Parameter values of the Spring beanFactory method which returned the bean. The method is named * ProxyReplacer.FACTORY_METHOD_NAME */ public HotswapSpringInvocationHandler(Object bean, Object beanFactry, Class<?>[] paramClasses, Object[] paramValues) { super(bean, beanFactry, paramClasses, paramValues); } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (method.getName().equals("getWrappedObject") && method.getDeclaringClass().getName().equals("org.springframework.core.InfrastructureProxy")) { for (Class<?> beanInterface : getBean().getClass().getInterfaces()) { if (beanInterface.getName().equals("org.springframework.core.InfrastructureProxy")) { return doInvoke(method, args); } } return getBean(); } return doInvoke(method, args); } private Object doInvoke(Method method, Object[] args) throws Throwable {<FILL_FUNCTION_BODY>} }
try { return method.invoke(getBean(), args); } catch (InvocationTargetException e) { throw e.getCause(); }
408
43
451
<methods>public void <init>(java.lang.Object, java.lang.Object, Class<?>[], java.lang.Object[]) ,public void detach() ,public static void detachBeans() ,public java.lang.Object getBean() throws java.lang.IllegalAccessException, java.lang.reflect.InvocationTargetException,public java.lang.Object getTarget() ,public void setTarget(java.lang.Object) <variables>private static org.hotswap.agent.logging.AgentLogger LOGGER,private java.lang.Object bean,private java.lang.Object beanFactory,private static List<WeakReference<org.hotswap.agent.plugin.spring.getbean.DetachableBeanHolder>> beanProxies,private Class<?>[] paramClasses,private java.lang.Object[] paramValues,private static final long serialVersionUID
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-spring-plugin/src/main/java/org/hotswap/agent/plugin/spring/getbean/ProxyReplacer.java
ProxyReplacer
register
class ProxyReplacer { private static AgentLogger LOGGER = AgentLogger.getLogger(ProxyReplacer.class); private static Class<?> infrastructureProxyClass; /** * Name of the Spring beanFactory method, which returns a bean */ public static final String FACTORY_METHOD_NAME = "getBean"; /** * Clears the bean references inside all the proxies */ public static void clearAllProxies() { DetachableBeanHolder.detachBeans(); } /** * Creates a proxied Spring bean. Called from within WebApp code by modification of Spring classes * * @param beanFactry Spring beanFactory * @param bean Spring bean * @param paramClasses Parameter Classes of the Spring beanFactory method which returned the bean. The method is named * ProxyReplacer.FACTORY_METHOD_NAME * @param paramValues Parameter values of the Spring beanFactory method which returned the bean. The method is named * ProxyReplacer.FACTORY_METHOD_NAME * @return Proxied bean */ public static Object register(Object beanFactry, Object bean, Class<?>[] paramClasses, Object[] paramValues) {<FILL_FUNCTION_BODY>} private static Class<?> getInfrastructureProxyClass() throws ClassNotFoundException { if (infrastructureProxyClass == null) { infrastructureProxyClass = ProxyReplacer.class.getClassLoader().loadClass("org.springframework.core.InfrastructureProxy"); } return infrastructureProxyClass; } }
if (bean == null) { return bean; } if (SpringPlugin.basePackagePrefixes != null) { boolean hasMatch = false; for (String basePackagePrefix : SpringPlugin.basePackagePrefixes) { if (bean.getClass().getName().startsWith(basePackagePrefix)) { hasMatch = true; break; } } // bean from other package if (!hasMatch) { LOGGER.info("{} not in basePackagePrefix", bean.getClass().getName()); return bean; } } // create proxy for prototype-scope beans and apsect proxied beans if (bean.getClass().getName().startsWith("com.sun.proxy.$Proxy")) { InvocationHandler handler = new HotswapSpringInvocationHandler(bean, beanFactry, paramClasses, paramValues); Class<?>[] interfaces = bean.getClass().getInterfaces(); try { if (!Arrays.asList(interfaces).contains(getInfrastructureProxyClass())) { interfaces = Arrays.copyOf(interfaces, interfaces.length + 1); interfaces[interfaces.length - 1] = getInfrastructureProxyClass(); } } catch (ClassNotFoundException e) { LOGGER.error("error adding org.springframework.core.InfrastructureProxy to proxy class", e); } // fix: it should be the classloader of the bean, // or org.springframework.beans.factory.support.AbstractBeanFactory.getBeanClassLoader, // but not the classLoader of the beanFactry return Proxy.newProxyInstance(bean.getClass().getClassLoader(), interfaces, handler); } else if (EnhancerProxyCreater.isSupportedCglibProxy(bean)) { // already a proxy, skip.. if (bean.getClass().getName().contains("$HOTSWAPAGENT_")) { return bean; } return EnhancerProxyCreater.createProxy(beanFactry, bean, paramClasses, paramValues); } return bean;
401
520
921
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-spring-plugin/src/main/java/org/hotswap/agent/plugin/spring/listener/SpringEventSource.java
SpringEventSource
addListener
class SpringEventSource { private final static AgentLogger LOGGER = AgentLogger.getLogger(SpringEventSource.class); public static final SpringEventSource INSTANCE = new SpringEventSource(); private SpringEventSource() { } private final Set<SpringListener<SpringEvent<?>>> listeners = new HashSet<>(); public void addListener(SpringListener<SpringEvent<?>> listener) {<FILL_FUNCTION_BODY>} public void fireEvent(SpringEvent<?> event) { for (SpringListener<SpringEvent<?>> listener : listeners) { if (listener.shouldSkip(event)) { continue; } try { listener.onEvent(event); } catch (Throwable e) { LOGGER.warning("SpringListener onEvent error", e); } } } }
if (listener == null) { return; } synchronized (listeners) { if (listeners.contains(listener)) { LOGGER.debug("SpringListener already registered, {}", listener); return; } listeners.add(listener); }
222
78
300
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-spring-plugin/src/main/java/org/hotswap/agent/plugin/spring/reload/BeanFactoryAssistant.java
BeanFactoryAssistant
existReload
class BeanFactoryAssistant { private ConfigurableListableBeanFactory beanFactory; private AtomicInteger reloadTimes; private long lastReloadTime; private volatile boolean isReload = false; // keep the bean name and xml file relation for the beans which are defined in xml file and the bean contains placeholder Map<String, String> placeHolderXmlMapping = new ConcurrentHashMap<>(); private static Map<ConfigurableListableBeanFactory, BeanFactoryAssistant> beanFactoryAssistants = new ConcurrentHashMap<>(4); public BeanFactoryAssistant(ConfigurableListableBeanFactory beanFactory) { this.beanFactory = beanFactory; this.reloadTimes = new AtomicInteger(0); this.lastReloadTime = System.currentTimeMillis(); beanFactoryAssistants.put(beanFactory, this); } public static boolean existReload() {<FILL_FUNCTION_BODY>} public static BeanFactoryAssistant getBeanFactoryAssistant(ConfigurableListableBeanFactory beanFactory) { return beanFactoryAssistants.get(beanFactory); } public static BeanFactoryAssistant getBeanFactoryAssistant(DefaultListableBeanFactory beanFactory) { return beanFactoryAssistants.get(beanFactory); } public static BeanFactoryAssistant getBeanFactoryAssistant(AbstractAutowireCapableBeanFactory beanFactory) { if (beanFactory instanceof ConfigurableListableBeanFactory) { return getBeanFactoryAssistant((ConfigurableListableBeanFactory) beanFactory); } return null; } public void increaseReloadTimes() { this.reloadTimes.incrementAndGet(); this.lastReloadTime = System.currentTimeMillis(); } public ConfigurableListableBeanFactory getBeanFactory() { return beanFactory; } public void reset() { this.reloadTimes.set(0); this.lastReloadTime = System.currentTimeMillis(); } public int getReloadTimes() { return reloadTimes.get(); } public long getLastReloadTime() { return lastReloadTime; } public boolean isReload() { return isReload; } public void setReload(boolean isReload) { this.isReload = isReload; } /** * check the bean is destroyed or not * @param beanName * @return */ public boolean isDestroyedBean(String beanName) { if (beanFactory instanceof BeanFactoryLifecycle) { return ((BeanFactoryLifecycle) beanFactory).hotswapAgent$isDestroyedBean(beanName); } return false; } }
for (BeanFactoryAssistant assistant : beanFactoryAssistants.values()) { if (assistant.isReload) { return true; } } return false;
695
50
745
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-spring-plugin/src/main/java/org/hotswap/agent/plugin/spring/reload/ClassChangedCommand.java
ClassChangedCommand
executeCommand
class ClassChangedCommand extends MergeableCommand { private static AgentLogger LOGGER = AgentLogger.getLogger(ClassChangedCommand.class); private static final Set<String> IGNORE_PACKAGES = new HashSet<>(); ClassLoader appClassLoader; Class clazz; Scheduler scheduler; static { IGNORE_PACKAGES.add("org.hotswap.agent.plugin.spring.reload"); IGNORE_PACKAGES.add("org.hotswap.agent.plugin.spring.scanner"); } public ClassChangedCommand(ClassLoader appClassLoader, Class clazz, Scheduler scheduler) { this.appClassLoader = appClassLoader; this.clazz = clazz; this.scheduler = scheduler; } @Override public void executeCommand() {<FILL_FUNCTION_BODY>} }
try { Class<?> targetClass = Class.forName("org.hotswap.agent.plugin.spring.reload.SpringChangedAgent", true, appClassLoader); Method targetMethod = targetClass.getDeclaredMethod("addChangedClass", Class.class); targetMethod.invoke(null, clazz); } catch (NoSuchMethodException e) { throw new IllegalStateException("Plugin error, method not found", e); } catch (InvocationTargetException e) { LOGGER.error("Error invoking method", e); } catch (IllegalAccessException e) { throw new IllegalStateException("Plugin error, illegal access", e); } catch (ClassNotFoundException e) { throw new IllegalStateException("Plugin error, Spring class not found in application classloader", e); }
236
201
437
<methods>public non-sealed void <init>() ,public List<org.hotswap.agent.command.Command> getMergedCommands() ,public org.hotswap.agent.command.Command merge(org.hotswap.agent.command.Command) ,public List<org.hotswap.agent.command.Command> popMergedCommands() <variables>List<org.hotswap.agent.command.Command> mergedCommands
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-spring-plugin/src/main/java/org/hotswap/agent/plugin/spring/reload/PropertiesChangedCommand.java
PropertiesChangedCommand
executeCommand
class PropertiesChangedCommand extends MergeableCommand { private static AgentLogger LOGGER = AgentLogger.getLogger(PropertiesChangedCommand.class); ClassLoader appClassLoader; URL url; Scheduler scheduler; public PropertiesChangedCommand(ClassLoader appClassLoader, URL url, Scheduler scheduler) { this.appClassLoader = appClassLoader; this.url = url; this.scheduler = scheduler; } @Override public void executeCommand() {<FILL_FUNCTION_BODY>} }
try { Class<?> clazz = Class.forName("org.hotswap.agent.plugin.spring.reload.SpringChangedAgent", true, appClassLoader); Method method = clazz.getDeclaredMethod( "addChangedProperty", new Class[]{URL.class}); method.invoke(null, url); } catch (NoSuchMethodException e) { throw new IllegalStateException("Plugin error, method not found", e); } catch (InvocationTargetException e) { LOGGER.error("Error invoking method", e); } catch (IllegalAccessException e) { throw new IllegalStateException("Plugin error, illegal access", e); } catch (ClassNotFoundException e) { throw new IllegalStateException("Plugin error, Spring class not found in application classloader", e); }
139
204
343
<methods>public non-sealed void <init>() ,public List<org.hotswap.agent.command.Command> getMergedCommands() ,public org.hotswap.agent.command.Command merge(org.hotswap.agent.command.Command) ,public List<org.hotswap.agent.command.Command> popMergedCommands() <variables>List<org.hotswap.agent.command.Command> mergedCommands
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-spring-plugin/src/main/java/org/hotswap/agent/plugin/spring/reload/SpringChangedReloadCommand.java
SpringChangedReloadCommand
executeCommand
class SpringChangedReloadCommand extends MergeableCommand { private static AgentLogger LOGGER = AgentLogger.getLogger(XmlsChangedCommand.class); // unit test only private static AtomicLong waitingTaskCount = new AtomicLong(0); ClassLoader appClassLoader; long timestamps; public SpringChangedReloadCommand(ClassLoader appClassLoader) { this.appClassLoader = appClassLoader; this.timestamps = System.currentTimeMillis(); LOGGER.trace("SpringChangedReloadCommand created with timestamp '{}'", timestamps); waitingTaskCount.incrementAndGet(); } @Override public void executeCommand() {<FILL_FUNCTION_BODY>} // this is used by tests public static boolean isEmptyTask() { return waitingTaskCount.get() == 0; } }
// async call to avoid reload too much times try { Class<?> clazz = Class.forName("org.hotswap.agent.plugin.spring.reload.SpringChangedAgent", true, appClassLoader); Method method = clazz.getDeclaredMethod( "reload", long.class); method.invoke(null, timestamps); } catch (NoSuchMethodException e) { throw new IllegalStateException("Plugin error, method not found", e); } catch (InvocationTargetException e) { LOGGER.error("Error invoking method", e); } catch (IllegalAccessException e) { throw new IllegalStateException("Plugin error, illegal access", e); } catch (ClassNotFoundException e) { throw new IllegalStateException("Plugin error, Spring class not found in application classloader", e); } finally { waitingTaskCount.decrementAndGet(); }
219
231
450
<methods>public non-sealed void <init>() ,public List<org.hotswap.agent.command.Command> getMergedCommands() ,public org.hotswap.agent.command.Command merge(org.hotswap.agent.command.Command) ,public List<org.hotswap.agent.command.Command> popMergedCommands() <variables>List<org.hotswap.agent.command.Command> mergedCommands
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-spring-plugin/src/main/java/org/hotswap/agent/plugin/spring/reload/SpringReloadConfig.java
SpringReloadConfig
setDelayMillis
class SpringReloadConfig { public static int reloadDelayMillis = 1600; public static void setDelayMillis(int delayMillis) {<FILL_FUNCTION_BODY>} }
if (delayMillis > 30000) { reloadDelayMillis = 30000; return; } SpringReloadConfig.reloadDelayMillis = delayMillis;
56
56
112
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-spring-plugin/src/main/java/org/hotswap/agent/plugin/spring/reload/XmlsChangedCommand.java
XmlsChangedCommand
executeCommand
class XmlsChangedCommand extends MergeableCommand { private static AgentLogger LOGGER = AgentLogger.getLogger(XmlsChangedCommand.class); ClassLoader appClassLoader; URL url; Scheduler scheduler; public XmlsChangedCommand(ClassLoader appClassLoader, URL url, Scheduler scheduler) { this.appClassLoader = appClassLoader; this.url = url; this.scheduler = scheduler; } @Override public void executeCommand() {<FILL_FUNCTION_BODY>} }
try { Class<?> clazz = Class.forName("org.hotswap.agent.plugin.spring.reload.SpringChangedAgent", true, appClassLoader); Method method = clazz.getDeclaredMethod( "addChangedXml", new Class[]{URL.class}); method.invoke(null, url); } catch (NoSuchMethodException e) { throw new IllegalStateException("Plugin error, method not found", e); } catch (InvocationTargetException e) { LOGGER.error("Error invoking method", e); } catch (IllegalAccessException e) { throw new IllegalStateException("Plugin error, illegal access", e); } catch (ClassNotFoundException e) { throw new IllegalStateException("Plugin error, Spring class not found in application classloader", e); }
144
204
348
<methods>public non-sealed void <init>() ,public List<org.hotswap.agent.command.Command> getMergedCommands() ,public org.hotswap.agent.command.Command merge(org.hotswap.agent.command.Command) ,public List<org.hotswap.agent.command.Command> popMergedCommands() <variables>List<org.hotswap.agent.command.Command> mergedCommands
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-spring-plugin/src/main/java/org/hotswap/agent/plugin/spring/reload/YamlChangedCommand.java
YamlChangedCommand
executeCommand
class YamlChangedCommand extends MergeableCommand { private static AgentLogger LOGGER = AgentLogger.getLogger(YamlChangedCommand.class); ClassLoader appClassLoader; URL url; Scheduler scheduler; public YamlChangedCommand(ClassLoader appClassLoader, URL url, Scheduler scheduler) { this.appClassLoader = appClassLoader; this.url = url; this.scheduler = scheduler; } @Override public void executeCommand() {<FILL_FUNCTION_BODY>} }
try { Class<?> clazz = Class.forName("org.hotswap.agent.plugin.spring.reload.SpringChangedAgent", true, appClassLoader); Method method = clazz.getDeclaredMethod( "addChangedYaml", new Class[]{URL.class}); method.invoke(null, url); } catch (Exception e) { throw new RuntimeException("YamlChangedCommand.execute error", e); }
142
115
257
<methods>public non-sealed void <init>() ,public List<org.hotswap.agent.command.Command> getMergedCommands() ,public org.hotswap.agent.command.Command merge(org.hotswap.agent.command.Command) ,public List<org.hotswap.agent.command.Command> popMergedCommands() <variables>List<org.hotswap.agent.command.Command> mergedCommands
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-spring-plugin/src/main/java/org/hotswap/agent/plugin/spring/scanner/ClassPathBeanRefreshCommand.java
ClassPathBeanRefreshCommand
isDeleteEvent
class ClassPathBeanRefreshCommand extends MergeableCommand { private static AgentLogger LOGGER = AgentLogger.getLogger(ClassPathBeanRefreshCommand.class); ClassLoader appClassLoader; String basePackage; String className; // either event or classDefinition is set by constructor (watcher or transformer) WatchFileEvent event; byte[] classDefinition; Scheduler scheduler; public ClassPathBeanRefreshCommand(ClassLoader appClassLoader, String basePackage, String className, byte[] classDefinition, Scheduler scheduler) { this.appClassLoader = appClassLoader; this.basePackage = basePackage; this.className = className; this.classDefinition = classDefinition; this.scheduler = scheduler; } public ClassPathBeanRefreshCommand(ClassLoader appClassLoader, String basePackage, String className, WatchFileEvent event, Scheduler scheduler) { this.appClassLoader = appClassLoader; this.basePackage = basePackage; this.event = event; this.className = className; this.scheduler = scheduler; } @Override public void executeCommand() { if (isDeleteEvent()) { LOGGER.trace("Skip Spring reload for delete event on class '{}'", className); return; } try { if (classDefinition == null) { try { this.classDefinition = IOUtils.toByteArray(event.getURI()); } catch (IllegalArgumentException e) { LOGGER.debug("File {} not found on filesystem (deleted?). Unable to refresh associated Spring bean.", event.getURI()); return; } } LOGGER.debug("Executing ClassPathBeanDefinitionScannerAgent.refreshClass('{}')", className); Class<?> clazz = Class.forName("org.hotswap.agent.plugin.spring.scanner.ClassPathBeanDefinitionScannerAgent", true, appClassLoader); Method method = clazz.getDeclaredMethod( "refreshClassAndCheckReload", new Class[] {ClassLoader.class, String.class, String.class, byte[].class}); method.invoke(null, appClassLoader , basePackage, basePackage, classDefinition); } catch (NoSuchMethodException e) { throw new IllegalStateException("Plugin error, method not found", e); } catch (InvocationTargetException e) { LOGGER.error("Error refreshing class {} in classLoader {}", e, className, appClassLoader); } catch (IllegalAccessException e) { throw new IllegalStateException("Plugin error, illegal access", e); } catch (ClassNotFoundException e) { throw new IllegalStateException("Plugin error, Spring class not found in application classloader", e); } } /** * Check all merged events for delete and create events. If delete without create is found, than assume * file was deleted. */ private boolean isDeleteEvent() {<FILL_FUNCTION_BODY>} @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ClassPathBeanRefreshCommand that = (ClassPathBeanRefreshCommand) o; if (!appClassLoader.equals(that.appClassLoader)) return false; if (!className.equals(that.className)) return false; return true; } @Override public int hashCode() { int result = appClassLoader.hashCode(); result = 31 * result + className.hashCode(); return result; } @Override public String toString() { return "ClassPathBeanRefreshCommand{" + "appClassLoader=" + appClassLoader + ", basePackage='" + basePackage + '\'' + ", className='" + className + '\'' + '}'; } }
// for all merged commands including this command List<ClassPathBeanRefreshCommand> mergedCommands = new ArrayList<>(); for (Command command : getMergedCommands()) { mergedCommands.add((ClassPathBeanRefreshCommand) command); } mergedCommands.add(this); boolean createFound = false; boolean deleteFound = false; for (ClassPathBeanRefreshCommand command : mergedCommands) { if (command.event != null) { if (command.event.getEventType().equals(FileEvent.DELETE)) deleteFound = true; if (command.event.getEventType().equals(FileEvent.CREATE)) createFound = true; } } LOGGER.trace("isDeleteEvent result {}: createFound={}, deleteFound={}", createFound, deleteFound); return !createFound && deleteFound;
984
222
1,206
<methods>public non-sealed void <init>() ,public List<org.hotswap.agent.command.Command> getMergedCommands() ,public org.hotswap.agent.command.Command merge(org.hotswap.agent.command.Command) ,public List<org.hotswap.agent.command.Command> popMergedCommands() <variables>List<org.hotswap.agent.command.Command> mergedCommands
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-spring-plugin/src/main/java/org/hotswap/agent/plugin/spring/scanner/SpringBeanWatchEventListener.java
SpringBeanWatchEventListener
onEvent
class SpringBeanWatchEventListener implements WatchEventListener { private static final AgentLogger LOGGER = AgentLogger.getLogger(SpringBeanWatchEventListener.class); /** * If a class is modified in IDE, sequence of multiple events is generated - * class file DELETE, CREATE, MODIFY, than Hotswap transformer is invoked. * ClassPathBeanRefreshCommand tries to merge these events into single command. * Wait this this timeout after class file event. */ private static final int WAIT_ON_CREATE = 600; private Scheduler scheduler; private ClassLoader appClassLoader; private String basePackage; public SpringBeanWatchEventListener(Scheduler scheduler, ClassLoader appClassLoader, String basePackage) { this.scheduler = scheduler; this.appClassLoader = appClassLoader; this.basePackage = basePackage; } @Override public void onEvent(WatchFileEvent event) {<FILL_FUNCTION_BODY>} @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SpringBeanWatchEventListener that = (SpringBeanWatchEventListener) o; return Objects.equals(appClassLoader, that.appClassLoader) && Objects.equals(basePackage, that.basePackage); } @Override public int hashCode() { return Objects.hash(appClassLoader, basePackage); } }
// new File if (event.getEventType() == FileEvent.CREATE && event.isFile() && event.getURI().toString().endsWith(".class")) { // check that the class is not loaded by the classloader yet (avoid duplicate reload) String className; try { className = IOUtils.urlToClassName(event.getURI()); } catch (IOException e) { LOGGER.trace("Watch event on resource '{}' skipped, probably Ok because of delete/create event " + "sequence (compilation not finished yet).", e, event.getURI()); return; } if (!ClassLoaderHelper.isClassLoaded(appClassLoader, className)) { // refresh spring only for new classes scheduler.scheduleCommand(new ClassPathBeanRefreshCommand(appClassLoader, basePackage, className, event, scheduler), WAIT_ON_CREATE); LOGGER.trace("Scheduling Spring reload for class '{}' in classLoader {}", className, appClassLoader); scheduler.scheduleCommand(new SpringChangedReloadCommand(appClassLoader), SpringReloadConfig.reloadDelayMillis); } }
380
287
667
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-spring-plugin/src/main/java/org/hotswap/agent/plugin/spring/transformers/BeanFactoryTransformer.java
BeanFactoryTransformer
registerAbstractAutowireCapableBeanFactory
class BeanFactoryTransformer { private static final AgentLogger LOGGER = AgentLogger.getLogger(BeanFactoryTransformer.class); @OnClassLoadEvent(classNameRegexp = "org.springframework.beans.factory.support.DefaultSingletonBeanRegistry") public static void registerDefaultSingletonBeanRegistry(ClassLoader appClassLoader, CtClass clazz, ClassPool classPool) throws NotFoundException, CannotCompileException { clazz.addField( CtField.make("private java.util.Set hotswapAgent$destroyBean = new java.util.HashSet();", clazz)); clazz.addInterface(classPool.get("org.hotswap.agent.plugin.spring.transformers.api.BeanFactoryLifecycle")); clazz.addMethod(CtNewMethod.make( "public boolean hotswapAgent$isDestroyedBean(String beanName) { return hotswapAgent$destroyBean.contains" + "(beanName); }", clazz)); clazz.addMethod(CtNewMethod.make( "public void hotswapAgent$destroyBean(String beanName) { hotswapAgent$destroyBean.add(beanName); }", clazz)); clazz.addMethod( CtNewMethod.make("public void hotswapAgent$clearDestroyBean() { hotswapAgent$destroyBean.clear(); }", clazz)); CtMethod destroySingletonMethod = clazz.getDeclaredMethod("destroySingleton", new CtClass[] {classPool.get(String.class.getName())}); destroySingletonMethod.insertAfter( BeanFactoryProcessor.class.getName() + ".postProcessDestroySingleton($0, $1);"); } @OnClassLoadEvent(classNameRegexp = "org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory") public static void registerAbstractAutowireCapableBeanFactory(ClassLoader appClassLoader, CtClass clazz, ClassPool classPool) throws NotFoundException, CannotCompileException {<FILL_FUNCTION_BODY>} }
clazz.addField(CtField.make("private static final org.hotswap.agent.logging.AgentLogger $$ha$LOGGER = " + "org.hotswap.agent.logging.AgentLogger.getLogger(org.springframework.beans.factory.annotation" + ".InitDestroyAnnotationBeanPostProcessor.class);", clazz)); CtMethod createBeanMethod = clazz.getDeclaredMethod("createBean", new CtClass[] { classPool.get(String.class.getName()), classPool.get("org.springframework.beans.factory.support.RootBeanDefinition"), classPool.get(Object[].class.getName())}); createBeanMethod.insertAfter(BeanFactoryProcessor.class.getName() + ".postProcessCreateBean($0, $1, $2);"); // try catch for custom init method CtMethod[] invokeCustomInitMethods = clazz.getDeclaredMethods("invokeCustomInitMethod"); if (invokeCustomInitMethods.length != 1) { LOGGER.error("Unexpected number of 'invokeCustomInitMethod' methods found. Expected: 1, Found: " + invokeCustomInitMethods.length); } invokeCustomInitMethods[0].addCatch( InitMethodEnhance.catchException("$2", "$$ha$LOGGER", "$e", "invokeCustomInitMethod", false), classPool.get("java.lang.Throwable")); // try catch for afterPropertiesSet CtMethod invokeInitMethod = clazz.getDeclaredMethod("invokeInitMethods", new CtClass[] {classPool.get(String.class.getName()), classPool.get("java.lang.Object"), classPool.get("org.springframework.beans.factory.support.RootBeanDefinition")}); invokeInitMethod.addCatch( InitMethodEnhance.catchException("$2", "$$ha$LOGGER", "$e", "invokeInitMethods", false), classPool.get("java.lang.Throwable"));
529
492
1,021
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-spring-plugin/src/main/java/org/hotswap/agent/plugin/spring/transformers/ClassPathBeanDefinitionScannerTransformer.java
ClassPathBeanDefinitionScannerTransformer
transform
class ClassPathBeanDefinitionScannerTransformer { private static final AgentLogger LOGGER = AgentLogger.getLogger(ClassPathBeanDefinitionScannerTransformer.class); /** * Insert at the beginning of the method: * <pre>public Set<BeanDefinition> findCandidateComponents(String basePackage)</pre> * new code to initialize ClassPathBeanDefinitionScannerAgent for a base class * It would be better to override a more appropriate method * org.springframework.context.annotation.ClassPathBeanDefinitionScanner.scan() directly, * however there are issues with javassist and varargs parameters. */ @OnClassLoadEvent(classNameRegexp = "org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider") public static void transform(CtClass clazz, ClassPool classPool) throws NotFoundException, CannotCompileException {<FILL_FUNCTION_BODY>} }
if (SpringPlugin.basePackagePrefixes == null) { CtMethod method = clazz.getDeclaredMethod("findCandidateComponents", new CtClass[]{classPool.get("java.lang.String")}); method.insertAfter( "if (this instanceof org.springframework.context.annotation.ClassPathBeanDefinitionScanner) {" + " if (org.hotswap.agent.plugin.spring.scanner.ClassPathBeanDefinitionScannerAgent.getInstance($1) == null) {" + " org.hotswap.agent.plugin.spring.scanner.ClassPathBeanDefinitionScannerAgent.getInstance(" + "(org.springframework.context.annotation.ClassPathBeanDefinitionScanner)this).registerBasePackage($1);" + " }" + "}"); LOGGER.debug("Class 'org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider' " + "patched with basePackage registration."); } else { LOGGER.debug("No need to register scanned path, instead just register 'spring.basePackagePrefix' in " + "configuration file."); }
225
283
508
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-spring-plugin/src/main/java/org/hotswap/agent/plugin/spring/transformers/ConfigurationClassPostProcessorTransformer.java
ConfigurationClassPostProcessorTransformer
transform
class ConfigurationClassPostProcessorTransformer { private static final AgentLogger LOGGER = AgentLogger.getLogger(ConfigurationClassPostProcessorTransformer.class); @OnClassLoadEvent(classNameRegexp = "org.springframework.context.annotation.ConfigurationClassPostProcessor") public static void transform(CtClass clazz, ClassPool classPool) throws NotFoundException, CannotCompileException {<FILL_FUNCTION_BODY>} }
LOGGER.debug("Class 'org.springframework.context.annotation.ConfigurationClassPostProcessor' patched with processor registration."); CtMethod method = clazz.getDeclaredMethod("processConfigBeanDefinitions", new CtClass[]{classPool.get("org.springframework.beans.factory.support.BeanDefinitionRegistry")}); method.insertAfter("org.hotswap.agent.plugin.spring.core.ConfigurationClassPostProcessorEnhance.getInstance($1)." + "setProcessor(this);"); try { /** * remove warning log in org.springframework.context.annotation.ConfigurationClassPostProcessor.enhanceConfigurationClasses */ CtMethod enhanceConfigurationClassesMethod = clazz.getDeclaredMethod("enhanceConfigurationClasses"); enhanceConfigurationClassesMethod.instrument(new ExprEditor() { @Override public void edit(MethodCall m) throws CannotCompileException { if (m.getClassName().equals("org.springframework.beans.factory.config.ConfigurableListableBeanFactory") && m.getMethodName().equals("containsSingleton")) { m.replace("{$_ = $proceed($$) && " + "(org.hotswap.agent.plugin.spring.reload.BeanFactoryAssistant.getBeanFactoryAssistant($0) == null || " + "!org.hotswap.agent.plugin.spring.reload.BeanFactoryAssistant.getBeanFactoryAssistant($0).isReload());}"); } } }); } catch (NotFoundException e) { // ignore }
104
391
495
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-spring-plugin/src/main/java/org/hotswap/agent/plugin/spring/transformers/InitDestroyAnnotationBeanPostProcessorTransformer.java
InitDestroyAnnotationBeanPostProcessorTransformer
transform
class InitDestroyAnnotationBeanPostProcessorTransformer { private static final AgentLogger LOGGER = AgentLogger.getLogger( InitDestroyAnnotationBeanPostProcessorTransformer.class); @OnClassLoadEvent(classNameRegexp = "org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor") public static void transform(CtClass clazz, ClassPool classPool) throws NotFoundException, CannotCompileException {<FILL_FUNCTION_BODY>} }
LOGGER.debug( "Class 'org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor' patched with" + " catch exception."); clazz.addField(CtField.make("private static final org.hotswap.agent.logging.AgentLogger $$ha$LOGGER = " + "org.hotswap.agent.logging.AgentLogger.getLogger(org.springframework.beans.factory.annotation" + ".InitDestroyAnnotationBeanPostProcessor.class);", clazz)); CtMethod method = clazz.getDeclaredMethod("postProcessBeforeInitialization", new CtClass[] {classPool.get("java.lang.Object"), classPool.get("java.lang.String")}); String code = "{" + "if (!org.hotswap.agent.plugin.spring.reload.BeanFactoryAssistant.existReload()) {" + " throw $e ; }" + "else {" + "if ($$ha$LOGGER.isDebugEnabled()) {" + "$$ha$LOGGER.debug(\"Failed to invoke init method of {} from @PostConstructor: {}\", $e, " + "new java.lang.Object[]{$1.getClass().getName(),$e.getMessage()});" + "} else {" + "$$ha$LOGGER.warning(\"Failed to invoke init method of {} from @PostConstructor: {}\", " + "new java.lang.Object[]{$1.getClass().getName(),$e.getMessage()});" + "}" + "return $1;" + "}" + "}"; method.addCatch(code, classPool.get("org.springframework.beans.factory.BeanCreationException"));
118
429
547
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-spring-plugin/src/main/java/org/hotswap/agent/plugin/spring/transformers/PlaceholderConfigurerSupportTransformer.java
PlaceholderConfigurerSupportTransformer
transform
class PlaceholderConfigurerSupportTransformer { private static AgentLogger LOGGER = AgentLogger.getLogger(PlaceholderConfigurerSupportTransformer.class); /** * @param clazz * @param classPool * @throws NotFoundException * @throws CannotCompileException */ @OnClassLoadEvent(classNameRegexp = "org.springframework.beans.factory.config.PlaceholderConfigurerSupport") public static void transform(CtClass clazz, ClassPool classPool) throws NotFoundException, CannotCompileException {<FILL_FUNCTION_BODY>} }
for (CtClass interfaceClazz : clazz.getInterfaces()) { if (interfaceClazz.getName().equals("org.hotswap.agent.plugin.spring.transformers.api.ValueResolverSupport")) { return; } } clazz.addInterface(classPool.get("org.hotswap.agent.plugin.spring.transformers.api.ValueResolverSupport")); clazz.addField(CtField.make("private java.util.List _resolvers;", clazz), "new java.util.ArrayList(2)"); clazz.addMethod(CtMethod.make("public java.util.List valueResolvers() { return this._resolvers; }", clazz)); CtMethod ctMethod = clazz.getDeclaredMethod("doProcessProperties", new CtClass[]{classPool.get("org.springframework.beans.factory.config.ConfigurableListableBeanFactory"), classPool.get("org.springframework.util.StringValueResolver")}); ctMethod.insertBefore("org.hotswap.agent.plugin.spring.reload.SpringChangedAgent.collectPlaceholderProperties($1); " + "this._resolvers.add($2);"); LOGGER.debug("class 'org.springframework.beans.factory.config.PlaceholderConfigurerSupport' patched with placeholder keep.");
148
330
478
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-spring-plugin/src/main/java/org/hotswap/agent/plugin/spring/transformers/PostProcessorRegistrationDelegateTransformer.java
PostProcessorRegistrationDelegateTransformer
edit
class PostProcessorRegistrationDelegateTransformer { private static AgentLogger LOGGER = AgentLogger.getLogger(PostProcessorRegistrationDelegateTransformer.class); /** * @param clazz * @param classPool * @throws NotFoundException * @throws CannotCompileException */ @OnClassLoadEvent(classNameRegexp = "org.springframework.context.support.PostProcessorRegistrationDelegate") public static void transform(CtClass clazz, ClassPool classPool) throws NotFoundException, CannotCompileException { clazz.addField(CtField.make("private static final org.hotswap.agent.logging.AgentLogger LOGGER = " + "org.hotswap.agent.logging.AgentLogger.getLogger(org.springframework.context.support.PostProcessorRegistrationDelegate.class);", clazz)); CtMethod ctMethod = clazz.getDeclaredMethod("invokeBeanFactoryPostProcessors", new CtClass[]{classPool.get("java.util.Collection"), classPool.get("org.springframework.beans.factory.config.ConfigurableListableBeanFactory")}); ctMethod.instrument(new ExprEditor() { @Override public void edit(MethodCall m) throws CannotCompileException {<FILL_FUNCTION_BODY>} }); LOGGER.debug("class 'org.springframework.beans.factory.config.PlaceholderConfigurerSupport' patched with placeholder keep."); } }
if (m.getClassName().equals("org.springframework.beans.factory.config.BeanFactoryPostProcessor") && m.getMethodName().equals("postProcessBeanFactory")) { m.replace("{ try{ $_ = $proceed($$); " + "}catch (java.lang.Exception e) {\n" + " LOGGER.debug(\"Failed to invoke BeanDefinitionRegistryPostProcessor: {}, reason:{}\",\n" + " new java.lang.Object[]{$0.getClass().getName(), e.getMessage()});\n" + " };}"); }
358
152
510
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-spring-plugin/src/main/java/org/hotswap/agent/plugin/spring/transformers/ProxyReplacerTransformer.java
ProxyReplacerTransformer
replaceBeanWithProxy
class ProxyReplacerTransformer { public static final String FACTORY_METHOD_NAME = "getBean"; private static CtMethod overrideMethod(CtClass ctClass, CtMethod getConnectionMethodOfSuperclass) throws NotFoundException, CannotCompileException { final CtMethod m = CtNewMethod.delegator(getConnectionMethodOfSuperclass, ctClass); ctClass.addMethod(m); return m; } /** * * @param ctClass * @throws NotFoundException * @throws CannotCompileException */ @OnClassLoadEvent(classNameRegexp = "org.springframework.beans.factory.support.DefaultListableBeanFactory") public static void replaceBeanWithProxy(CtClass ctClass) throws NotFoundException, CannotCompileException {<FILL_FUNCTION_BODY>} /** * Disable cache usage in FastClass.Generator to avoid 'IllegalArgumentException: Protected method' exceptions * * @param ctClass * @throws NotFoundException * @throws CannotCompileException */ @OnClassLoadEvent(classNameRegexp = "org.springframework.cglib.reflect.FastClass.Generator") public static void replaceSpringFastClassGenerator(CtClass ctClass) throws NotFoundException, CannotCompileException { CtConstructor[] constructors = ctClass.getConstructors(); for (CtConstructor ctConstructor : constructors) { ctConstructor.insertAfter("setUseCache(false);"); } } /** * Disable cache usage in FastClass.Generator to avoid 'IllegalArgumentException: Protected method' exceptions * * @param ctClass * @throws NotFoundException * @throws CannotCompileException */ @OnClassLoadEvent(classNameRegexp = "net.sf.cglib.reflect.FastClass.Generator") public static void replaceCglibFastClassGenerator(CtClass ctClass) throws NotFoundException, CannotCompileException { CtConstructor[] constructors = ctClass.getConstructors(); for (CtConstructor ctConstructor : constructors) { ctConstructor.insertAfter("setUseCache(false);"); } } }
CtMethod[] methods = ctClass.getMethods(); for (CtMethod ctMethod : methods) { if (!ctMethod.getName().equals(FACTORY_METHOD_NAME)) continue; if (!ctClass.equals(ctMethod.getDeclaringClass())) { ctMethod = overrideMethod(ctClass, ctMethod); } StringBuilder methodParamTypes = new StringBuilder(); for (CtClass type : ctMethod.getParameterTypes()) { methodParamTypes.append(type.getName()).append(".class").append(", "); } ctMethod.insertAfter("if(true){return org.hotswap.agent.plugin.spring.getbean.ProxyReplacer.register($0, $_,new Class[]{" + methodParamTypes.substring(0, methodParamTypes.length() - 2) + "}, $args);}"); }
568
226
794
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-spring-plugin/src/main/java/org/hotswap/agent/plugin/spring/transformers/ResourcePropertySourceTransformer.java
ResourcePropertySourceTransformer
transform
class ResourcePropertySourceTransformer { private static AgentLogger LOGGER = AgentLogger.getLogger(ResourcePropertySourceTransformer.class); /** * Insert at the beginning of the method: * <pre>public Set<BeanDefinition> findCandidateComponents(String basePackage)</pre> * new code to initialize ClassPathBeanDefinøitionScannerAgent for a base class * It would be better to override a more appropriate method * org.springframework.context.annotation.ClassPathBeanDefinitionScanner.scan() directly, * however there are issues with javassist and varargs parameters. */ @OnClassLoadEvent(classNameRegexp = "org.springframework.core.io.support.ResourcePropertySource") public static void transform(CtClass clazz, ClassPool classPool) throws NotFoundException, CannotCompileException {<FILL_FUNCTION_BODY>} }
clazz.addInterface(classPool.get("org.hotswap.agent.plugin.spring.transformers.api.ReloadableResourcePropertySource")); clazz.addField(CtField.make("private org.springframework.core.io.support.EncodedResource encodedResource;", clazz)); clazz.addField(CtField.make("private org.springframework.core.io.Resource resource;", clazz)); CtConstructor ctConstructor0 = clazz.getDeclaredConstructor(new CtClass[]{classPool.get("java.lang.String"), classPool.get("org.springframework.core.io.support.EncodedResource")}); ctConstructor0.insertBefore("this.encodedResource = $2;"); CtConstructor ctConstructor1 = clazz.getDeclaredConstructor(new CtClass[]{classPool.get("org.springframework.core.io.support.EncodedResource")}); ctConstructor1.insertBefore("this.encodedResource = $1;"); CtConstructor ctConstructor2 = clazz.getDeclaredConstructor(new CtClass[]{classPool.get("java.lang.String"), classPool.get("org.springframework.core.io.Resource")}); ctConstructor2.insertBefore("this.resource = $2;"); CtConstructor ctConstructor3 = clazz.getDeclaredConstructor(new CtClass[]{classPool.get("org.springframework.core.io.Resource")}); ctConstructor3.insertBefore("this.resource = $1;"); clazz.addMethod(CtMethod.make("public org.springframework.core.io.support.EncodedResource encodedResource() { return this.encodedResource; }", clazz)); clazz.addMethod(CtMethod.make("public org.springframework.core.io.Resource resource() { return this.resource; }", clazz)); LOGGER.debug("class 'org.springframework.core.io.support.DefaultPropertySourceFactory' patched with PropertySource keep.");
219
484
703
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-spring-plugin/src/main/java/org/hotswap/agent/plugin/spring/transformers/XmlBeanDefinitionScannerTransformer.java
XmlBeanDefinitionScannerTransformer
transform
class XmlBeanDefinitionScannerTransformer { private static AgentLogger LOGGER = AgentLogger.getLogger(XmlBeanDefinitionScannerTransformer.class); /** * Insert at the beginning of the method: * <pre>public Set<BeanDefinition> findCandidateComponents(String basePackage)</pre> * new code to initialize ClassPathBeanDefinitionScannerAgent for a base class * It would be better to override a more appropriate method * org.springframework.context.annotation.ClassPathBeanDefinitionScanner.scan() directly, * however there are issues with javassist and varargs parameters. */ @OnClassLoadEvent(classNameRegexp = "org.springframework.beans.factory.xml.XmlBeanDefinitionReader") public static void transform(CtClass clazz, ClassPool classPool) throws NotFoundException, CannotCompileException {<FILL_FUNCTION_BODY>} }
CtMethod method = clazz.getDeclaredMethod("registerBeanDefinitions", new CtClass[]{ classPool.get("org.w3c.dom.Document"), classPool.get("org.springframework.core.io.Resource")}); method.insertBefore(XmlBeanDefinitionScannerAgent.class.getName() + ".registerXmlBeanDefinitionScannerAgent(this, $2);"); LOGGER.debug("Class 'org.springframework.beans.factory.xml.XmlBeanDefinitionReader' patched with xmlReader registration.");
221
131
352
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-spring-plugin/src/main/java/org/hotswap/agent/plugin/spring/transformers/support/InitMethodEnhance.java
InitMethodEnhance
catchException
class InitMethodEnhance { public static String catchException(String objectName, String loggerName, String exceptionName, String from, boolean hasReturnValue) {<FILL_FUNCTION_BODY>} }
return "{" + "if (org.hotswap.agent.plugin.spring.reload.BeanFactoryAssistant.getBeanFactoryAssistant($0) == null || " + " !org.hotswap.agent.plugin.spring.reload.BeanFactoryAssistant.getBeanFactoryAssistant($0).isReload()) {" + " throw " + exceptionName + " ; }" + "else {" + " " + loggerName + ".warning(\"Failed to invoke init method of {} from {}: {}\", " + "new java.lang.Object[]{" + objectName + ".getClass().getName(),\"" + from + "\", "+ exceptionName + ".getMessage()});" + " " + loggerName + ".debug(\"the detail reason as following{}: \", " + exceptionName + ", new java.lang.Object[]{ \" \"});" + (hasReturnValue ? " return " + objectName + ";" : "return;") + " } " + "}";
54
252
306
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-spring-plugin/src/main/java/org/hotswap/agent/plugin/spring/utils/AnnotatedBeanDefinitionUtils.java
AnnotatedBeanDefinitionUtils
getFactoryMethodMetadata
class AnnotatedBeanDefinitionUtils { public static MethodMetadata getFactoryMethodMetadata(AnnotatedBeanDefinition beanDefinition) {<FILL_FUNCTION_BODY>} public static boolean containValueAnnotation(Annotation[][] annotations) { for (int i = 0; i < annotations.length; i++) { Annotation[] annotationArray = annotations[i]; for (Annotation annotation : annotationArray) { if (annotation.annotationType().getName().equals("org.springframework.beans.factory.annotation.Value")) { return true; } } } return false; } }
Object target = ReflectionHelper.invokeNoException(beanDefinition, beanDefinition.getClass().getName(), beanDefinition.getClass().getClassLoader(), "getFactoryMethodMetadata", new Class<?>[]{}); if (target != null) { return (MethodMetadata) target; } /** earlier than spring 4.1 */ if (beanDefinition.getSource() != null && beanDefinition.getSource() instanceof StandardMethodMetadata) { StandardMethodMetadata standardMethodMetadata = (StandardMethodMetadata) beanDefinition.getSource(); return standardMethodMetadata; } return null;
153
144
297
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-spring-plugin/src/main/java/org/hotswap/agent/plugin/spring/utils/RegistryUtils.java
RegistryUtils
maybeRegistryToBeanFactory
class RegistryUtils { public static DefaultListableBeanFactory maybeRegistryToBeanFactory(BeanDefinitionRegistry registry) {<FILL_FUNCTION_BODY>} }
if (registry instanceof DefaultListableBeanFactory) { return (DefaultListableBeanFactory) registry; } else if (registry instanceof GenericApplicationContext) { return ((GenericApplicationContext) registry).getDefaultListableBeanFactory(); } return null;
41
69
110
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-spring-plugin/src/main/java/org/hotswap/agent/plugin/spring/utils/ResourceUtils.java
ResourceUtils
convertToClasspathURL
class ResourceUtils { private static final AgentLogger LOGGER = AgentLogger.getLogger(XmlBeanDefinitionScannerAgent.class); public static String getPath(Resource resource) { if (resource == null) { return null; } String path; if (resource instanceof ClassPathResource) { path = ((ClassPathResource) resource).getPath(); } else if (resource instanceof ByteArrayResource) { LOGGER.debug("Cannot get path from ByteArrayResource: {}", new String(((ByteArrayResource) resource).getByteArray())); return null; } else { try { path = convertToClasspathURL(resource.getURL().getPath()); } catch (IOException e) { LOGGER.error("Cannot get url from resource: {}", e, resource); return null; } } return path; } /** * convert src/main/resources/xxx.xml and classes/xxx.xml to xxx.xml * * @param filePath the file path to convert * @return if convert succeed, return classpath path, or else return file path */ public static String convertToClasspathURL(String filePath) { String[] paths = filePath.split("src/main/resources/"); if (paths.length == 2) { return paths[1]; } paths = filePath.split("WEB-INF/classes/"); if (paths.length == 2) { return paths[1]; } paths = filePath.split("WEB-INF/"); if (paths.length == 2) { return paths[1]; } paths = filePath.split("target/classes/"); if (paths.length == 2) { return paths[1]; } paths = filePath.split("target/test-classes/"); if (paths.length == 2) { return paths[1]; } LOGGER.error("failed to convert filePath {} to classPath path", filePath); return filePath; } /** * convert src/main/resources/xxx.xml and classes/xxx.xml to xxx.xml * * @param extraClassPaths the extra class paths * @param filePath the file path to convert * @return if convert succeed, return classpath path, or else return file path */ public static String convertToClasspathURL(URL[] extraClassPaths, String filePath) {<FILL_FUNCTION_BODY>} }
String path = convertToClasspathURL(filePath); if (!StringUtils.isEmpty(path)) { return path; } if (extraClassPaths != null && extraClassPaths.length != 0) { for (URL extraClassPath : extraClassPaths) { String extraClassPathStr = extraClassPath.getPath(); String[] paths = filePath.split(extraClassPathStr); if (paths.length == 2) { return paths[1]; } } } LOGGER.error("failed to convert filePath {} to classPath path", filePath); return filePath;
631
161
792
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-thymeleaf-plugin/src/main/java/org/hotswap/agent/plugin/thymeleaf/ThymeleafPlugin.java
ThymeleafPlugin
patchParseAndProcess
class ThymeleafPlugin { private static final AgentLogger LOGGER = AgentLogger.getLogger(ThymeleafPlugin.class); @OnClassLoadEvent(classNameRegexp = "org.thymeleaf.engine.TemplateManager") public static void patchParseAndProcess(ClassPool classPool, final CtClass ctClass) {<FILL_FUNCTION_BODY>} }
try { CtMethod method = ctClass.getDeclaredMethod("parseAndProcess", new CtClass[]{ classPool.get("org.thymeleaf.TemplateSpec"), classPool.get("org.thymeleaf.context.IContext"), classPool.get("java.io.Writer")}); method.insertBefore("clearCachesFor($1.getTemplate());"); } catch (NotFoundException | CannotCompileException e) { LOGGER.debug("Cannot patch parseAndProcess method for {}", ctClass.getName(), e); }
97
142
239
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-undertow-plugin/src/main/java/org/hotswap/agent/plugin/undertow/PrefixingResourceManager.java
PrefixingResourceManager
removeResourceChangeListener
class PrefixingResourceManager implements ResourceManager { private static AgentLogger LOGGER = AgentLogger.getLogger(PrefixingResourceManager.class); private List<ResourceManager> delegates; public PrefixingResourceManager(ResourceManager delegate) { this.delegates = new ArrayList<>(); this.delegates.add(delegate); } public void setExtraResources(List extraResources) { List<ResourceManager> delegates = new ArrayList<>(); for (Object o: extraResources) { File resource = File.class.cast(o); try { delegates.add(new FileResourceManager(resource.getCanonicalFile(), 1024, true, false, "/")); } catch (IOException e) { LOGGER.warning("Unable to create cannonical file from {}. File skipped.", resource.getName(), e); } } delegates.addAll(this.delegates); this.delegates = delegates; } @Override public Resource getResource(String path) throws IOException { for(ResourceManager d : delegates) { Resource res = d.getResource(path); if(res != null) { return res; } } return null; } @Override public boolean isResourceChangeListenerSupported() { return true; } @Override public void registerResourceChangeListener(ResourceChangeListener listener) { for(ResourceManager del : delegates) { if(del.isResourceChangeListenerSupported()) { del.registerResourceChangeListener(listener); } } } @Override public void removeResourceChangeListener(ResourceChangeListener listener) {<FILL_FUNCTION_BODY>} @Override public void close() throws IOException { for(ResourceManager del : delegates) { IoUtils.safeClose(del); } } }
for(ResourceManager del : delegates) { if(del.isResourceChangeListenerSupported()) { del.removeResourceChangeListener(listener); } }
487
47
534
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-undertow-plugin/src/main/java/org/hotswap/agent/plugin/undertow/UndertowPlugin.java
UndertowPlugin
init
class UndertowPlugin { private static AgentLogger LOGGER = AgentLogger.getLogger(UndertowPlugin.class); // Undertow resource manager object to a application classloader static Map<Object, ClassLoader> registeredResourceManagersMap = new HashMap<>(); // For each app classloader map of undertow repository name to associated watch resource classloader private static Map<ClassLoader, Map<String, ClassLoader>> extraRepositories = new HashMap<>(); String undertowVersion = ""; /** * Init the plugin during DeploymentManagerImpl.deploy lifecycle. This method is invoked before the plugin is initialized. * @param appClassLoader main web deplyment classloader. * @param resourceManager undertow resource manager associated to deployment */ public static void init(ClassLoader appClassLoader, Object resourceManager) {<FILL_FUNCTION_BODY>} private static void addExtraResources(List<File> extraResources, URL[] extraURLs) { for (int i=0; i < extraURLs.length; i++) { try { File file = new File(extraURLs[i].toURI()); if (file.isDirectory()) { extraResources.add(file); } } catch (URISyntaxException e) { LOGGER.warning("Unable to convert resource URL '{}' to URI. URL is skipped.", e, extraURLs[i]); } } } /** * Init plugin and resolve version. * * @param undertowVersion the undertow version * @param appClassLoader the app class loader */ private void init(String undertowVersion, ClassLoader appClassLoader ) { LOGGER.info("Undertow plugin initialized - Undertow version '{}'", undertowVersion); this.undertowVersion = undertowVersion; } /** * Close plugin * * @param classLoader the class loader */ public static void close(ClassLoader classLoader) { Map<String, ClassLoader> registerMap = extraRepositories.remove(classLoader); if (registerMap != null) { for (ClassLoader loader : registerMap.values()) { PluginManager.getInstance().getWatcher().closeClassLoader(loader); } } } /** * Resolve the server version from Version class. * @param appClassLoader application classloader * @return the server version */ private static String resolveUndertowVersion(ClassLoader appClassLoader) { try { Class version = appClassLoader.loadClass("io.undertow.Version"); return (String) ReflectionHelper.invoke(null, version, "getVersionString", new Class[]{}); } catch (Exception e) { LOGGER.debug("Unable to resolve undertow version", e); return "unknown"; } } }
String version = resolveUndertowVersion(appClassLoader); registeredResourceManagersMap.put(resourceManager, appClassLoader); // create plugin configuration in advance to get extraClasspath and watchResources properties PluginConfiguration pluginConfiguration = new PluginConfiguration(appClassLoader); List<File> extraResources = new ArrayList<>(); addExtraResources(extraResources, pluginConfiguration.getExtraClasspath()); addExtraResources(extraResources, pluginConfiguration.getWatchResources()); addExtraResources(extraResources, pluginConfiguration.getWebappDir()); try { ReflectionHelper.invoke(resourceManager, resourceManager.getClass(), "setExtraResources", new Class[] { List.class }, extraResources); } catch (Exception e) { LOGGER.error("init() exception {}.", e.getMessage()); } Object plugin = PluginManagerInvoker.callInitializePlugin(UndertowPlugin.class, appClassLoader); if (plugin != null) { ReflectionHelper.invoke(plugin, plugin.getClass(), "init", new Class[]{String.class, ClassLoader.class}, version, appClassLoader); } else { LOGGER.debug("UndertowPlugin is disabled in {}", appClassLoader); }
723
307
1,030
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-undertow-plugin/src/main/java/org/hotswap/agent/plugin/undertow/UndertowTransformer.java
UndertowTransformer
patchWebappLoader
class UndertowTransformer { private static AgentLogger LOGGER = AgentLogger.getLogger(UndertowTransformer.class); @OnClassLoadEvent(classNameRegexp = "io.undertow.servlet.core.DeploymentManagerImpl") public static void patchWebappLoader(CtClass ctClass) throws NotFoundException, CannotCompileException, ClassNotFoundException {<FILL_FUNCTION_BODY>} }
try { ctClass.getDeclaredMethod("deploy").insertBefore( "{" + "org.hotswap.agent.plugin.undertow.PrefixingResourceManager rm=" + "new org.hotswap.agent.plugin.undertow.PrefixingResourceManager(originalDeployment.getResourceManager());" + "originalDeployment.setResourceManager(rm);" + UndertowPlugin.class.getName() + ".init(originalDeployment.getClassLoader(),rm);" + "}" ); } catch (NotFoundException e) { LOGGER.error("io.undertow.servlet.core.DeploymentManagerImpl does not contain start() method."); } try { ctClass.getDeclaredMethod("stop").insertBefore( PluginManagerInvoker.buildCallCloseClassLoader("originalDeployment.getClassLoader()") + UndertowPlugin.class.getName() + ".close(originalDeployment.getClassLoader());" ); } catch (NotFoundException e) { LOGGER.error("orgio.undertow.servlet.core.DeploymentManagerImpl does not contain stop() method."); }
108
291
399
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-vaadin-plugin/src/main/java/org/hotswap/agent/plugin/vaadin/VaadinIntegration.java
VaadinIntegration
updateRoutes
class VaadinIntegration { private static final AgentLogger LOGGER = AgentLogger .getLogger(VaadinIntegration.class); private VaadinServlet vaadinServlet = null; /** * Sets the Vaadin servlet once instantiated. * * @param servlet * the Vaadin serlvet */ public void servletInitialized(VaadinServlet servlet) { vaadinServlet = servlet; LOGGER.info("{} initialized for servlet {}", getClass(), servlet); } /** * Update Flow route registry and push refresh to UIs (concrete parameter * types as {@link org.hotswap.agent.command.ReflectionCommand} determines * the method from actual argument types). * * @param addedClasses * returns classes that have been added or modified * @param modifiedClasses * returns classes that have been deleted */ public void updateRoutes(HashSet<Class<?>> addedClasses, HashSet<Class<?>> modifiedClasses) {<FILL_FUNCTION_BODY>} /** * Reload UI in browser. */ public void reload() { VaadinService vaadinService = vaadinServlet.getService(); Optional<BrowserLiveReload> liveReload = BrowserLiveReloadAccessor.getLiveReloadFromService(vaadinService); if (liveReload.isPresent()) { liveReload.get().reload(); LOGGER.info("Live reload triggered"); } } /** * Updates route registry as necessary when classes have been added / * modified / deleted. * * TODO: move to flow-server internal utility methods. * * @param registry * route registry * @param addedClasses * added classes * @param modifiedClasses * modified classes * @param deletedClasses * deleted classes */ private static void updateRouteRegistry(RouteRegistry registry, Set<Class<?>> addedClasses, Set<Class<?>> modifiedClasses, Set<Class<?>> deletedClasses) { RouteConfiguration routeConf = RouteConfiguration.forRegistry(registry); registry.update(() -> { // remove deleted classes and classes that lost the annotation from registry Stream.concat(deletedClasses.stream(), modifiedClasses.stream().filter( clazz -> !clazz.isAnnotationPresent(Route.class))) .filter(Component.class::isAssignableFrom) .forEach(clazz -> { Class<? extends Component> componentClass = (Class<? extends Component>) clazz; routeConf.removeRoute(componentClass); }); // add new routes to registry Stream.concat(addedClasses.stream(), modifiedClasses.stream()) .distinct() .filter(Component.class::isAssignableFrom) .filter(clazz -> clazz.isAnnotationPresent(Route.class)) .forEach(clazz -> { Class<? extends Component> componentClass = (Class<? extends Component>) clazz; routeConf.removeRoute(componentClass); routeConf.setAnnotatedRoute(componentClass); }); }); } }
assert (vaadinServlet != null); LOGGER.debug("The following classes were added:"); addedClasses.forEach(clazz -> LOGGER.debug("+ {}", clazz)); LOGGER.debug("The following classes were modified:"); modifiedClasses.forEach(clazz -> LOGGER.debug("# {}", clazz)); Method getInstanceMethod = null; Object getInstanceMethodParam = null; try { // Vaadin 14.2+ getInstanceMethod = ApplicationRouteRegistry.class.getMethod("getInstance", VaadinContext.class); getInstanceMethodParam = vaadinServlet.getService().getContext(); } catch (NoSuchMethodException ex1) { // In Vaadin 14.1, this method instead takes a ServletContext parameter LOGGER.debug("ApplicationRouteRegistry::getInstance(VaadinContext) not found"); try { getInstanceMethod = ApplicationRouteRegistry.class.getMethod("getInstance", ServletContext.class); getInstanceMethodParam = vaadinServlet.getServletContext(); } catch (NoSuchMethodException ex2) { // In Vaadin 14.1, this method takes a ServletContext parameter LOGGER.warning("Unable to obtain ApplicationRouteRegistry instance; routes are not updated "); return; } } try { ApplicationRouteRegistry registry = (ApplicationRouteRegistry) getInstanceMethod.invoke(null, getInstanceMethodParam); updateRouteRegistry(registry, addedClasses, modifiedClasses, Collections.emptySet()); } catch (IllegalAccessException | InvocationTargetException ex) { LOGGER.warning("Unable to obtain ApplicationRouteRegistry instance; routes are not updated:", ex); }
820
429
1,249
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-vaadin-plugin/src/main/java/org/hotswap/agent/plugin/vaadin/VaadinPlugin.java
VaadinPlugin
getReloadQuietTime
class VaadinPlugin { @Init Scheduler scheduler; @Init ClassLoader appClassLoader; @Init PluginConfiguration pluginConfiguration; private UpdateRoutesCommand updateRouteRegistryCommand; private ReflectionCommand reloadCommand; private ReflectionCommand clearReflectionCache = new ReflectionCommand(this, "com.vaadin.flow.internal.ReflectionCache", "clearAll"); private Set<Class<?>> addedClasses = new HashSet<>(); private Set<Class<?>> modifiedClasses = new HashSet<>(); private static final AgentLogger LOGGER = AgentLogger.getLogger(VaadinPlugin.class); private static final String RELOAD_QUIET_TIME_PARAMETER = "vaadin.liveReloadQuietTime"; private static final int DEFAULT_RELOAD_QUIET_TIME = 1000; // ms private int reloadQuietTime = 0; public VaadinPlugin() { } @OnClassLoadEvent(classNameRegexp = "com.vaadin.flow.server.VaadinServlet") public static void init(CtClass ctClass) throws NotFoundException, CannotCompileException { String src = PluginManagerInvoker .buildInitializePlugin(VaadinPlugin.class); src += PluginManagerInvoker.buildCallPluginMethod(VaadinPlugin.class, "registerServlet", "this", Object.class.getName()); ctClass.getDeclaredConstructor(new CtClass[0]).insertAfter(src); LOGGER.info("Initialized Vaadin plugin"); } public void registerServlet(Object vaadinServlet) { try { Class<?> vaadinIntegrationClass = resolveClass("org.hotswap.agent.plugin.vaadin.VaadinIntegration"); Object vaadinIntegration = vaadinIntegrationClass.getConstructor() .newInstance(); Class<?> vaadinServletClass = resolveClass("com.vaadin.flow.server.VaadinServlet"); Method m = vaadinIntegrationClass.getDeclaredMethod("servletInitialized", vaadinServletClass); m.invoke(vaadinIntegration, vaadinServlet); updateRouteRegistryCommand = new UpdateRoutesCommand(vaadinIntegration); reloadCommand = new ReflectionCommand(vaadinIntegration, "reload"); } catch (ClassNotFoundException | NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException ex) { LOGGER.error(null, ex); } } @OnClassLoadEvent(classNameRegexp = ".*", events = LoadEvent.REDEFINE) public void invalidateReflectionCache(CtClass ctClass) throws Exception { LOGGER.debug("Redefined class {}, clearing Vaadin reflection cache and reloading browser", ctClass.getName()); scheduler.scheduleCommand(clearReflectionCache); scheduler.scheduleCommand(reloadCommand, getReloadQuietTime()); } @OnClassFileEvent(classNameRegexp = ".*", events = { FileEvent.CREATE, FileEvent.MODIFY }) public void classCreated(FileEvent eventType, CtClass ctClass) throws Exception { if (FileEvent.CREATE.equals(eventType)) { LOGGER.debug("Create class file event for " + ctClass.getName()); addedClasses.add(resolveClass(ctClass.getName())); } else if (FileEvent.MODIFY.equals(eventType)) { LOGGER.debug("Modify class file event for " + ctClass.getName()); modifiedClasses.add(resolveClass(ctClass.getName())); } // Note that scheduling multiple calls to the same command postpones it scheduler.scheduleCommand(updateRouteRegistryCommand); } private Class<?> resolveClass(String name) throws ClassNotFoundException { return Class.forName(name, true, appClassLoader); } private int getReloadQuietTime() {<FILL_FUNCTION_BODY>} private class UpdateRoutesCommand extends ReflectionCommand { private final Object vaadinIntegration; UpdateRoutesCommand(Object vaadinIntegration) { super(vaadinIntegration, "updateRoutes", addedClasses, modifiedClasses); this.vaadinIntegration = vaadinIntegration; } // NOTE: Identity equality semantics @Override public boolean equals(Object that) { return this == that; } @Override public int hashCode() { return System.identityHashCode(vaadinIntegration); } @Override public void executeCommand() { super.executeCommand(); addedClasses.clear(); modifiedClasses.clear(); } } }
if (reloadQuietTime <= 0) { reloadQuietTime = DEFAULT_RELOAD_QUIET_TIME; String reloadQuietTimeValue = pluginConfiguration.getProperty(RELOAD_QUIET_TIME_PARAMETER); if (reloadQuietTimeValue != null) { if (reloadQuietTimeValue.matches("[1-9][0-1]+")) { reloadQuietTime = Integer.parseInt(reloadQuietTimeValue); LOGGER.info("Live-reload quiet time is {} ms", reloadQuietTime); } else { LOGGER.error("Illegal value '{}' for parameter {}, using default of {} ms", reloadQuietTimeValue, RELOAD_QUIET_TIME_PARAMETER, DEFAULT_RELOAD_QUIET_TIME); } } } return reloadQuietTime;
1,227
222
1,449
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-velocity-plugin/src/main/java/org/hotswap/agent/plugin/velocity/VelocityPlugin.java
VelocityPlugin
patchSetPreferFileSystemAccess
class VelocityPlugin { private static final AgentLogger LOGGER = AgentLogger.getLogger(VelocityPlugin.class); @OnClassLoadEvent(classNameRegexp = "org.springframework.ui.velocity.VelocityEngineFactory") public static void patchSetPreferFileSystemAccess(ClassPool classPool, final CtClass ctClass) {<FILL_FUNCTION_BODY>} @OnClassLoadEvent(classNameRegexp = "org.springframework.ui.velocity.VelocityEngineFactory") public static void patchSetResourceLoaderPath(ClassPool classPool, final CtClass ctClass) { try { CtMethod method = ctClass.getDeclaredMethod("setResourceLoaderPath", new CtClass[]{classPool.get("java.lang.String")}); method.insertAfter("this.resourceLoaderPath = \"classpath:/$$ha$velocity/,\" + this.resourceLoaderPath;"); } catch (NotFoundException | CannotCompileException e) { LOGGER.debug("Cannot patch parseAndProcess method for {}", ctClass.getName(), e); } } @OnClassLoadEvent(classNameRegexp = "org.springframework.ui.velocity.VelocityEngineFactory") public static void patchInitSpringResourceLoader(ClassPool classPool, final CtClass ctClass) { try { CtMethod method = ctClass.getDeclaredMethod("initSpringResourceLoader", new CtClass[]{classPool.get("org.apache.velocity.app.VelocityEngine"), classPool.get("java.lang.String")}); method.insertAfter("$1.setProperty(\"spring.resource.loader.cache\", \"false\");"); } catch (NotFoundException | CannotCompileException e) { LOGGER.debug("Cannot patch parseAndProcess method for {}", ctClass.getName(), e); } } }
try { CtMethod method = ctClass.getDeclaredMethod("setPreferFileSystemAccess", new CtClass[]{classPool.get("boolean")}); method.insertAfter("this.preferFileSystemAccess = false;"); } catch (NotFoundException | CannotCompileException e) { LOGGER.debug("Cannot patch parseAndProcess method for {}", ctClass.getName(), e); }
470
104
574
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-weblogic-plugin/src/main/java/org/hotswap/agent/plugin/weblogic/WeblogicPlugin.java
WeblogicPlugin
transformGenericClassLoader
class WeblogicPlugin { @Init ClassLoader moduleClassLoader; static protected AgentLogger LOGGER = AgentLogger.getLogger(WeblogicPlugin.class); @OnClassLoadEvent(classNameRegexp = "weblogic.utils.classloaders.ChangeAwareClassLoader") public static void transformChangeAwareClassLoader(ClassPool classPool, CtClass ctClass) throws NotFoundException, CannotCompileException { LOGGER.info("transformChangeAwareClassLoader: {}", ctClass.getSimpleName()); String src = WeblogicPlugin.class.getName() + ".logMessage(\"ChangeAwareClassLoaderConstructor -> \" + $1.toString());"; ctClass.getDeclaredConstructor(new CtClass[] { classPool.get("weblogic.utils.classloaders.ClassFinder"), CtClass.booleanType, classPool.get("java.lang.ClassLoader") }) .insertBefore(src); } @OnClassLoadEvent(classNameRegexp = "weblogic.utils.classloaders.MultiClassFinder") public static void transformMultiClassFinder(ClassPool classPool, CtClass ctClass) throws NotFoundException, CannotCompileException { LOGGER.info("MultiClassFinder: {}", ctClass.getSimpleName()); String srcAddFinder = WeblogicPlugin.class.getName() + ".logMessage(\"MultiClassFinder#addFinder -> \" + $1.toString());"; ctClass.getDeclaredMethod("addFinder", new CtClass[] { classPool.get("weblogic.utils.classloaders.ClassFinder") }).insertBefore(srcAddFinder); String srcAddFinderFirst = WeblogicPlugin.class.getName() + ".logMessage(\"MultiClassFinder#addFinderFirst -> \" + $1.toString());"; ctClass.getDeclaredMethod("addFinderFirst", new CtClass[] { classPool.get("weblogic.utils.classloaders.ClassFinder") }).insertBefore(srcAddFinderFirst); } @OnClassLoadEvent(classNameRegexp = "weblogic.utils.classloaders.CompositeWebAppFinder") public static void transformCompositeWebAppFinder(ClassPool classPool, CtClass ctClass) throws NotFoundException, CannotCompileException { LOGGER.info("CompositeWebAppFinder: {}", ctClass.getSimpleName()); String src = WeblogicPlugin.class.getName() + ".logMessage(\"CompositeWebAppFinder#addLibraryFinder -> \" + $1.toString());"; ctClass.getDeclaredMethod("addLibraryFinder", new CtClass[] { classPool.get("weblogic.utils.classloaders.ClassFinder") }).insertBefore(src); } @OnClassLoadEvent(classNameRegexp = "weblogic.utils.classloaders.GenericClassLoader") public static void transformGenericClassLoader(ClassPool classPool, CtClass ctClass) throws NotFoundException, CannotCompileException {<FILL_FUNCTION_BODY>} public static void logMessage(String str){ LOGGER.info("logmessage: {}", str); } public static void logException(Exception e){ LOGGER.error("logException: {}", e); } }
LOGGER.info("transformGenericClassLoader: {}", ctClass.getSimpleName()); CtClass ctHaClassLoader = classPool.get(HotswapAgentClassLoaderExt.class.getName()); ctClass.addInterface(ctHaClassLoader); // Implementation of HotswapAgentClassLoaderExt.setExtraClassPath(...) //@formatter:off ctClass.addMethod(CtNewMethod.make( "public void $$ha$setExtraClassPath(java.net.URL[] extraClassPath) {" + WeblogicPlugin.class.getName() + ".logMessage(\"setExtraClassPath in=\" + extraClassPath[0].toString());" + "try {" + "weblogic.utils.classloaders.MultiClassFinder multiClassFinder = new weblogic.utils.classloaders.MultiClassFinder();" + "for (int i=0; i<extraClassPath.length; i++) {" + "try {" + "java.net.URL url = extraClassPath[i];" + "java.io.File root = new java.io.File(url.getPath());" + "weblogic.utils.classloaders.IndexedDirectoryClassFinder indexedDirectoryClassFinder = new weblogic.utils.classloaders.IndexedDirectoryClassFinder(root);" + "multiClassFinder.addFinder(indexedDirectoryClassFinder);" + "} catch (java.lang.Exception e) {" + WeblogicPlugin.class.getName() + ".logException(e);" + "}" + "}" + "this.addClassFinderFirst(multiClassFinder);" + WeblogicPlugin.class.getName() + ".logMessage(\"setExtraClassPath result=\" + this.getClassPath());" + "} catch (java.lang.Exception e) {" + WeblogicPlugin.class.getName() + ".logException(e);" + "}" + "}", ctClass) ); //@formatter:on ctClass.addMethod( CtNewMethod.make( "public void $$ha$setWatchResourceLoader(" + WatchResourcesClassLoader.class.getName() + " watchResourceLoader) { " + WeblogicPlugin.class.getName() + ".logMessage(\"WatchResourcesClassLoader -> \" + watchResourceLoader.toString());" + "}", ctClass ));
834
614
1,448
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-webobjects-plugin/src/main/java/org/hotswap/agent/plugin/webobjects/HotswapWebObjectsPlugin.java
ClearActionCache
executeCommand
class ClearActionCache implements Command { @Override public void executeCommand() {<FILL_FUNCTION_BODY>} }
try { nsThreadsafeMutableDictionary_removeAllObjects.invoke(actionClassesCacheDictionnary); LOGGER.info("Resetting Action class cache"); } catch (Exception e) { e.printStackTrace(); }
35
63
98
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-weld-jakarta-plugin/src/main/java/org/hotswap/agent/plugin/weld_jakarta/ArchivePathHelper.java
ArchivePathHelper
archivePathToURLViaURLClassLoader
class ArchivePathHelper { private static AgentLogger LOGGER = AgentLogger.getLogger(ArchivePathHelper.class); public static String getNormalizedArchivePath(CtClass ctClass) throws NotFoundException { String classFilePath = ctClass.getURL().getFile(); String className = ctClass.getName().replace(".", "/"); // archive path ends with '/' therefore we set end position before the '/' (-1) return classFilePath.substring(0, classFilePath.indexOf(className) - 1); } /** * Method resolves archive path from BdaId * * @param classLoader the class loader * @param archiveId the archive id * @return the normalized archive path */ public static String getNormalizedArchivePath(ClassLoader classLoader, String archiveId) { URL archiveURL = archivePathToURL(classLoader, archiveId); if (archiveURL != null) { try { String result = archiveURL.getFile(); // Strip trailing "/" from normalized archive path while (result.endsWith("/")) { result = result.substring(0, result.length() -1); } return result; } catch (Exception e) { LOGGER.error("getNormalizedArchivePath() exception {}.", e.getMessage()); } } return null; } private static URL archivePathToURL(ClassLoader classLoader, String archiveId) { URL result = archiveFilePathToURL(archiveId); if (result == null) { // File doesn't exists, try to resolve it using appClassLoader if (classLoader instanceof URLClassLoader) { result = archivePathToURLViaURLClassLoader((URLClassLoader) classLoader, archiveId); } } return result; } private static URL archivePathToURLViaURLClassLoader(URLClassLoader urlClassLoader, String archivePath) {<FILL_FUNCTION_BODY>} private static URL archiveFilePathToURL(String archivePath) { File f = new File(archivePath); if (f.exists()) { try { try { // Try to format as a URL? return f.toURI().toURL(); } catch (MalformedURLException e) { // try to locate a file if (archivePath.startsWith("./")) archivePath = archivePath.substring(2); File file = new File(archivePath).getCanonicalFile(); return file.toURI().toURL(); } } catch (Exception e) { // Swallow exception } } return null; } }
URL[] urls = urlClassLoader.getURLs(); if (urls != null) { for (URL url: urls) { String fileName = url.getFile(); String checkedArchivePath = (fileName.endsWith("/") && !archivePath.endsWith("/")) ? (archivePath + "/") : archivePath; if (fileName.endsWith(checkedArchivePath)) { return archiveFilePathToURL(fileName); } } } return null;
671
129
800
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-weld-jakarta-plugin/src/main/java/org/hotswap/agent/plugin/weld_jakarta/WeldClassSignatureHelper.java
WeldClassSignatureHelper
getSignatureForProxyClass
class WeldClassSignatureHelper { private static AgentLogger LOGGER = AgentLogger.getLogger(WeldClassSignatureHelper.class); private static final ClassSignatureElement[] SIGNATURE_ELEM_PROXY = { ClassSignatureElement.SUPER_CLASS, ClassSignatureElement.INTERFACES, ClassSignatureElement.CLASS_ANNOTATION, ClassSignatureElement.CONSTRUCTOR, ClassSignatureElement.METHOD, ClassSignatureElement.METHOD_ANNOTATION, ClassSignatureElement.METHOD_PARAM_ANNOTATION, ClassSignatureElement.METHOD_EXCEPTION, ClassSignatureElement.FIELD, ClassSignatureElement.FIELD_ANNOTATION }; private static final ClassSignatureElement[] SIGNATURE_ELEM_METHOD_FIELDS = { ClassSignatureElement.SUPER_CLASS, ClassSignatureElement.INTERFACES, ClassSignatureElement.CLASS_ANNOTATION, ClassSignatureElement.CONSTRUCTOR, ClassSignatureElement.CONSTRUCTOR_PRIVATE, // private constructors are used if CONSTRUCTOR && CONSTRUCTOR_PRIVATE are set ClassSignatureElement.METHOD, ClassSignatureElement.METHOD_PRIVATE, // private methods are used if METHOD && METHOD_PRIVATE are set ClassSignatureElement.METHOD_ANNOTATION, // applies to constructors as well ClassSignatureElement.METHOD_PARAM_ANNOTATION, // applies to constructors as well ClassSignatureElement.FIELD, ClassSignatureElement.FIELD_ANNOTATION }; private static final ClassSignatureElement[] SIGNATURE_ELEM_FIELDS = { ClassSignatureElement.FIELD, ClassSignatureElement.FIELD_ANNOTATION }; /** * Gets the class signature for proxy class comparison * * @param clazz the clazz for which signature is calculated * @return the java class signature */ public static String getSignatureForProxyClass(Class<?> clazz) {<FILL_FUNCTION_BODY>} /** * Gets the signature by strategy. * * @param strategy the strategy * @param clazz the clazz * @return the signature by strategy */ public static String getSignatureByStrategy(BeanReloadStrategy strategy, Class<?> clazz) { if (strategy == null) { strategy = BeanReloadStrategy.NEVER; } switch (strategy) { case CLASS_CHANGE : return null; case METHOD_FIELD_SIGNATURE_CHANGE : return getClassMethodFieldsSignature(clazz); case FIELD_SIGNATURE_CHANGE : return getClassFieldsSignature(clazz); default: case NEVER: return null; } } private static String getClassMethodFieldsSignature(Class<?> clazz) { try { return ClassSignatureComparerHelper.getJavaClassSignature(clazz, SIGNATURE_ELEM_METHOD_FIELDS); } catch (Exception e) { LOGGER.error("getSignatureForProxyClass(): Error reading signature", e); return null; } } private static String getClassFieldsSignature(Class<?> clazz) { try { return ClassSignatureComparerHelper.getJavaClassSignature(clazz, SIGNATURE_ELEM_FIELDS); } catch (Exception e) { LOGGER.error("getSignatureForProxyClass(): Error reading signature", e); return null; } } }
try { return ClassSignatureComparerHelper.getJavaClassSignature(clazz, SIGNATURE_ELEM_PROXY); } catch (Exception e) { LOGGER.error("getSignatureForProxyClass(): Error reading signature", e); return null; }
877
71
948
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-weld-jakarta-plugin/src/main/java/org/hotswap/agent/plugin/weld_jakarta/beans/ContextualReloadHelper.java
ContextualReloadHelper
reinitialize
class ContextualReloadHelper { private static AgentLogger LOGGER = AgentLogger.getLogger(ContextualReloadHelper.class); public static void reload(WeldHotswapContext ctx) { Set<Contextual<Object>> beans = ctx.$$ha$getBeansToReloadWeld(); if (beans != null && !beans.isEmpty()) { LOGGER.debug("Starting re-loading Contextuals in {}, {}", ctx, beans.size()); Iterator<Contextual<Object>> it = beans.iterator(); while (it.hasNext()) { Contextual<Object> managedBean = it.next(); destroy(ctx, managedBean); } beans.clear(); LOGGER.debug("Finished re-loading Contextuals in {}", ctx); } } /** * Tries to add the bean in the context so it is reloaded in the next activation of the context. * * @param ctx * @param managedBean * @return */ public static boolean addToReloadSet(Context ctx, Contextual<Object> managedBean) { try { LOGGER.debug("Adding bean in '{}' : {}", ctx.getClass(), managedBean); Field toRedefine = ctx.getClass().getDeclaredField("$$ha$toReloadWeld"); Set toReload = Set.class.cast(toRedefine.get(ctx)); if (toReload == null) { toReload = new HashSet(); toRedefine.set(ctx, toReload); } toReload.add(managedBean); return true; } catch(Exception e) { LOGGER.warning("Context {} is not patched. Can not add {} to reload set", e, ctx, managedBean); } return false; } /** * Will remove bean from context forcing a clean new instance to be created (eg calling post-construct) * * @param ctx * @param managedBean */ public static void destroy(WeldHotswapContext ctx, Contextual<?> managedBean ) { try { LOGGER.debug("Removing Contextual from Context........ {},: {}", managedBean, ctx); Object get = ctx.get(managedBean); if (get != null) { ctx.destroy(managedBean); } get = ctx.get(managedBean); if (get != null) { LOGGER.error("Error removing ManagedBean {}, it still exists as instance {} ", managedBean, get); ctx.destroy(managedBean); } } catch (Exception e) { LOGGER.error("Error destoying bean {},: {}", e, managedBean, ctx); } } /** * Will re-inject any managed beans in the target. Will not call any other life-cycle methods * * @param ctx * @param managedBean */ public static void reinitialize(Context ctx, Contextual<Object> contextual) {<FILL_FUNCTION_BODY>} }
try { ManagedBean<Object> managedBean = ManagedBean.class.cast(contextual); LOGGER.debug("Re-Initializing........ {},: {}", managedBean, ctx); Object get = ctx.get(managedBean); if (get != null) { LOGGER.debug("Bean injection points are reinitialized '{}'", managedBean); managedBean.getProducer().inject(get, managedBean.getBeanManager().createCreationalContext(managedBean)); } } catch (Exception e) { LOGGER.error("Error reinitializing bean {},: {}", e, contextual, ctx); }
776
162
938
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-weld-jakarta-plugin/src/main/java/org/hotswap/agent/plugin/weld_jakarta/command/BdaAgentRegistry.java
BdaAgentRegistry
getArchiveByClassName
class BdaAgentRegistry { // map archive path -> BeanClassRefreshAgent private static Map<String, BeanClassRefreshAgent> INSTANCES = new ConcurrentHashMap<>(); public static Map<String, BeanClassRefreshAgent> getInstances() { return INSTANCES; } public static boolean contains(String archivePath) { return INSTANCES.containsKey(archivePath); } public static void put(String archivePath, BeanClassRefreshAgent bdaAgent) { INSTANCES.put(archivePath, bdaAgent); } public static BeanClassRefreshAgent get(String archivePath) { return INSTANCES.get(archivePath); } public static Collection<BeanClassRefreshAgent> values() { return INSTANCES.values(); } /** * Iterate over agents and find the one containing the class by name * * @param className * @return */ public static String getArchiveByClassName(String className){<FILL_FUNCTION_BODY>} }
for(BeanClassRefreshAgent agent: INSTANCES.values()) { if(agent.getDeploymentArchive().getBeanClasses().contains(className)) { return agent.getArchivePath(); } } return null;
288
65
353
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-weld-jakarta-plugin/src/main/java/org/hotswap/agent/plugin/weld_jakarta/command/ProxyClassLoadingDelegate.java
ProxyClassLoadingDelegate
toClassWeld3
class ProxyClassLoadingDelegate { private static final ThreadLocal<Boolean> MAGIC_IN_PROGRESS = new ThreadLocal<Boolean>() { @Override protected Boolean initialValue() { return false; } }; public static final void beginProxyRegeneration() { MAGIC_IN_PROGRESS.set(true); } public static final void endProxyRegeneration() { MAGIC_IN_PROGRESS.remove(); } public static Class<?> loadClass(final ClassLoader classLoader, final String className) throws ClassNotFoundException { if (MAGIC_IN_PROGRESS.get()) { throw new ClassNotFoundException("HotswapAgent"); } return classLoader.loadClass(className); } public static Class<?> toClassWeld2(ClassFile ct, ClassLoader loader, ProtectionDomain domain) throws ClassNotFoundException { if (MAGIC_IN_PROGRESS.get()) { try { final Class<?> originalProxyClass = loader.loadClass(ct.getName()); try { Map<Class<?>, byte[]> reloadMap = new HashMap<>(); reloadMap.put(originalProxyClass, ct.toBytecode()); // TODO : is this standard way how to reload class? PluginManager.getInstance().hotswap(reloadMap); return originalProxyClass; } catch (Exception e) { throw new RuntimeException(e); } } catch (ClassNotFoundException e) { } } Class<?> classFileUtilsClass = Class.forName("org.jboss.weld.util.bytecode.ClassFileUtils", true, loader); return (Class<?>) ReflectionHelper.invoke(null, classFileUtilsClass, "toClass", new Class[] { ClassFile.class, ClassLoader.class, ProtectionDomain.class }, ct, loader, domain); } public static Class<?> toClassWeld3(Object proxyFactory, ClassFile ct, Class<?> originalClass, ProxyServices proxyServices, ProtectionDomain domain) {<FILL_FUNCTION_BODY>} }
if (MAGIC_IN_PROGRESS.get()) { try { ClassLoader loader = originalClass.getClassLoader(); if (loader == null) { loader = Thread.currentThread().getContextClassLoader(); } final Class<?> originalProxyClass = loader.loadClass(ct.getName()); try { Map<Class<?>, byte[]> reloadMap = new HashMap<>(); reloadMap.put(originalProxyClass, ct.toBytecode()); // TODO : is this standard way how to reload class? PluginManager.getInstance().hotswap(reloadMap); return originalProxyClass; } catch (Exception e) { throw new RuntimeException(e); } } catch (ClassNotFoundException e) { } } return (Class<?>) ReflectionHelper.invoke(proxyFactory, proxyFactory.getClass(), "$$ha$toClass", new Class[] { ClassFile.class, Class.class, ProxyServices.class, ProtectionDomain.class }, ct, originalClass, proxyServices, domain);
545
272
817
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-weld-jakarta-plugin/src/main/java/org/hotswap/agent/plugin/weld_jakarta/transformer/AbstractClassBeanTransformer.java
AbstractClassBeanTransformer
transformAbstractClassBean
class AbstractClassBeanTransformer { private static AgentLogger LOGGER = AgentLogger.getLogger(AbstractClassBeanTransformer.class); /** * * @param ctClass * @param classPool * @throws NotFoundException * @throws CannotCompileException */ @OnClassLoadEvent(classNameRegexp = "org.jboss.weld.bean.AbstractClassBean") public static void transformAbstractClassBean(CtClass ctClass, ClassPool classPool) throws NotFoundException, CannotCompileException {<FILL_FUNCTION_BODY>} }
if (!HaCdiCommons.isJakarta(classPool)) { return; } CtMethod method = ctClass.getDeclaredMethod("cleanupAfterBoot"); method.setBody("{ }"); LOGGER.debug("AbstractClassBean.cleanupAfterBoot patched");
148
79
227
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-weld-jakarta-plugin/src/main/java/org/hotswap/agent/plugin/weld_jakarta/transformer/BeanDeploymentArchiveTransformer.java
BeanDeploymentArchiveTransformer
transformJbossBda
class BeanDeploymentArchiveTransformer { private static AgentLogger LOGGER = AgentLogger.getLogger(BeanDeploymentArchiveTransformer.class); /** * Basic WeldBeanDeploymentArchive transformation. * * @param classPool the class pool * @param clazz the clazz * @throws NotFoundException the not found exception * @throws CannotCompileException the cannot compile exception */ @OnClassLoadEvent(classNameRegexp = "org.jboss.weld.environment.deployment.WeldBeanDeploymentArchive") public static void transform(ClassPool classPool, CtClass clazz) throws NotFoundException, CannotCompileException { if (!HaCdiCommons.isJakarta(classPool)) { return; } StringBuilder src = new StringBuilder("{"); src.append(PluginManagerInvoker.buildInitializePlugin(WeldJakartaPlugin.class)); src.append(PluginManagerInvoker.buildCallPluginMethod(WeldJakartaPlugin.class, "init")); src.append("org.hotswap.agent.plugin.weld.command.BeanClassRefreshAgent.registerArchive(getClass().getClassLoader(), this, null);"); src.append("}"); for (CtConstructor constructor : clazz.getDeclaredConstructors()) { constructor.insertAfter(src.toString()); } LOGGER.debug("Class '{}' patched with BDA registration.", clazz.getName()); } /** * JbossAS (Wildfly) BeanDeploymentArchiveImpl transformation. * * @param clazz * @param classPool * @throws NotFoundException * @throws CannotCompileException */ @OnClassLoadEvent(classNameRegexp = "org.jboss.as.weld.deployment.BeanDeploymentArchiveImpl") public static void transformJbossBda(ClassPool classPool, CtClass clazz) throws NotFoundException, CannotCompileException {<FILL_FUNCTION_BODY>} /** * GlassFish BeanDeploymentArchiveImpl transformation. * * @param classPool the class pool * @param clazz the clazz * @throws NotFoundException the not found exception * @throws CannotCompileException the cannot compile exception */ @OnClassLoadEvent(classNameRegexp = "org.glassfish.weld.BeanDeploymentArchiveImpl") public static void transformGlassFishBda(ClassPool classPool, CtClass clazz) throws NotFoundException, CannotCompileException { if (!HaCdiCommons.isJakarta(classPool)) { return; } StringBuilder src = new StringBuilder("{"); src.append(PluginManagerInvoker.buildInitializePlugin(WeldJakartaPlugin.class, "this.moduleClassLoaderForBDA")); src.append(PluginManagerInvoker.buildCallPluginMethod("this.moduleClassLoaderForBDA", WeldJakartaPlugin.class, "initInGlassFish")); src.append(" Class agC = Class.forName(\"org.hotswap.agent.plugin.weld.command.BeanClassRefreshAgent\", true, this.moduleClassLoaderForBDA);"); src.append(" java.lang.reflect.Method agM = agC.getDeclaredMethod(\"registerArchive\", new Class[] {java.lang.ClassLoader.class, org.jboss.weld.bootstrap.spi.BeanDeploymentArchive.class, java.lang.String.class});"); src.append(" agM.invoke(null, new Object[] { this.moduleClassLoaderForBDA, this, null});"); src.append("}"); for (CtConstructor constructor : clazz.getDeclaredConstructors()) { constructor.insertAfter(src.toString()); } LOGGER.debug("Class 'org.jboss.as.weld.deployment.BeanDeploymentArchiveImpl' patched with BDA registration."); } }
if (!HaCdiCommons.isJakarta(classPool)) { return; } StringBuilder src = new StringBuilder("{"); src.append("if (beansXml!=null && beanArchiveType!=null && (\"EXPLICIT\".equals(beanArchiveType.toString()) || \"IMPLICIT\".equals(beanArchiveType.toString()))){"); src.append(PluginManagerInvoker.buildInitializePlugin(WeldJakartaPlugin.class, "module.getClassLoader()")); src.append(PluginManagerInvoker.buildCallPluginMethod("module.getClassLoader()", WeldJakartaPlugin.class, "initInJBossAS")); src.append(" Class agC = Class.forName(\"org.hotswap.agent.plugin.weld.command.BeanClassRefreshAgent\", true, module.getClassLoader());"); src.append(" java.lang.reflect.Method agM = agC.getDeclaredMethod(\"registerArchive\", new Class[] {java.lang.ClassLoader.class, org.jboss.weld.bootstrap.spi.BeanDeploymentArchive.class, java.lang.String.class});"); src.append(" agM.invoke(null, new Object[] { module.getClassLoader(),this, beanArchiveType.toString()});"); src.append("}}"); for (CtConstructor constructor : clazz.getDeclaredConstructors()) { constructor.insertAfter(src.toString()); } LOGGER.debug("Class 'org.jboss.as.weld.deployment.BeanDeploymentArchiveImpl' patched with BDA registration.");
1,011
412
1,423
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-weld-jakarta-plugin/src/main/java/org/hotswap/agent/plugin/weld_jakarta/transformer/CdiContextsTransformer.java
CdiContextsTransformer
transformReloadingWeldContexts
class CdiContextsTransformer { private static AgentLogger LOGGER = AgentLogger.getLogger(CdiContextsTransformer.class); public static final String BOUND_SESSION_BEAN_STORE_REGISTRY = "$$ha$boundSessionBeanStoreRegistry"; /** * Add context reloading functionality to base contexts classes. * * @param classPool the class pool * @param ctClass the class * @throws NotFoundException the not found exception * @throws CannotCompileException the cannot compile exception */ @OnClassLoadEvent(classNameRegexp = "(org.jboss.weld.context.AbstractManagedContext)|" + "(org.jboss.weld.context.AbstractSharedContext)|" + "(org.jboss.weld.context.unbound.DependentContextImpl)|" + "(org.jboss.weld.util.ForwardingContext)|" + "(org.apache.myfaces.flow.cdi.FlowScopedContextImpl)|" + "(org.apache.myfaces.cdi.view.ViewScopeContextImpl)" ) public static void transformReloadingWeldContexts(ClassPool classPool, CtClass ctClass) throws NotFoundException, CannotCompileException {<FILL_FUNCTION_BODY>} /** * Add custom tracker field to session context * * @param classPool the class pool * @param ctClass the class * @throws NotFoundException the not found exception * @throws CannotCompileException the cannot compile exception */ @OnClassLoadEvent(classNameRegexp = "org.jboss.weld.context.AbstractContext") public static void transformHttpSessionContext(ClassPool classPool, CtClass ctClass) throws NotFoundException, CannotCompileException { if (!HaCdiCommons.isJakarta(classPool)) { return; } HaCdiCommons.transformContext(classPool, ctClass); } }
if (!HaCdiCommons.isJakarta(classPool)) { return; } LOGGER.debug("Adding interface {} to {}.", WeldHotswapContext.class.getName(), ctClass.getName()); ctClass.addInterface(classPool.get(WeldHotswapContext.class.getName())); CtField toReloadFld = CtField.make("public transient java.util.Set $$ha$toReloadWeld = null;", ctClass); ctClass.addField(toReloadFld); CtField reloadingFld = CtField.make("public transient boolean $$ha$reloadingWeld = false;", ctClass); ctClass.addField(reloadingFld); CtMethod addBeanToReload = CtMethod.make( "public void $$ha$addBeanToReloadWeld(jakarta.enterprise.context.spi.Contextual bean) {" + "if ($$ha$toReloadWeld == null)" + "$$ha$toReloadWeld = new java.util.HashSet();" + "$$ha$toReloadWeld.add(bean);" + "}", ctClass ); ctClass.addMethod(addBeanToReload); CtMethod getBeansToReload = CtMethod.make("public java.util.Set $$ha$getBeansToReloadWeld(){return $$ha$toReloadWeld;}", ctClass); ctClass.addMethod(getBeansToReload); CtMethod reload = CtMethod.make("public void $$ha$reloadWeld() {" + ContextualReloadHelper.class.getName() +".reload(this);}", ctClass); ctClass.addMethod(reload); CtMethod isActive = ctClass.getDeclaredMethod("isActive"); isActive.insertAfter( "{" + "if($_ && !$$ha$reloadingWeld ) { " + "$$ha$reloadingWeld = true;" + "$$ha$reloadWeld();" + "$$ha$reloadingWeld = false;" + "}" + "return $_;" + "}" ); LOGGER.debug("Class '{}' patched with hot-swapping support", ctClass.getName() );
514
604
1,118
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-weld-jakarta-plugin/src/main/java/org/hotswap/agent/plugin/weld_jakarta/transformer/ProxyFactoryTransformer.java
ProxyFactoryTransformer
edit
class ProxyFactoryTransformer { private static AgentLogger LOGGER = AgentLogger.getLogger(ProxyFactoryTransformer.class); /** * Patch ProxyFactory class. * - add factory registration into constructor * - changes call classLoader.loadClass(...) in getProxyClass() to ProxyClassLoadingDelegate.loadClass(classLoader, ...) * - changes call ClassFileUtils.toClass() in createProxyClass() to ProxyClassLoadingDelegate.loadClass(...) * * @param classPool the class pool * @param ctClass the ProxyFactory class * @throws NotFoundException the not found exception * @throws CannotCompileException the cannot compile exception */ @OnClassLoadEvent(classNameRegexp = "org.jboss.weld.bean.proxy.ProxyFactory") public static void patchProxyFactory(ClassPool classPool, CtClass ctClass) throws NotFoundException, CannotCompileException { if (!HaCdiCommons.isJakarta(classPool)) { return; } CtClass[] constructorParams = new CtClass[] { classPool.get("java.lang.String"), classPool.get("java.lang.Class"), classPool.get("java.util.Set"), //classPool.get("java.lang.String"), classPool.get("jakarta.enterprise.inject.spi.Bean"), classPool.get("boolean") }; CtConstructor declaredConstructor = ctClass.getDeclaredConstructor(constructorParams); // TODO : we should find constructor without this() call and put registration only into this one declaredConstructor.insertAfter("{" + "java.lang.Class originalClass = (this.bean != null) ? this.bean.getBeanClass() : this.proxiedBeanType;" + "java.lang.ClassLoader loader = originalClass.getClassLoader();" + "if (loader==null) {"+ "loader = Thread.currentThread().getContextClassLoader();" + "}" + "if (" + PluginManager.class.getName() + ".getInstance().isPluginInitialized(\"" + WeldJakartaPlugin.class.getName() + "\", loader)) {" + PluginManagerInvoker.buildCallPluginMethod("loader", WeldJakartaPlugin.class, "registerProxyFactory", "this", "java.lang.Object", "bean", "java.lang.Object", "loader", "java.lang.ClassLoader", "proxiedBeanType", "java.lang.Class" ) + "}" + "}"); try { // Weld 3 CtMethod oldMethod = ctClass.getDeclaredMethod("toClass"); oldMethod.setName("$$ha$toClass"); // TODO: use another convention for renamed? oldMethod.setModifiers(Modifier.PUBLIC); CtMethod newMethod = CtNewMethod.make( "protected java.lang.Class toClass(org.jboss.classfilewriter.ClassFile ct, java.lang.Class originalClass, " + "org.jboss.weld.serialization.spi.ProxyServices proxyServices, java.security.ProtectionDomain domain) {" + "return org.hotswap.agent.plugin.weld.command.ProxyClassLoadingDelegate.toClassWeld3(this, ct, originalClass, proxyServices, domain);" + "}", ctClass); ctClass.addMethod(newMethod); } catch (NotFoundException e) { // Weld 2 CtMethod getProxyClassMethod = ctClass.getDeclaredMethod("getProxyClass"); getProxyClassMethod.instrument( new ExprEditor() { public void edit(MethodCall m) throws CannotCompileException { if (m.getClassName().equals(ClassLoader.class.getName()) && m.getMethodName().equals("loadClass")) m.replace("{ $_ = org.hotswap.agent.plugin.weld.command.ProxyClassLoadingDelegate.loadClass(this.classLoader,$1); }"); } }); CtMethod createProxyClassMethod = ctClass.getDeclaredMethod("createProxyClass"); createProxyClassMethod.instrument( new ExprEditor() { public void edit(MethodCall m) throws CannotCompileException {<FILL_FUNCTION_BODY>} } ); } } }
// Patch Weld2 if (m.getClassName().equals("org.jboss.weld.util.bytecode.ClassFileUtils") && m.getMethodName().equals("toClass")) try { if (m.getMethod().getParameterTypes().length == 3) { m.replace("{ $_ = org.hotswap.agent.plugin.weld.command.ProxyClassLoadingDelegate.toClassWeld2($$); }"); } else if (m.getMethod().getParameterTypes().length == 4) { LOGGER.debug("Proxy factory patch for delegating method skipped.", m.getClassName(), m.getMethodName()); } else { LOGGER.error("Method '{}.{}' patch failed. Unknown method arguments.", m.getClassName(), m.getMethodName()); } } catch (NotFoundException e) { LOGGER.error("Method '{}' not found in '{}'.", m.getMethodName(), m.getClassName()); }
1,111
247
1,358
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-weld-plugin/src/main/java/org/hotswap/agent/plugin/weld/ArchivePathHelper.java
ArchivePathHelper
getNormalizedArchivePath
class ArchivePathHelper { private static AgentLogger LOGGER = AgentLogger.getLogger(ArchivePathHelper.class); public static String getNormalizedArchivePath(CtClass ctClass) throws NotFoundException { String classFilePath = ctClass.getURL().getFile(); String className = ctClass.getName().replace(".", "/"); // archive path ends with '/' therefore we set end position before the '/' (-1) return classFilePath.substring(0, classFilePath.indexOf(className) - 1); } /** * Method resolves archive path from BdaId * * @param classLoader the class loader * @param archiveId the archive id * @return the normalized archive path */ public static String getNormalizedArchivePath(ClassLoader classLoader, String archiveId) {<FILL_FUNCTION_BODY>} private static URL archivePathToURL(ClassLoader classLoader, String archiveId) { URL result = archiveFilePathToURL(archiveId); if (result == null) { // File doesn't exists, try to resolve it using appClassLoader if (classLoader instanceof URLClassLoader) { result = archivePathToURLViaURLClassLoader((URLClassLoader) classLoader, archiveId); } } return result; } private static URL archivePathToURLViaURLClassLoader(URLClassLoader urlClassLoader, String archivePath) { URL[] urls = urlClassLoader.getURLs(); if (urls != null) { for (URL url: urls) { String fileName = url.getFile(); String checkedArchivePath = (fileName.endsWith("/") && !archivePath.endsWith("/")) ? (archivePath + "/") : archivePath; if (fileName.endsWith(checkedArchivePath)) { return archiveFilePathToURL(fileName); } } } return null; } private static URL archiveFilePathToURL(String archivePath) { File f = new File(archivePath); if (f.exists()) { try { try { // Try to format as a URL? return f.toURI().toURL(); } catch (MalformedURLException e) { // try to locate a file if (archivePath.startsWith("./")) archivePath = archivePath.substring(2); File file = new File(archivePath).getCanonicalFile(); return file.toURI().toURL(); } } catch (Exception e) { // Swallow exception } } return null; } }
URL archiveURL = archivePathToURL(classLoader, archiveId); if (archiveURL != null) { try { String result = archiveURL.getFile(); // Strip trailing "/" from normalized archive path while (result.endsWith("/")) { result = result.substring(0, result.length() -1); } return result; } catch (Exception e) { LOGGER.error("getNormalizedArchivePath() exception {}.", e.getMessage()); } } return null;
663
137
800
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-weld-plugin/src/main/java/org/hotswap/agent/plugin/weld/WeldClassSignatureHelper.java
WeldClassSignatureHelper
getSignatureByStrategy
class WeldClassSignatureHelper { private static AgentLogger LOGGER = AgentLogger.getLogger(WeldClassSignatureHelper.class); private static final ClassSignatureElement[] SIGNATURE_ELEM_PROXY = { ClassSignatureElement.SUPER_CLASS, ClassSignatureElement.INTERFACES, ClassSignatureElement.CLASS_ANNOTATION, ClassSignatureElement.CONSTRUCTOR, ClassSignatureElement.METHOD, ClassSignatureElement.METHOD_ANNOTATION, ClassSignatureElement.METHOD_PARAM_ANNOTATION, ClassSignatureElement.METHOD_EXCEPTION, ClassSignatureElement.FIELD, ClassSignatureElement.FIELD_ANNOTATION }; private static final ClassSignatureElement[] SIGNATURE_ELEM_METHOD_FIELDS = { ClassSignatureElement.SUPER_CLASS, ClassSignatureElement.INTERFACES, ClassSignatureElement.CLASS_ANNOTATION, ClassSignatureElement.CONSTRUCTOR, ClassSignatureElement.CONSTRUCTOR_PRIVATE, // private constructors are used if CONSTRUCTOR && CONSTRUCTOR_PRIVATE are set ClassSignatureElement.METHOD, ClassSignatureElement.METHOD_PRIVATE, // private methods are used if METHOD && METHOD_PRIVATE are set ClassSignatureElement.METHOD_ANNOTATION, // applies to constructors as well ClassSignatureElement.METHOD_PARAM_ANNOTATION, // applies to constructors as well ClassSignatureElement.FIELD, ClassSignatureElement.FIELD_ANNOTATION }; private static final ClassSignatureElement[] SIGNATURE_ELEM_FIELDS = { ClassSignatureElement.FIELD, ClassSignatureElement.FIELD_ANNOTATION }; /** * Gets the class signature for proxy class comparison * * @param clazz the clazz for which signature is calculated * @return the java class signature */ public static String getSignatureForProxyClass(Class<?> clazz) { try { return ClassSignatureComparerHelper.getJavaClassSignature(clazz, SIGNATURE_ELEM_PROXY); } catch (Exception e) { LOGGER.error("getSignatureForProxyClass(): Error reading signature", e); return null; } } /** * Gets the signature by strategy. * * @param strategy the strategy * @param clazz the clazz * @return the signature by strategy */ public static String getSignatureByStrategy(BeanReloadStrategy strategy, Class<?> clazz) {<FILL_FUNCTION_BODY>} private static String getClassMethodFieldsSignature(Class<?> clazz) { try { return ClassSignatureComparerHelper.getJavaClassSignature(clazz, SIGNATURE_ELEM_METHOD_FIELDS); } catch (Exception e) { LOGGER.error("getSignatureForProxyClass(): Error reading signature", e); return null; } } private static String getClassFieldsSignature(Class<?> clazz) { try { return ClassSignatureComparerHelper.getJavaClassSignature(clazz, SIGNATURE_ELEM_FIELDS); } catch (Exception e) { LOGGER.error("getSignatureForProxyClass(): Error reading signature", e); return null; } } }
if (strategy == null) { strategy = BeanReloadStrategy.NEVER; } switch (strategy) { case CLASS_CHANGE : return null; case METHOD_FIELD_SIGNATURE_CHANGE : return getClassMethodFieldsSignature(clazz); case FIELD_SIGNATURE_CHANGE : return getClassFieldsSignature(clazz); default: case NEVER: return null; }
829
119
948
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-weld-plugin/src/main/java/org/hotswap/agent/plugin/weld/beans/ContextualReloadHelper.java
ContextualReloadHelper
addToReloadSet
class ContextualReloadHelper { private static AgentLogger LOGGER = AgentLogger.getLogger(ContextualReloadHelper.class); public static void reload(WeldHotswapContext ctx) { Set<Contextual<Object>> beans = ctx.$$ha$getBeansToReloadWeld(); if (beans != null && !beans.isEmpty()) { LOGGER.debug("Starting re-loading Contextuals in {}, {}", ctx, beans.size()); Iterator<Contextual<Object>> it = beans.iterator(); while (it.hasNext()) { Contextual<Object> managedBean = it.next(); destroy(ctx, managedBean); } beans.clear(); LOGGER.debug("Finished re-loading Contextuals in {}", ctx); } } /** * Tries to add the bean in the context so it is reloaded in the next activation of the context. * * @param ctx * @param managedBean * @return */ public static boolean addToReloadSet(Context ctx, Contextual<Object> managedBean) {<FILL_FUNCTION_BODY>} /** * Will remove bean from context forcing a clean new instance to be created (eg calling post-construct) * * @param ctx * @param managedBean */ public static void destroy(WeldHotswapContext ctx, Contextual<?> managedBean ) { try { LOGGER.debug("Removing Contextual from Context........ {},: {}", managedBean, ctx); Object get = ctx.get(managedBean); if (get != null) { ctx.destroy(managedBean); } get = ctx.get(managedBean); if (get != null) { LOGGER.error("Error removing ManagedBean {}, it still exists as instance {} ", managedBean, get); ctx.destroy(managedBean); } } catch (Exception e) { LOGGER.error("Error destoying bean {},: {}", e, managedBean, ctx); } } /** * Will re-inject any managed beans in the target. Will not call any other life-cycle methods * * @param ctx * @param managedBean */ public static void reinitialize(Context ctx, Contextual<Object> contextual) { try { ManagedBean<Object> managedBean = ManagedBean.class.cast(contextual); LOGGER.debug("Re-Initializing........ {},: {}", managedBean, ctx); Object get = ctx.get(managedBean); if (get != null) { LOGGER.debug("Bean injection points are reinitialized '{}'", managedBean); managedBean.getProducer().inject(get, managedBean.getBeanManager().createCreationalContext(managedBean)); } } catch (Exception e) { LOGGER.error("Error reinitializing bean {},: {}", e, contextual, ctx); } } }
try { LOGGER.debug("Adding bean in '{}' : {}", ctx.getClass(), managedBean); Field toRedefine = ctx.getClass().getDeclaredField("$$ha$toReloadWeld"); Set toReload = Set.class.cast(toRedefine.get(ctx)); if (toReload == null) { toReload = new HashSet(); toRedefine.set(ctx, toReload); } toReload.add(managedBean); return true; } catch(Exception e) { LOGGER.warning("Context {} is not patched. Can not add {} to reload set", e, ctx, managedBean); } return false;
754
184
938
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-weld-plugin/src/main/java/org/hotswap/agent/plugin/weld/command/BdaAgentRegistry.java
BdaAgentRegistry
getArchiveByClassName
class BdaAgentRegistry { // map archive path -> BeanClassRefreshAgent private static Map<String, BeanClassRefreshAgent> INSTANCES = new ConcurrentHashMap<>(); public static Map<String, BeanClassRefreshAgent> getInstances() { return INSTANCES; } public static boolean contains(String archivePath) { return INSTANCES.containsKey(archivePath); } public static void put(String archivePath, BeanClassRefreshAgent bdaAgent) { INSTANCES.put(archivePath, bdaAgent); } public static BeanClassRefreshAgent get(String archivePath) { return INSTANCES.get(archivePath); } public static Collection<BeanClassRefreshAgent> values() { return INSTANCES.values(); } /** * Iterate over agents and find the one containing the class by name * * @param className * @return */ public static String getArchiveByClassName(String className){<FILL_FUNCTION_BODY>} }
for(BeanClassRefreshAgent agent: INSTANCES.values()) { if(agent.getDeploymentArchive().getBeanClasses().contains(className)) { return agent.getArchivePath(); } } return null;
288
65
353
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-weld-plugin/src/main/java/org/hotswap/agent/plugin/weld/command/ProxyClassLoadingDelegate.java
ProxyClassLoadingDelegate
toClassWeld2
class ProxyClassLoadingDelegate { private static final ThreadLocal<Boolean> MAGIC_IN_PROGRESS = new ThreadLocal<Boolean>() { @Override protected Boolean initialValue() { return false; } }; public static final void beginProxyRegeneration() { MAGIC_IN_PROGRESS.set(true); } public static final void endProxyRegeneration() { MAGIC_IN_PROGRESS.remove(); } public static Class<?> loadClass(final ClassLoader classLoader, final String className) throws ClassNotFoundException { if (MAGIC_IN_PROGRESS.get()) { throw new ClassNotFoundException("HotswapAgent"); } return classLoader.loadClass(className); } public static Class<?> toClassWeld2(ClassFile ct, ClassLoader loader, ProtectionDomain domain) throws ClassNotFoundException {<FILL_FUNCTION_BODY>} public static Class<?> toClassWeld3(Object proxyFactory, ClassFile ct, Class<?> originalClass, ProxyServices proxyServices, ProtectionDomain domain) { if (MAGIC_IN_PROGRESS.get()) { try { ClassLoader loader = originalClass.getClassLoader(); if (loader == null) { loader = Thread.currentThread().getContextClassLoader(); } final Class<?> originalProxyClass = loader.loadClass(ct.getName()); try { Map<Class<?>, byte[]> reloadMap = new HashMap<>(); reloadMap.put(originalProxyClass, ct.toBytecode()); // TODO : is this standard way how to reload class? PluginManager.getInstance().hotswap(reloadMap); return originalProxyClass; } catch (Exception e) { throw new RuntimeException(e); } } catch (ClassNotFoundException e) { } } return (Class<?>) ReflectionHelper.invoke(proxyFactory, proxyFactory.getClass(), "$$ha$toClass", new Class[] { ClassFile.class, Class.class, ProxyServices.class, ProtectionDomain.class }, ct, originalClass, proxyServices, domain); } }
if (MAGIC_IN_PROGRESS.get()) { try { final Class<?> originalProxyClass = loader.loadClass(ct.getName()); try { Map<Class<?>, byte[]> reloadMap = new HashMap<>(); reloadMap.put(originalProxyClass, ct.toBytecode()); // TODO : is this standard way how to reload class? PluginManager.getInstance().hotswap(reloadMap); return originalProxyClass; } catch (Exception e) { throw new RuntimeException(e); } } catch (ClassNotFoundException e) { } } Class<?> classFileUtilsClass = Class.forName("org.jboss.weld.util.bytecode.ClassFileUtils", true, loader); return (Class<?>) ReflectionHelper.invoke(null, classFileUtilsClass, "toClass", new Class[] { ClassFile.class, ClassLoader.class, ProtectionDomain.class }, ct, loader, domain);
561
256
817
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-weld-plugin/src/main/java/org/hotswap/agent/plugin/weld/transformer/AbstractClassBeanTransformer.java
AbstractClassBeanTransformer
transformAbstractClassBean
class AbstractClassBeanTransformer { private static AgentLogger LOGGER = AgentLogger.getLogger(AbstractClassBeanTransformer.class); /** * * @param ctClass * @param classPool * @throws NotFoundException * @throws CannotCompileException */ @OnClassLoadEvent(classNameRegexp = "org.jboss.weld.bean.AbstractClassBean") public static void transformAbstractClassBean(CtClass ctClass, ClassPool classPool) throws NotFoundException, CannotCompileException {<FILL_FUNCTION_BODY>} }
if (HaCdiCommons.isJakarta(classPool)) { return; } CtMethod method = ctClass.getDeclaredMethod("cleanupAfterBoot"); method.setBody("{ }"); LOGGER.debug("AbstractClassBean.cleanupAfterBoot patched");
148
79
227
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-weld-plugin/src/main/java/org/hotswap/agent/plugin/weld/transformer/BeanDeploymentArchiveTransformer.java
BeanDeploymentArchiveTransformer
transform
class BeanDeploymentArchiveTransformer { private static AgentLogger LOGGER = AgentLogger.getLogger(BeanDeploymentArchiveTransformer.class); /** * Basic WeldBeanDeploymentArchive transformation. * * @param classPool the class pool * @param clazz the clazz * @throws NotFoundException the not found exception * @throws CannotCompileException the cannot compile exception */ @OnClassLoadEvent(classNameRegexp = "org.jboss.weld.environment.deployment.WeldBeanDeploymentArchive") public static void transform(ClassPool classPool, CtClass clazz) throws NotFoundException, CannotCompileException {<FILL_FUNCTION_BODY>} /** * JbossAS (Wildfly) BeanDeploymentArchiveImpl transformation. * * @param clazz * @param classPool * @throws NotFoundException * @throws CannotCompileException */ @OnClassLoadEvent(classNameRegexp = "org.jboss.as.weld.deployment.BeanDeploymentArchiveImpl") public static void transformJbossBda(ClassPool classPool, CtClass clazz) throws NotFoundException, CannotCompileException { if (HaCdiCommons.isJakarta(classPool)) { return; } StringBuilder src = new StringBuilder("{"); src.append("if (beansXml!=null && beanArchiveType!=null && (\"EXPLICIT\".equals(beanArchiveType.toString()) || \"IMPLICIT\".equals(beanArchiveType.toString()))){"); src.append(PluginManagerInvoker.buildInitializePlugin(WeldPlugin.class, "module.getClassLoader()")); src.append(PluginManagerInvoker.buildCallPluginMethod("module.getClassLoader()", WeldPlugin.class, "initInJBossAS")); src.append(" Class agC = Class.forName(\"org.hotswap.agent.plugin.weld.command.BeanClassRefreshAgent\", true, module.getClassLoader());"); src.append(" java.lang.reflect.Method agM = agC.getDeclaredMethod(\"registerArchive\", new Class[] {java.lang.ClassLoader.class, org.jboss.weld.bootstrap.spi.BeanDeploymentArchive.class, java.lang.String.class});"); src.append(" agM.invoke(null, new Object[] { module.getClassLoader(),this, beanArchiveType.toString()});"); src.append("}}"); for (CtConstructor constructor : clazz.getDeclaredConstructors()) { constructor.insertAfter(src.toString()); } LOGGER.debug("Class 'org.jboss.as.weld.deployment.BeanDeploymentArchiveImpl' patched with BDA registration."); } /** * GlassFish BeanDeploymentArchiveImpl transformation. * * @param classPool the class pool * @param clazz the clazz * @throws NotFoundException the not found exception * @throws CannotCompileException the cannot compile exception */ @OnClassLoadEvent(classNameRegexp = "org.glassfish.weld.BeanDeploymentArchiveImpl") public static void transformGlassFishBda(ClassPool classPool, CtClass clazz) throws NotFoundException, CannotCompileException { if (HaCdiCommons.isJakarta(classPool)) { return; } StringBuilder src = new StringBuilder("{"); src.append(PluginManagerInvoker.buildInitializePlugin(WeldPlugin.class, "this.moduleClassLoaderForBDA")); src.append(PluginManagerInvoker.buildCallPluginMethod("this.moduleClassLoaderForBDA", WeldPlugin.class, "initInGlassFish")); src.append(" Class agC = Class.forName(\"org.hotswap.agent.plugin.weld.command.BeanClassRefreshAgent\", true, this.moduleClassLoaderForBDA);"); src.append(" java.lang.reflect.Method agM = agC.getDeclaredMethod(\"registerArchive\", new Class[] {java.lang.ClassLoader.class, org.jboss.weld.bootstrap.spi.BeanDeploymentArchive.class, java.lang.String.class});"); src.append(" agM.invoke(null, new Object[] { this.moduleClassLoaderForBDA, this, null});"); src.append("}"); for (CtConstructor constructor : clazz.getDeclaredConstructors()) { constructor.insertAfter(src.toString()); } LOGGER.debug("Class 'org.jboss.as.weld.deployment.BeanDeploymentArchiveImpl' patched with BDA registration."); } }
if (HaCdiCommons.isJakarta(classPool)) { return; } StringBuilder src = new StringBuilder("{"); src.append(PluginManagerInvoker.buildInitializePlugin(WeldPlugin.class)); src.append(PluginManagerInvoker.buildCallPluginMethod(WeldPlugin.class, "init")); src.append("org.hotswap.agent.plugin.weld.command.BeanClassRefreshAgent.registerArchive(getClass().getClassLoader(), this, null);"); src.append("}"); for (CtConstructor constructor : clazz.getDeclaredConstructors()) { constructor.insertAfter(src.toString()); } LOGGER.debug("Class '{}' patched with BDA registration.", clazz.getName());
1,200
199
1,399
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-weld-plugin/src/main/java/org/hotswap/agent/plugin/weld/transformer/CdiContextsTransformer.java
CdiContextsTransformer
transformReloadingWeldContexts
class CdiContextsTransformer { private static AgentLogger LOGGER = AgentLogger.getLogger(CdiContextsTransformer.class); public static final String BOUND_SESSION_BEAN_STORE_REGISTRY = "$$ha$boundSessionBeanStoreRegistry"; /** * Add context reloading functionality to base contexts classes. * * @param classPool the class pool * @param ctClass the class * @throws NotFoundException the not found exception * @throws CannotCompileException the cannot compile exception */ @OnClassLoadEvent(classNameRegexp = "(org.jboss.weld.context.AbstractManagedContext)|" + "(org.jboss.weld.context.AbstractSharedContext)|" + "(org.jboss.weld.context.unbound.DependentContextImpl)|" + "(org.jboss.weld.util.ForwardingContext)|" + "(org.apache.myfaces.flow.cdi.FlowScopedContextImpl)|" + "(org.apache.myfaces.cdi.view.ViewScopeContextImpl)" ) public static void transformReloadingWeldContexts(ClassPool classPool, CtClass ctClass) throws NotFoundException, CannotCompileException {<FILL_FUNCTION_BODY>} /** * Add custom tracker field to session context * * @param classPool the class pool * @param ctClass the class * @throws NotFoundException the not found exception * @throws CannotCompileException the cannot compile exception */ @OnClassLoadEvent(classNameRegexp = "org.jboss.weld.context.AbstractContext") public static void transformHttpSessionContext(ClassPool classPool, CtClass ctClass) throws NotFoundException, CannotCompileException { if (HaCdiCommons.isJakarta(classPool)) { return; } HaCdiCommons.transformContext(classPool, ctClass); } }
if (HaCdiCommons.isJakarta(classPool)) { return; } LOGGER.debug("Adding interface {} to {}.", WeldHotswapContext.class.getName(), ctClass.getName()); ctClass.addInterface(classPool.get(WeldHotswapContext.class.getName())); CtField toReloadFld = CtField.make("public transient java.util.Set $$ha$toReloadWeld = null;", ctClass); ctClass.addField(toReloadFld); CtField reloadingFld = CtField.make("public transient boolean $$ha$reloadingWeld = false;", ctClass); ctClass.addField(reloadingFld); CtMethod addBeanToReload = CtMethod.make( "public void $$ha$addBeanToReloadWeld(javax.enterprise.context.spi.Contextual bean) {" + "if ($$ha$toReloadWeld == null)" + "$$ha$toReloadWeld = new java.util.HashSet();" + "$$ha$toReloadWeld.add(bean);" + "}", ctClass ); ctClass.addMethod(addBeanToReload); CtMethod getBeansToReload = CtMethod.make("public java.util.Set $$ha$getBeansToReloadWeld(){return $$ha$toReloadWeld;}", ctClass); ctClass.addMethod(getBeansToReload); CtMethod reload = CtMethod.make("public void $$ha$reloadWeld() {" + ContextualReloadHelper.class.getName() +".reload(this);}", ctClass); ctClass.addMethod(reload); CtMethod isActive = ctClass.getDeclaredMethod("isActive"); isActive.insertAfter( "{" + "if($_ && !$$ha$reloadingWeld ) { " + "$$ha$reloadingWeld = true;" + "$$ha$reloadWeld();" + "$$ha$reloadingWeld = false;" + "}" + "return $_;" + "}" ); LOGGER.debug("Class '{}' patched with hot-swapping support", ctClass.getName() );
514
602
1,116
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-weld-plugin/src/main/java/org/hotswap/agent/plugin/weld/transformer/ProxyFactoryTransformer.java
ProxyFactoryTransformer
patchProxyFactory
class ProxyFactoryTransformer { private static AgentLogger LOGGER = AgentLogger.getLogger(ProxyFactoryTransformer.class); /** * Patch ProxyFactory class. * - add factory registration into constructor * - changes call classLoader.loadClass(...) in getProxyClass() to ProxyClassLoadingDelegate.loadClass(classLoader, ...) * - changes call ClassFileUtils.toClass() in createProxyClass() to ProxyClassLoadingDelegate.loadClass(...) * * @param classPool the class pool * @param ctClass the ProxyFactory class * @throws NotFoundException the not found exception * @throws CannotCompileException the cannot compile exception */ @OnClassLoadEvent(classNameRegexp = "org.jboss.weld.bean.proxy.ProxyFactory") public static void patchProxyFactory(ClassPool classPool, CtClass ctClass) throws NotFoundException, CannotCompileException {<FILL_FUNCTION_BODY>} }
if (HaCdiCommons.isJakarta(classPool)) { return; } CtClass[] constructorParams = new CtClass[] { classPool.get("java.lang.String"), classPool.get("java.lang.Class"), classPool.get("java.util.Set"), //classPool.get("java.lang.String"), classPool.get("javax.enterprise.inject.spi.Bean"), classPool.get("boolean") }; CtConstructor declaredConstructor = ctClass.getDeclaredConstructor(constructorParams); // TODO : we should find constructor without this() call and put registration only into this one declaredConstructor.insertAfter("{" + "java.lang.Class originalClass = (this.bean != null) ? this.bean.getBeanClass() : this.proxiedBeanType;" + "java.lang.ClassLoader loader = originalClass.getClassLoader();" + "if (loader==null) {"+ "loader = Thread.currentThread().getContextClassLoader();" + "}" + "if (" + PluginManager.class.getName() + ".getInstance().isPluginInitialized(\"" + WeldPlugin.class.getName() + "\", loader)) {" + PluginManagerInvoker.buildCallPluginMethod("loader", WeldPlugin.class, "registerProxyFactory", "this", "java.lang.Object", "bean", "java.lang.Object", "loader", "java.lang.ClassLoader", "proxiedBeanType", "java.lang.Class" ) + "}" + "}"); try { // Weld 3 CtMethod oldMethod = ctClass.getDeclaredMethod("toClass"); oldMethod.setName("$$ha$toClass"); // TODO: use another convention for renamed? oldMethod.setModifiers(Modifier.PUBLIC); CtMethod newMethod = CtNewMethod.make( "protected java.lang.Class toClass(org.jboss.classfilewriter.ClassFile ct, java.lang.Class originalClass, " + "org.jboss.weld.serialization.spi.ProxyServices proxyServices, java.security.ProtectionDomain domain) {" + "return org.hotswap.agent.plugin.weld.command.ProxyClassLoadingDelegate.toClassWeld3(this, ct, originalClass, proxyServices, domain);" + "}", ctClass); ctClass.addMethod(newMethod); } catch (NotFoundException e) { // Weld 2 CtMethod getProxyClassMethod = ctClass.getDeclaredMethod("getProxyClass"); getProxyClassMethod.instrument( new ExprEditor() { public void edit(MethodCall m) throws CannotCompileException { if (m.getClassName().equals(ClassLoader.class.getName()) && m.getMethodName().equals("loadClass")) m.replace("{ $_ = org.hotswap.agent.plugin.weld.command.ProxyClassLoadingDelegate.loadClass(this.classLoader,$1); }"); } }); CtMethod createProxyClassMethod = ctClass.getDeclaredMethod("createProxyClass"); createProxyClassMethod.instrument( new ExprEditor() { public void edit(MethodCall m) throws CannotCompileException { // Patch Weld2 if (m.getClassName().equals("org.jboss.weld.util.bytecode.ClassFileUtils") && m.getMethodName().equals("toClass")) try { if (m.getMethod().getParameterTypes().length == 3) { m.replace("{ $_ = org.hotswap.agent.plugin.weld.command.ProxyClassLoadingDelegate.toClassWeld2($$); }"); } else if (m.getMethod().getParameterTypes().length == 4) { LOGGER.debug("Proxy factory patch for delegating method skipped.", m.getClassName(), m.getMethodName()); } else { LOGGER.error("Method '{}.{}' patch failed. Unknown method arguments.", m.getClassName(), m.getMethodName()); } } catch (NotFoundException e) { LOGGER.error("Method '{}' not found in '{}'.", m.getMethodName(), m.getClassName()); } } } ); }
247
1,101
1,348
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-wicket-plugin/src/main/java/org/hotswap/agent/plugin/wicket/WicketPlugin.java
WicketPlugin
clearCache
class WicketPlugin { private static final String WICKET_APPLICATION = "org.apache.wicket.protocol.http.WebApplication"; private static final AgentLogger LOGGER = AgentLogger.getLogger(WicketPlugin.class); @Init Scheduler scheduler; @Init ClassLoader appClassLoader; private Object wicketApplication; @OnClassLoadEvent(classNameRegexp = WICKET_APPLICATION) public static void init(CtClass ctClass) throws NotFoundException, CannotCompileException { String src = PluginManagerInvoker .buildInitializePlugin(WicketPlugin.class); src += PluginManagerInvoker.buildCallPluginMethod(WicketPlugin.class, "registerApplication", "this", "java.lang.Object"); ctClass.getDeclaredConstructor(new CtClass[0]).insertAfter(src); LOGGER.info("Wicket application has been enhanced."); } public void registerApplication(Object wicketApplication) { this.wicketApplication = wicketApplication; LOGGER.info("Plugin {} initialized for application {}", getClass(), wicketApplication); } @OnResourceFileEvent(path = "/", filter = ".*.properties") public void clearLocalizerCaches() { scheduler.scheduleCommand(this::clearCache); } private void clearCache() {<FILL_FUNCTION_BODY>} private Object getLocalizer() { try { final Method getResourceSettingsMethod = resolveClass("org.apache.wicket.Application") .getDeclaredMethod("getResourceSettings"); final Method getLocalizerMethod = resolveClass("org.apache.wicket.settings.ResourceSettings") .getDeclaredMethod("getLocalizer"); final Object resourceSettings = getResourceSettingsMethod.invoke(wicketApplication); return getLocalizerMethod.invoke(resourceSettings); } catch (Exception e) { LOGGER.error("Error getting Wicket localizer", e); return null; } } private Class<?> resolveClass(String name) throws ClassNotFoundException { return Class.forName(name, true, appClassLoader); } }
LOGGER.debug("Refreshing Wicket localizer cache."); try { final Object localizer = getLocalizer(); final Method clearCacheMethod = resolveClass("org.apache.wicket.Localizer") .getDeclaredMethod("clearCache"); clearCacheMethod.invoke(localizer); } catch (Exception e) { LOGGER.error("Error refreshing Wicket localizer cache", e); }
555
106
661
<no_super_class>
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-wildfly-el-plugin/src/main/java/org/hotswap/agent/plugin/wildfly/el/PurgeWildFlyBeanELResolverCacheCommand.java
PurgeWildFlyBeanELResolverCacheCommand
executeCommand
class PurgeWildFlyBeanELResolverCacheCommand extends MergeableCommand { /** The logger. */ private static AgentLogger LOGGER = AgentLogger.getLogger(PurgeWildFlyBeanELResolverCacheCommand.class); /** The app class loader. */ private ClassLoader appClassLoader; /** The class name. */ private String className; /** * Instantiates a new purge wild fly bean el resolver cache command. * * @param appClassLoader the app class loader * @param className the class name */ public PurgeWildFlyBeanELResolverCacheCommand(ClassLoader appClassLoader, String className) { this.appClassLoader = appClassLoader; this.className = className; } /* (non-Javadoc) * @see org.hotswap.agent.command.Command#executeCommand() */ @Override public void executeCommand() {<FILL_FUNCTION_BODY>} /** * Resolve class. * * @param name the name * @return the class * @throws ClassNotFoundException the class not found exception */ private Class<?> resolveClass(String name) throws ClassNotFoundException { return Class.forName(name, true, appClassLoader); } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PurgeWildFlyBeanELResolverCacheCommand that = (PurgeWildFlyBeanELResolverCacheCommand) o; if (!appClassLoader.equals(that.appClassLoader)) return false; return true; } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { int result = appClassLoader.hashCode(); return result; } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return "PurgeWildFlyBeanELResolverCacheCommand{" + "appClassLoader=" + appClassLoader + '}'; } }
LOGGER.info("Cleaning BeanPropertiesCache {} {}.", className, appClassLoader); if (className != null) { try { ClassLoader oldContextClassLoader = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(appClassLoader); Class<?> cacheClazz = Class.forName("org.jboss.el.cache.BeanPropertiesCache", true, appClassLoader); Method beanElResolverMethod = cacheClazz.getDeclaredMethod("getProperties", new Class<?>[] {}); Object o = beanElResolverMethod.invoke(null); @SuppressWarnings("unchecked") Map<Class<?>, Object> m = Map.class.cast(o); Iterator<Map.Entry<Class<?>, Object>> it = m.entrySet().iterator(); while (it.hasNext()) { Map.Entry<Class<?>, Object> entry = it.next(); if(entry.getKey().getClassLoader() == appClassLoader) { if (entry.getKey().getName().equals(className) || (entry.getKey().getName()).equals(className + "$Proxy$_$$_WeldSubclass")) { it.remove(); } } } } finally { Thread.currentThread().setContextClassLoader(oldContextClassLoader); } } catch (Exception e) { LOGGER.error("Error cleaning BeanPropertiesCache. {}", e, className); } } else { try { LOGGER.info("Cleaning BeanPropertiesCache {}.", appClassLoader); Method beanElResolverMethod = resolveClass("org.jboss.el.cache.BeanPropertiesCache").getDeclaredMethod("clear", ClassLoader.class); beanElResolverMethod.setAccessible(true); beanElResolverMethod.invoke(null, appClassLoader); } catch (Exception e) { LOGGER.error("Error cleaning BeanPropertiesCache. {}", e, appClassLoader); } try { LOGGER.info("Cleaning FactoryFinderCache {}.", appClassLoader); Method beanElResolverMethod = resolveClass("org.jboss.el.cache.FactoryFinderCache").getDeclaredMethod("clearClassLoader", ClassLoader.class); beanElResolverMethod.setAccessible(true); beanElResolverMethod.invoke(null, appClassLoader); } catch (Exception e) { LOGGER.error("Error cleaning FactoryFinderCache. {}", e, appClassLoader); } }
612
633
1,245
<methods>public non-sealed void <init>() ,public List<org.hotswap.agent.command.Command> getMergedCommands() ,public org.hotswap.agent.command.Command merge(org.hotswap.agent.command.Command) ,public List<org.hotswap.agent.command.Command> popMergedCommands() <variables>List<org.hotswap.agent.command.Command> mergedCommands
HotswapProjects_HotswapAgent
HotswapAgent/plugin/hotswap-agent-wildfly-el-plugin/src/main/java/org/hotswap/agent/plugin/wildfly/el/WildFlyELResolverPlugin.java
WildFlyELResolverPlugin
beanELResolverRegisterVariable
class WildFlyELResolverPlugin { private static AgentLogger LOGGER = AgentLogger.getLogger(WildFlyELResolverPlugin.class); public static final String PURGE_CLASS_CACHE_METHOD_NAME = "$$ha$resetCache"; @Init Scheduler scheduler; @Init ClassLoader appClassLoader; /** * Hook on BeanELResolver class and for each instance: - ensure plugin is * initialized - register instances using registerBeanELResolver() method. * * @param ctClass * the ct class * @param classPool * the class pool * @throws CannotCompileException * the cannot compile exception * @throws NotFoundException * the not found exception */ @OnClassLoadEvent(classNameRegexp = "javax.el.BeanELResolver") public static void beanELResolverRegisterVariable(CtClass ctClass, ClassPool classPool) throws CannotCompileException, NotFoundException {<FILL_FUNCTION_BODY>} /** * Hook on BeanELResolver class and for each instance: - ensure plugin is * initialized - register instances using registerBeanELResolver() method. * * @param ctClass * the ct class * @param classPool * the class pool * @throws CannotCompileException * the cannot compile exception * @throws NotFoundException * the not found exception */ @OnClassLoadEvent(classNameRegexp = "org.jboss.el.cache.BeanPropertiesCache") public static void beanPropertiesCache(CtClass ctClass, ClassPool classPool) throws CannotCompileException, NotFoundException { for (CtConstructor constructor : ctClass.getDeclaredConstructors()) { constructor.insertAfter("java.lang.ClassLoader $$cl = Thread.currentThread().getContextClassLoader();" + PluginManagerInvoker.buildInitializePlugin(WildFlyELResolverPlugin.class, "$$cl")); } LOGGER.info("Patched org.jboss.el.cache.BeanPropertiesCache"); } /** * Hook on org.jboss.el.cache.BeanPropertiesCache.SoftConcurrentHashMap * class and for each instance: - ensure plugin is initialized - register * instances using registerBeanELResolver() method * * @param ctClass * the ct class * @param classPool * the class pool * @throws CannotCompileException * the cannot compile exception * @throws NotFoundException * the not found exception */ @OnClassLoadEvent(classNameRegexp = "org.jboss.el.cache.BeanPropertiesCache.SoftConcurrentHashMap") public static void beanPropertiesCacheSoftConcurrentHashMap(CtClass ctClass, ClassPool classPool) throws CannotCompileException, NotFoundException { ctClass.addMethod(CtMethod.make("public java.util.Set entrySet() { return map.entrySet();}", ctClass)); LOGGER.info("Patched org.jboss.el.cache.BeanPropertiesCache$SoftConcurrentHashMap"); } /** * Hook on BeanELResolver class and for each instance: - ensure plugin is * initialized - register instances using registerBeanELResolver() method. * * @param ctClass * the ct class * @param classPool * the class pool * @throws CannotCompileException * the cannot compile exception * @throws NotFoundException * the not found exception */ @OnClassLoadEvent(classNameRegexp = "org.jboss.el.cache.FactoryFinderCache") public static void factoryFinderCache(CtClass ctClass, ClassPool classPool) throws CannotCompileException, NotFoundException { for (CtConstructor constructor : ctClass.getDeclaredConstructors()) { constructor.insertAfter("java.lang.ClassLoader $$cl = Thread.currentThread().getContextClassLoader();" + // PluginManagerInvoker.buildInitializePlugin(WildFlyELResolverPlugin.class, "$$cl")); } LOGGER.info("Patched org.jboss.el.cache.FactoryFinderCache"); } /** * Invalidate class cache. * * @param original * the original * @throws Exception * the exception */ @OnClassLoadEvent(classNameRegexp = ".*", events = LoadEvent.REDEFINE) public void invalidateClassCache(Class<?> original) throws Exception { LOGGER.trace("Running invalidateClassCache {}", appClassLoader); PurgeWildFlyBeanELResolverCacheCommand cmd = new PurgeWildFlyBeanELResolverCacheCommand(appClassLoader, original.getName()); scheduler.scheduleCommand(cmd, 250, DuplicateSheduleBehaviour.SKIP); } /** * Initialize instance. * * @param pluginConfiguration * the plugin configuration */ @Init public void initializeInstance(PluginConfiguration pluginConfiguration) { LOGGER.info("WildFlyELResolver plugin initialized"); } }
for (CtConstructor constructor : ctClass.getDeclaredConstructors()) { constructor.insertAfter("java.lang.ClassLoader $$cl = Thread.currentThread().getContextClassLoader();" + PluginManagerInvoker.buildInitializePlugin(WildFlyELResolverPlugin.class, "$$cl")); } LOGGER.info("Patched JbossELResolver");
1,304
94
1,398
<no_super_class>