proj_name
stringclasses 131
values | relative_path
stringlengths 30
228
| class_name
stringlengths 1
68
| func_name
stringlengths 1
48
| masked_class
stringlengths 78
9.82k
| func_body
stringlengths 46
9.61k
| len_input
int64 29
2.01k
| len_output
int64 14
1.94k
| total
int64 55
2.05k
| relevant_context
stringlengths 0
38.4k
|
---|---|---|---|---|---|---|---|---|---|
HotswapProjects_HotswapAgent
|
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/util/AppClassLoaderExecutor.java
|
AppClassLoaderExecutor
|
execute
|
class AppClassLoaderExecutor {
private static AgentLogger LOGGER = AgentLogger.getLogger(AnnotationProcessor.class);
ClassLoader appClassLoader;
ProtectionDomain protectionDomain;
public AppClassLoaderExecutor(ClassLoader appClassLoader, ProtectionDomain protectionDomain) {
this.appClassLoader = appClassLoader;
this.protectionDomain = protectionDomain;
}
public Object execute(String className, String method, Object... params)
throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {<FILL_FUNCTION_BODY>}
private boolean isSimpleType(Class<? extends Object> aClass) {
// primitive data types has null class loader
return aClass.getClassLoader() == null;
}
}
|
LOGGER.error("Start");
PluginManager.getInstance().initClassLoader(appClassLoader, protectionDomain);
Class classInAppClassLoader = Class.forName(className, true, appClassLoader);
LOGGER.error("Executing: requestedClassLoader={}, resolvedClassLoader={}, class={}, method={}, params={}",
appClassLoader, classInAppClassLoader.getClassLoader(), classInAppClassLoader, method, params);
Class[] paramTypes = new Class[params.length];
for (int i = 0; i < params.length; i++) {
if (params[i] == null)
throw new IllegalArgumentException("Cannot execute for null parameter classNameRegexp");
else if (!isSimpleType(params[i].getClass())) {
throw new IllegalArgumentException("Use only simple parameter values.");
} else {
paramTypes[i] = params[i].getClass();
}
}
Object instance = classInAppClassLoader.newInstance();
Method m = classInAppClassLoader.getDeclaredMethod(method, paramTypes);
Thread.currentThread().setContextClassLoader(appClassLoader);
return m.invoke(instance, params);
| 193 | 297 | 490 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/util/HotswapProperties.java
|
HotswapProperties
|
substitute
|
class HotswapProperties extends Properties {
private static final long serialVersionUID = 4467598209091707788L;
private static final Pattern VAR_PATTERN = Pattern.compile("\\$\\{([a-zA-Z0-9._]+?)\\}");
@Override
public Object put(Object key, Object value) {
return super.put(key, substitute(value));
}
private Object substitute(Object obj) {<FILL_FUNCTION_BODY>}
}
|
if (obj instanceof String) {
StringBuffer result = new StringBuffer();
Matcher m = VAR_PATTERN.matcher((String) obj);
while (m.find()) {
String replacement = System.getProperty(m.group(1));
if (replacement != null) {
m.appendReplacement(result, replacement);
}
}
m.appendTail(result);
return result.toString();
}
return obj;
| 142 | 121 | 263 |
<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/hotswap-agent-core/src/main/java/org/hotswap/agent/util/HotswapTransformer.java
|
RegisteredTransformersRecord
|
closeClassLoader
|
class RegisteredTransformersRecord {
Pattern pattern;
List<HaClassFileTransformer> transformerList = new LinkedList<>();
}
protected Map<String, RegisteredTransformersRecord> redefinitionTransformers = new LinkedHashMap<>();
protected Map<String, RegisteredTransformersRecord> otherTransformers = new LinkedHashMap<>();
// keep track about which classloader requested which transformer
protected Map<ClassFileTransformer, ClassLoader> classLoaderTransformers = new LinkedHashMap<>();
protected Map<ClassLoader, Boolean> seenClassLoaders = new WeakHashMap<>();
private List<Pattern> includedClassLoaderPatterns;
private List<Pattern> excludedClassLoaderPatterns;
public List<Pattern> getIncludedClassLoaderPatterns() {
return includedClassLoaderPatterns;
}
public void setIncludedClassLoaderPatterns(List<Pattern> includedClassLoaderPatterns) {
this.includedClassLoaderPatterns = includedClassLoaderPatterns;
}
/**
* @param excludedClassLoaderPatterns
* the excludedClassLoaderPatterns to set
*/
public void setExcludedClassLoaderPatterns(List<Pattern> excludedClassLoaderPatterns) {
this.excludedClassLoaderPatterns = excludedClassLoaderPatterns;
}
public List<Pattern> getExcludedClassLoaderPatterns() {
return excludedClassLoaderPatterns;
}
/**
* Register a transformer for a regexp matching class names.
* Used by {@link org.hotswap.agent.annotation.OnClassLoadEvent} annotation respective
* {@link org.hotswap.agent.annotation.handler.OnClassLoadedHandler}.
*
* @param classLoader the classloader to which this transformation is associated
* @param classNameRegexp regexp to match fully qualified class name.
* Because "." is any character in regexp, this will match / in the transform method as well
* (diffentence between java/lang/String and java.lang.String).
* @param transformer the transformer to be called for each class matching regexp.
*/
public void registerTransformer(ClassLoader classLoader, String classNameRegexp, HaClassFileTransformer transformer) {
LOGGER.debug("Registering transformer for class regexp '{}'.", classNameRegexp);
String normalizeRegexp = normalizeTypeRegexp(classNameRegexp);
Map<String, RegisteredTransformersRecord> transformersMap = getTransformerMap(transformer);
RegisteredTransformersRecord transformerRecord = transformersMap.get(normalizeRegexp);
if (transformerRecord == null) {
transformerRecord = new RegisteredTransformersRecord();
transformerRecord.pattern = Pattern.compile(normalizeRegexp);
transformersMap.put(normalizeRegexp, transformerRecord);
}
if (!transformerRecord.transformerList.contains(transformer)) {
transformerRecord.transformerList.add(transformer);
}
// register classloader association to allow classloader unregistration
if (classLoader != null) {
classLoaderTransformers.put(transformer, classLoader);
}
}
private Map<String, RegisteredTransformersRecord> getTransformerMap(HaClassFileTransformer transformer) {
if (transformer.isForRedefinitionOnly()) {
return redefinitionTransformers;
}
return otherTransformers;
}
/**
* Remove registered transformer.
*
* @param classNameRegexp regexp to match fully qualified class name.
* @param transformer currently registered transformer
*/
public void removeTransformer(String classNameRegexp, HaClassFileTransformer transformer) {
String normalizeRegexp = normalizeTypeRegexp(classNameRegexp);
Map<String, RegisteredTransformersRecord> transformersMap = getTransformerMap(transformer);
RegisteredTransformersRecord transformerRecord = transformersMap.get(normalizeRegexp);
if (transformerRecord != null) {
transformerRecord.transformerList.remove(transformer);
}
}
/**
* Remove all transformers registered with a classloader
* @param classLoader
*/
public void closeClassLoader(ClassLoader classLoader) {<FILL_FUNCTION_BODY>
|
for (Iterator<Map.Entry<ClassFileTransformer, ClassLoader>> entryIterator = classLoaderTransformers.entrySet().iterator();
entryIterator.hasNext(); ) {
Map.Entry<ClassFileTransformer, ClassLoader> entry = entryIterator.next();
if (entry.getValue().equals(classLoader)) {
entryIterator.remove();
for (RegisteredTransformersRecord transformerRecord : redefinitionTransformers.values()) {
transformerRecord.transformerList.remove(entry.getKey());
}
for (RegisteredTransformersRecord transformerRecord : otherTransformers.values()) {
transformerRecord.transformerList.remove(entry.getKey());
}
}
}
LOGGER.debug("All transformers removed for classLoader {}", classLoader);
| 1,058 | 189 | 1,247 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/util/IOUtils.java
|
IOUtils
|
streamToString
|
class IOUtils {
private static final AgentLogger LOGGER = AgentLogger.getLogger(IOUtils.class);
// some IDEs remove and recreate whole package multiple times while recompiling -
// we may need to wait for a file to be available on a filesystem
private static final int WAIT_FOR_FILE_MAX_SECONDS = 5;
/** URL protocol for a file in the file system: "file" */
public static final String URL_PROTOCOL_FILE = "file";
/** URL protocol for a JBoss VFS resource: "vfs" */
public static final String URL_PROTOCOL_VFS = "vfs";
/**
* Download URI to byte array.
*
* Wait for the file to exists up to 5 seconds - it may be recreated while IDE recompilation,
* automatic retry will avoid false errors.
*
* @param uri uri to process
* @return byte array
* @throws IllegalArgumentException for download problems
*/
public static byte[] toByteArray(URI uri) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
InputStream inputStream = null;
int tryCount = 0;
while (inputStream == null) {
try {
inputStream = uri.toURL().openStream();
} catch (FileNotFoundException e) {
// some IDEs remove and recreate whole package multiple times while recompiling -
// we may need to waitForResult for the file.
if (tryCount > WAIT_FOR_FILE_MAX_SECONDS * 10) {
LOGGER.trace("File not found, exiting with exception...", e);
throw new IllegalArgumentException(e);
} else {
tryCount++;
LOGGER.trace("File not found, waiting...", e);
try {
Thread.sleep(100);
} catch (InterruptedException ignore) {
}
}
} catch (Exception e) {
throw new IllegalStateException(e);
}
finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
LOGGER.error("Can't close file.", e);
}
}
}
}
try (InputStream stream = uri.toURL().openStream()) {
byte[] chunk = new byte[4096];
int bytesRead;
while ((bytesRead = stream.read(chunk)) > 0) {
outputStream.write(chunk, 0, bytesRead);
}
} catch (IOException e) {
throw new IllegalArgumentException(e);
}
return outputStream.toByteArray();
}
/**
* Convert input stream to a string.
* @param is stream
* @return string (at least empty string for empty stream)
*/
public static String streamToString(InputStream is) {<FILL_FUNCTION_BODY>}
/**
* Determine whether the given URL points to a resource in the file system,
* that is, has protocol "file" or "vfs".
* @param url the URL to check
* @return whether the URL has been identified as a file system URL
* @author Juergen Hoeller (org.springframework.util.ResourceUtils)
*/
public static boolean isFileURL(URL url) {
String protocol = url.getProtocol();
return (URL_PROTOCOL_FILE.equals(protocol) || protocol.startsWith(URL_PROTOCOL_VFS));
}
/**
* Determine whether the given URL points to a directory in the file system
*
* @param url the URL to check
* @return whether the URL has been identified as a file system URL
*/
public static boolean isDirectoryURL(URL url) {
try {
File f = new File(url.toURI());
if(f.exists() && f.isDirectory()) {
return true;
}
} catch (Exception ignore) {
}
return false;
}
/**
* Return fully qualified class name of class file on a URI.
*
* @param uri uri of class file
* @return name
* @throws IOException any exception on class instantiation
*/
public static String urlToClassName(URI uri) throws IOException {
return ClassPool.getDefault().makeClass(uri.toURL().openStream()).getName();
}
/**
* Extract file name from input stream.
*
* @param is the is
* @return the string
*/
public static String extractFileNameFromInputStream(InputStream is) {
try {
if ("sun.nio.ch.ChannelInputStream".equals(is.getClass().getName())) {
ReadableByteChannel ch = (ReadableByteChannel) ReflectionHelper.get(is, "ch");
return ch instanceof FileChannel ? (String) ReflectionHelper.get(ch, "path") : null;
}
while (true) {
if (is instanceof FileInputStream) {
return (String) ReflectionHelper.get(is, "path");
}
if (!(is instanceof FilterInputStream)) {
break;
}
is = (InputStream) ReflectionHelper.get(is, "in");
}
} catch (IllegalArgumentException e) {
LOGGER.error("extractFileNameFromInputStream() failed.", e);
}
return null;
}
/**
* Extract file name from reader.
*
* @param reader the reader
* @return the string
*/
public static String extractFileNameFromReader(Reader reader) {
try {
if (reader instanceof InputStreamReader) {
InputStream is = (InputStream) ReflectionHelper.get(reader, "lock");
return extractFileNameFromInputStream(is);
}
} catch (IllegalArgumentException e) {
LOGGER.error("extractFileNameFromReader() failed.", e);
}
return null;
}
/**
* Extract file name from input source.
*
* @param inputSource the input source
* @return the string
*/
public static String extractFileNameFromInputSource(InputSource inputSource) {
if (inputSource.getByteStream() != null) {
return extractFileNameFromInputStream(inputSource.getByteStream());
}
if (inputSource.getCharacterStream() != null) {
return extractFileNameFromReader(inputSource.getCharacterStream());
}
return null;
}
}
|
java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
| 1,609 | 46 | 1,655 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/util/PluginManagerInvoker.java
|
PluginManagerInvoker
|
buildCallPluginMethod
|
class PluginManagerInvoker {
/**
* Initialize plugin for a classloader.
*
* @param pluginClass identify plugin instance
* @param appClassLoader classloader in which the plugin should reside
*/
public static <T> T callInitializePlugin(Class<T> pluginClass, ClassLoader appClassLoader) {
// noinspection unchecked
return (T) PluginManager.getInstance().getPluginRegistry().initializePlugin(
pluginClass.getName(), appClassLoader
);
}
public static String buildInitializePlugin(Class pluginClass) {
return buildInitializePlugin(pluginClass, "getClass().getClassLoader()");
}
public static String buildInitializePlugin(Class pluginClass, String classLoaderVar) {
return "org.hotswap.agent.config.PluginManager.getInstance().getPluginRegistry().initializePlugin(" +
"\"" + pluginClass.getName() + "\", " + classLoaderVar +
");";
}
/**
* Free all classloader references and close any associated plugin instance.
* Typical use is after webapp undeploy.
*
* @param appClassLoader clasloade to free
*/
public static void callCloseClassLoader(ClassLoader appClassLoader) {
PluginManager.getInstance().closeClassLoader(appClassLoader);
}
public static String buildCallCloseClassLoader(String classLoaderVar) {
return "org.hotswap.agent.config.PluginManager.getInstance().closeClassLoader(" + classLoaderVar + ");";
}
/**
* Methods on plugin should be called via reflection, because the real plugin object is in parent classloader,
* but plugin class may be defined in app classloader as well introducing ClassCastException on same class name.
*
* @param pluginClass class name of the plugin - it is used to resolve plugin instance from plugin manager
* @param appClassLoader application classloader (to resolve plugin instance)
* @param method method name
* @param paramTypes param types (as required by reflection)
* @param params actual param values
* @return method return value
*/
public static Object callPluginMethod(Class pluginClass, ClassLoader appClassLoader, String method, Class[] paramTypes, Object[] params) {
Object pluginInstance = PluginManager.getInstance().getPlugin(pluginClass.getName(), appClassLoader);
try {
Method m = pluginInstance.getClass().getDeclaredMethod(method, paramTypes);
return m.invoke(pluginInstance, params);
} catch (Exception e) {
throw new Error(String.format("Exception calling method %s on plugin class %s", method, pluginClass), e);
}
}
/**
* Equivalent to callPluginMethod for insertion into source code.
* <p/>
* PluginManagerInvoker.buildCallPluginMethod(this, "hibernateInitialized",
* "getClass().getClassLoader()", "java.lang.ClassLoader")
*
* @param pluginClass plugin to use
* @param method method name
* @param paramValueAndType for each param its value AND type must be provided
* @return method source code
*/
public static String buildCallPluginMethod(Class pluginClass, String method, String... paramValueAndType) {
return buildCallPluginMethod("getClass().getClassLoader()", pluginClass, method, paramValueAndType);
}
/**
* Same as {@link PluginManagerInvoker#buildCallPluginMethod(Class, String, String...)}, but with explicit
* appClassLoader variable. Use this method if appClassLoader is different from getClass().getClassLoader().
*/
public static String buildCallPluginMethod(String appClassLoaderVar, Class pluginClass,
String method, String... paramValueAndType) {<FILL_FUNCTION_BODY>}
}
|
String managerClass = PluginManager.class.getName();
int paramCount = paramValueAndType.length / 2;
StringBuilder b = new StringBuilder();
// block to hide variables and catch checked exceptions
b.append("try {");
b.append("ClassLoader __pluginClassLoader = ");
b.append(managerClass);
b.append(".class.getClassLoader();");
// Object __pluginInstance = org.hotswap.agent.config.PluginManager.getInstance().getPlugin(org.hotswap.agent.plugin.TestPlugin.class.getName(), __pluginClassLoader);
b.append("Object __pluginInstance = ");
b.append(managerClass);
b.append(".getInstance().getPlugin(");
b.append(pluginClass.getName());
b.append(".class.getName(), " + appClassLoaderVar + ");");
// Class __pluginClass = __pluginClassLoader.loadClass("org.hotswap.agent.plugin.TestPlugin");
b.append("Class __pluginClass = ");
b.append("__pluginClassLoader.loadClass(\"");
b.append(pluginClass.getName());
b.append("\");");
// param types
b.append("Class[] paramTypes = new Class[" + paramCount + "];");
for (int i = 0; i < paramCount; i++) {
// paramTypes[i] = = __pluginClassLoader.loadClass("my.test.TestClass").getClass();
b.append("paramTypes[" + i + "] = __pluginClassLoader.loadClass(\"" + paramValueAndType[(i * 2) + 1] + "\");");
}
// java.lang.reflect.Method __pluginMethod = __pluginClass.getDeclaredMethod("method", paramType1, paramType2);
b.append("java.lang.reflect.Method __callPlugin = __pluginClass.getDeclaredMethod(\"");
b.append(method);
b.append("\", paramTypes");
b.append(");");
b.append("Object[] params = new Object[" + paramCount + "];");
for (int i = 0; i < paramCount; i = i + 1) {
b.append("params[" + i + "] = " + paramValueAndType[i * 2] + ";");
}
// __pluginMethod.invoke(__pluginInstance, param1, param2);
b.append("__callPlugin.invoke(__pluginInstance, params);");
// catch (Exception e) {throw new Error(e);}
b.append("} catch (Exception e) {throw new Error(e);}");
return b.toString();
| 948 | 659 | 1,607 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/util/Version.java
|
Version
|
version
|
class Version {
/**
* Return current version.
* @return the version.
*/
public static String version() {<FILL_FUNCTION_BODY>}
}
|
try {
Properties prop = new Properties();
InputStream in = Version.class.getResourceAsStream("/version.properties");
prop.load(in);
in.close();
return prop.getProperty("version") == null ? "unkown" : prop.getProperty("version");
} catch (IOException e) {
return "unknown";
}
| 48 | 92 | 140 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/util/classloader/ClassLoaderDefineClassPatcher.java
|
ClassLoaderDefineClassPatcher
|
transferTo
|
class ClassLoaderDefineClassPatcher {
private static AgentLogger LOGGER = AgentLogger.getLogger(ClassLoaderDefineClassPatcher.class);
private static Map<String, List<byte[]>> pluginClassCache = new HashMap<>();
/**
* Patch the classloader.
*
* @param classLoaderFrom classloader to load classes from
* @param pluginPath path to copy
* @param classLoaderTo classloader to copy classes to
* @param protectionDomain required protection in target classloader
*/
public void patch(final ClassLoader classLoaderFrom, final String pluginPath,
final ClassLoader classLoaderTo, final ProtectionDomain protectionDomain) {
List<byte[]> cache = getPluginCache(classLoaderFrom, pluginPath);
if (cache != null) {
final ClassPool cp = new ClassPool();
cp.appendClassPath(new LoaderClassPath(getClass().getClassLoader()));
Set<String> loadedClasses = new HashSet<>();
String packagePrefix = pluginPath.replace('/', '.');
for (byte[] pluginBytes: cache) {
CtClass pluginClass = null;
try {
// force to load class in classLoaderFrom (it may not yet be loaded) and if the classLoaderTo
// is parent of classLoaderFrom, after definition in classLoaderTo will classLoaderFrom return
// class from parent classloader instead own definition (hence change of behaviour).
InputStream is = new ByteArrayInputStream(pluginBytes);
pluginClass = cp.makeClass(is);
try {
classLoaderFrom.loadClass(pluginClass.getName());
} catch (NoClassDefFoundError e) {
LOGGER.trace("Skipping class loading {} in classloader {} - " +
"class has probably unresolvable dependency.", pluginClass.getName(), classLoaderTo);
}
// and load the class in classLoaderTo as well. Now the class is defined in BOTH classloaders.
transferTo(pluginClass, packagePrefix, classLoaderTo, protectionDomain, loadedClasses);
} catch (CannotCompileException e) {
LOGGER.trace("Skipping class definition {} in app classloader {} - " +
"class is probably already defined.", pluginClass.getName(), classLoaderTo);
} catch (NoClassDefFoundError e) {
LOGGER.trace("Skipping class definition {} in app classloader {} - " +
"class has probably unresolvable dependency.", pluginClass.getName(), classLoaderTo);
} catch (Throwable e) {
LOGGER.trace("Skipping class definition app classloader {} - " +
"unknown error.", e, classLoaderTo);
}
}
}
LOGGER.debug("Classloader {} patched with plugin classes from agent classloader {}.", classLoaderTo, classLoaderFrom);
}
private void transferTo(CtClass pluginClass, String pluginPath, ClassLoader classLoaderTo,
ProtectionDomain protectionDomain, Set<String> loadedClasses) throws CannotCompileException {<FILL_FUNCTION_BODY>}
private List<byte[]> getPluginCache(final ClassLoader classLoaderFrom, final String pluginPath) {
List<byte[]> ret = null;
synchronized(pluginClassCache) {
ret = pluginClassCache.get(pluginPath);
if (ret == null) {
final List<byte[]> retList = new ArrayList<>();
Scanner scanner = new ClassPathScanner();
try {
scanner.scan(classLoaderFrom, pluginPath, new ScannerVisitor() {
@Override
public void visit(InputStream file) throws IOException {
// skip plugin classes
// TODO this should be skipped only in patching application classloader. To copy
// classes into agent classloader, Plugin class must be copied as well
// if (patchClass.hasAnnotation(Plugin.class)) {
// LOGGER.trace("Skipping plugin class: " + patchClass.getName());
// return;
// }
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int readBytes;
byte[] data = new byte[16384];
while ((readBytes = file.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, readBytes);
}
buffer.flush();
retList.add(buffer.toByteArray());
}
});
} catch (IOException e) {
LOGGER.error("Exception while scanning 'org/hotswap/agent/plugin'", e);
}
ret = retList;
pluginClassCache.put(pluginPath, ret);
}
}
return ret;
}
/**
* Check if the classloader can be patched.
* Typically skip synthetic classloaders.
*
* @param classLoader classloader to check
* @return if true, call patch()
*/
public boolean isPatchAvailable(ClassLoader classLoader) {
// we can define class in any class loader
// exclude synthetic classloader where it does not make any sense
// sun.reflect.DelegatingClassLoader - created automatically by JVM to optimize reflection calls
return classLoader != null &&
!classLoader.getClass().getName().equals("sun.reflect.DelegatingClassLoader") &&
!classLoader.getClass().getName().equals("jdk.internal.reflect.DelegatingClassLoader")
;
}
}
|
// if the class is already loaded, skip it
if (loadedClasses.contains(pluginClass.getName()) || pluginClass.isFrozen() ||
!pluginClass.getName().startsWith(pluginPath)) {
return;
}
// 1. interface
try {
if (!pluginClass.isInterface()) {
CtClass[] ctClasses = pluginClass.getInterfaces();
if (ctClasses != null && ctClasses.length > 0) {
for (CtClass ctClass : ctClasses) {
try {
transferTo(ctClass, pluginPath, classLoaderTo, protectionDomain, loadedClasses);
} catch (Throwable e) {
LOGGER.trace("Skipping class loading {} in classloader {} - " +
"class has probably unresolvable dependency.", ctClass.getName(), classLoaderTo);
}
}
}
}
} catch (NotFoundException e) {
}
// 2. superClass
try {
CtClass ctClass = pluginClass.getSuperclass();
if (ctClass != null) {
try {
transferTo(ctClass, pluginPath, classLoaderTo, protectionDomain, loadedClasses);
} catch (Throwable e) {
LOGGER.trace("Skipping class loading {} in classloader {} - " +
"class has probably unresolvable dependency.", ctClass.getName(), classLoaderTo);
}
}
} catch (NotFoundException e) {
}
pluginClass.toClass(classLoaderTo, protectionDomain);
loadedClasses.add(pluginClass.getName());
| 1,331 | 396 | 1,727 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/util/classloader/ClassLoaderHelper.java
|
ClassLoaderHelper
|
isClassLoderStarted
|
class ClassLoaderHelper {
private static AgentLogger LOGGER = AgentLogger.getLogger(ClassLoaderHelper.class);
public static Method findLoadedClass;
static {
try {
findLoadedClass = ClassLoader.class.getDeclaredMethod("findLoadedClass", new Class[] { String.class });
findLoadedClass.setAccessible(true);
} catch (NoSuchMethodException e) {
LOGGER.error("Unexpected: failed to get ClassLoader findLoadedClass method", e);
}
}
/**
* Check if the class was already loaded by the classloader. It does not try to load the class
* (opposite to Class.forName()).
*
* @param classLoader classLoader to check
* @param className fully qualified class name
* @return true if the class was loaded
*/
public static boolean isClassLoaded(ClassLoader classLoader, String className) {
try {
return findLoadedClass.invoke(classLoader, className) != null;
} catch (Exception e) {
LOGGER.error("Unable to invoke findLoadedClass on classLoader {}, className {}", e, classLoader, className);
return false;
}
}
/**
* Some class loader has activity state. e.g. WebappClassLoader must be started before it can be used
*
* @param classLoader the class loader
* @return true, if is class loader active
*/
public static boolean isClassLoderStarted(ClassLoader classLoader) {<FILL_FUNCTION_BODY>}
}
|
String classLoaderClassName = (classLoader != null) ? classLoader.getClass().getName() : null;
// TODO: use interface instead of this hack
if ("org.glassfish.web.loader.WebappClassLoader".equals(classLoaderClassName)||
"org.apache.catalina.loader.WebappClassLoader".equals(classLoaderClassName) ||
"org.apache.catalina.loader.ParallelWebappClassLoader".equals(classLoaderClassName) ||
"org.apache.tomee.catalina.TomEEWebappClassLoader".equals(classLoaderClassName) ||
"org.springframework.boot.web.embedded.tomcat.TomcatEmbeddedWebappClassLoader".equals(classLoaderClassName)
)
{
try {
Class<?> clazz = classLoader.getClass();
boolean isStarted;
if ("org.apache.catalina.loader.WebappClassLoaderBase".equals(clazz.getSuperclass().getName())) {
clazz = clazz.getSuperclass();
isStarted = "STARTED".equals((String) ReflectionHelper.invoke(classLoader, clazz, "getStateName", new Class[] {}, null));
} else {
isStarted = (boolean) ReflectionHelper.invoke(classLoader, clazz, "isStarted", new Class[] {}, null);
}
return isStarted;
} catch (Exception e) {
LOGGER.warning("isClassLoderStarted() : {}", e.getMessage());
}
}
return true;
| 391 | 389 | 780 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/util/classloader/ClassLoaderProxy.java
|
ClassLoaderProxy
|
create
|
class ClassLoaderProxy {
ClassLoader targetClassLoader;
public CtClass create(CtClass classToProxy) throws Exception {<FILL_FUNCTION_BODY>}
}
|
// CtPool ctPool = classToProxy;
// ProxyFactory factory = new ProxyFactory();
// factory.setSuperclass(classToProxy);
// factory.
//
// Class proxy = factory.createClass();
//
// new ClassFile()
//
//
// MethodHandler handler = new MethodHandler() {
//
// @Override
// public Object invoke(Object self, Method overridden, Method forwarder,
// Object[] args) throws Throwable {
// System.out.println("do something "+overridden.getName());
//
// Class classInTargetClassLoader = targetClassLoader.loadClass(classToProxy.getName());
// Method methodInTargetClassLoader = classInTargetClassLoader.getDeclaredMethod(
// overridden.getName(), overridden.getParameterTypes()
// );
//
// Class returnType = overridden.getReturnType();
//
// return methodInTargetClassLoader.invoke(null, args);
// }
// };
// Object instance = proxy.newInstance();
// ((ProxyObject) instance).setHandler(handler);
// return (T) instance;
return null;
| 49 | 292 | 341 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/util/classloader/WatchResourcesClassLoader.java
|
WatchResourcesClassLoader
|
initWatchResources
|
class WatchResourcesClassLoader extends URLClassLoader {
private static AgentLogger LOGGER = AgentLogger.getLogger(WatchResourcesClassLoader.class);
/**
* URLs of changed resources. Use this set to check if the resource was changed and hence should
* be returned by this classloader.
*/
Set<URL> changedUrls = new HashSet<>();
/**
* Watch for requested resource in parent classloader in case it is not found by this classloader?
* Note that there is child first precedence anyway.
*/
boolean searchParent = true;
public void setSearchParent(boolean searchParent) {
this.searchParent = searchParent;
}
/**
* URL classloader configured to get resources only from exact set of URL's (no parent delegation)
*/
ClassLoader watchResourcesClassLoader;
public WatchResourcesClassLoader() {
this(false);
}
public WatchResourcesClassLoader(boolean searchParent) {
super(new URL[]{}, searchParent ? WatchResourcesClassLoader.class.getClassLoader() : null);
this.searchParent = searchParent;
}
public WatchResourcesClassLoader(ClassLoader classLoader) {
super(new URL[] {}, classLoader);
this.searchParent = false;
}
/**
* Configure new instance with urls and watcher service.
*
* @param extraPath the URLs from which to load resources
*/
public void initExtraPath(URL[] extraPath) {
for (URL url : extraPath)
addURL(url);
}
/**
* Configure new instance with urls and watcher service.
*
* @param watchResources the URLs from which to load resources
* @param watcher watcher service to register watch events
*/
public void initWatchResources(URL[] watchResources, Watcher watcher) {<FILL_FUNCTION_BODY>}
/**
* Check if the resource was changed after this classloader instantiaton.
*
* @param url full URL of the file
* @return true if was changed after instantiation
*/
public boolean isResourceChanged(URL url) {
return changedUrls.contains(url);
}
/**
* Returns URL only if the resource is found in changedURL and was actually changed after
* instantiation of this classloader.
*/
@Override
public URL getResource(String name) {
if (watchResourcesClassLoader != null) {
URL resource = watchResourcesClassLoader.getResource(name);
if (resource != null && isResourceChanged(resource)) {
LOGGER.trace("watchResources - using changed resource {}", name);
return resource;
}
}
// child first (extra classpath)
URL resource = findResource(name);
if (resource != null)
return resource;
// without parent do not call super (ignore even bootstrapResources)
if (searchParent)
return super.getResource(name);
else
return null;
}
@Override
public InputStream getResourceAsStream(String name) {
URL url = getResource(name);
try {
return url != null ? url.openStream() : null;
} catch (IOException e) {
}
return null;
}
/**
* Returns only a single instance of the changed resource.
* There are conflicting requirements for other resources inclusion. This class
* should "hide" the original resource, hence it should not be included in the resoult.
* On the other hand, there may be resource with the same name in other JAR which
* should be included and now is hidden (for example multiple persistence.xml).
* Maybe a new property to influence this behaviour?
*/
@Override
public Enumeration<URL> getResources(String name) throws IOException {
if (watchResourcesClassLoader != null) {
URL resource = watchResourcesClassLoader.getResource(name);
if (resource != null && isResourceChanged(resource)) {
LOGGER.trace("watchResources - using changed resource {}", name);
Vector<URL> res = new Vector<>();
res.add(resource);
return res.elements();
}
}
// if extraClasspath contains at least one element, return only extraClasspath
if (findResources(name).hasMoreElements())
return findResources(name);
return super.getResources(name);
}
/**
* Support for classpath builder on Tomcat.
*/
public String getClasspath() {
ClassLoader parent = getParent();
if (parent == null)
return null;
try {
Method m = parent.getClass().getMethod("getClasspath", new Class[] {});
if( m==null ) return null;
Object o = m.invoke( parent, new Object[] {} );
if( o instanceof String )
return (String)o;
return null;
} catch( Exception ex ) {
LOGGER.debug("getClasspath not supported on parent classloader.");
}
return null;
}
/**
* Helper classloader to get resources from list of urls only.
*/
public static class UrlOnlyClassLoader extends URLClassLoader {
public UrlOnlyClassLoader(URL[] urls) {
super(urls);
}
// do not use parent resource (may introduce infinite loop)
@Override
public URL getResource(String name) {
return findResource(name);
}
};
}
|
// create classloader to serve resources only from watchResources URL's
this.watchResourcesClassLoader = new UrlOnlyClassLoader(watchResources);
// register watch resources - on change event each modified resource will be added to changedUrls.
for (URL resource : watchResources) {
try {
URI uri = resource.toURI();
LOGGER.debug("Watching directory '{}' for changes.", uri);
watcher.addEventListener(this, uri, new WatchEventListener() {
@Override
public void onEvent(WatchFileEvent event) {
try {
if (event.isFile() || event.isDirectory()) {
changedUrls.add(event.getURI().toURL());
LOGGER.trace("File '{}' changed and will be returned instead of original classloader equivalent.", event.getURI().toURL());
}
} catch (MalformedURLException e) {
LOGGER.error("Unexpected - cannot convert URI {} to URL.", e, event.getURI());
}
}
});
} catch (URISyntaxException e) {
LOGGER.warning("Unable to convert watchResources URL '{}' to URI. URL is skipped.", e, resource);
}
}
| 1,375 | 299 | 1,674 |
<methods>public void <init>(java.net.URL[]) ,public void <init>(java.net.URL[], java.lang.ClassLoader) ,public void <init>(java.net.URL[], java.lang.ClassLoader, java.net.URLStreamHandlerFactory) ,public void <init>(java.lang.String, java.net.URL[], java.lang.ClassLoader) ,public void <init>(java.lang.String, java.net.URL[], java.lang.ClassLoader, java.net.URLStreamHandlerFactory) ,public void close() throws java.io.IOException,public java.net.URL findResource(java.lang.String) ,public Enumeration<java.net.URL> findResources(java.lang.String) throws java.io.IOException,public java.io.InputStream getResourceAsStream(java.lang.String) ,public java.net.URL[] getURLs() ,public static java.net.URLClassLoader newInstance(java.net.URL[]) ,public static java.net.URLClassLoader newInstance(java.net.URL[], java.lang.ClassLoader) <variables>private final java.security.AccessControlContext acc,private WeakHashMap<java.io.Closeable,java.lang.Void> closeables,private final jdk.internal.loader.URLClassPath ucp
|
HotswapProjects_HotswapAgent
|
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/util/scanner/ClassPathAnnotationScanner.java
|
ClassPathAnnotationScanner
|
scanPlugins
|
class ClassPathAnnotationScanner {
private static AgentLogger LOGGER = AgentLogger.getLogger(ClassPathAnnotationScanner.class);
// Annotation name to search for
String annotation;
// scanner to search path
Scanner scanner;
/**
* Create scanner for the annotation.
*/
public ClassPathAnnotationScanner(String annotation, Scanner scanner) {
this.annotation = annotation;
this.scanner = scanner;
}
/**
* Run the scan - search path for files containing annotation.
*
* @param classLoader classloader to resolve path
* @param path path to scan {@link org.hotswap.agent.util.scanner.Scanner#scan(ClassLoader, String, ScannerVisitor)}
* @return list of class names containing the annotation
* @throws IOException scan exception.
*/
public List<String> scanPlugins(ClassLoader classLoader, String path) throws IOException {<FILL_FUNCTION_BODY>}
/**
* Check if the file contains annotation.
*/
protected boolean hasAnnotation(ClassFile cf) throws IOException {
AnnotationsAttribute visible = (AnnotationsAttribute) cf.getAttribute(AnnotationsAttribute.visibleTag);
if (visible != null) {
for (Annotation ann : visible.getAnnotations()) {
if (annotation.equals(ann.getTypeName())) {
return true;
}
}
}
return false;
}
}
|
final List<String> files = new LinkedList<>();
scanner.scan(classLoader, path, new ScannerVisitor() {
@Override
public void visit(InputStream file) throws IOException {
ClassFile cf;
try {
DataInputStream dstream = new DataInputStream(file);
cf = new ClassFile(dstream);
} catch (IOException e) {
throw new IOException("Stream not a valid classFile", e);
}
if (hasAnnotation(cf))
files.add(cf.getName());
}
});
return files;
| 372 | 144 | 516 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/util/scanner/ClassPathScanner.java
|
ClassPathScanner
|
scanJar
|
class ClassPathScanner implements Scanner {
private static AgentLogger LOGGER = AgentLogger.getLogger(ClassPathScanner.class);
// scan for files inside JAR file - e.g. jar:file:\J:\HotswapAgent\target\HotswapAgent-1.0.jar!\org\hotswap\agent\plugin
public static final String JAR_URL_SEPARATOR = "!/";
public static final String JAR_URL_PREFIX = "jar:";
public static final String ZIP_URL_PREFIX = "zip:";
public static final String FILE_URL_PREFIX = "file:";
@Override
public void scan(ClassLoader classLoader, String path, ScannerVisitor visitor) throws IOException {
LOGGER.trace("Scanning path {}", path);
// find all directories - classpath directory or JAR
Enumeration<URL> en = classLoader == null ? ClassLoader.getSystemResources(path) : classLoader.getResources(path);
while (en.hasMoreElements()) {
URL pluginDirURL = en.nextElement();
File pluginDir = new File(pluginDirURL.getFile());
if (pluginDir.isDirectory()) {
scanDirectory(pluginDir, visitor);
} else {
// JAR file
String uri;
try {
uri = pluginDirURL.toURI().toString();
} catch (URISyntaxException e) {
throw new IOException("Illegal directory URI " + pluginDirURL, e);
}
if (uri.startsWith(JAR_URL_PREFIX) || uri.startsWith(ZIP_URL_PREFIX)) {
String jarFile = uri.substring(uri.indexOf(':') + 1); // remove the prefix
scanJar(jarFile, visitor);
} else {
LOGGER.warning("Unknown resource type of file " + uri);
}
}
}
}
/**
* Recursively scan the directory.
*
* @param pluginDir directory.
* @param visitor callback
* @throws IOException exception from a visitor
*/
protected void scanDirectory(File pluginDir, ScannerVisitor visitor) throws IOException {
LOGGER.trace("Scanning directory " + pluginDir.getName());
for (File file : pluginDir.listFiles()) {
if (file.isDirectory()) {
scanDirectory(file, visitor);
} else if (file.isFile() && file.getName().endsWith(".class")) {
visitor.visit(new FileInputStream(file));
}
}
}
/**
* Scan JAR file for all entries.
* Resolve the JAR file itself and than iterate all entries and call visitor.
*
* @param urlFile URL to the file containing scanned directory
* (e.g. jar:file:\J:\HotswapAgent\target\HotswapAgent-1.0.jar!\org\hotswap\agent\plugin)
* @param visitor callback
* @throws IOException exception from a visitor
*/
private void scanJar(String urlFile, ScannerVisitor visitor) throws IOException {<FILL_FUNCTION_BODY>}
/**
* Resolve the given jar file URL into a JarFile object.
*/
protected JarFile getJarFile(String jarFileUrl) throws IOException {
LOGGER.trace("Opening JAR file " + jarFileUrl);
if (jarFileUrl.startsWith(FILE_URL_PREFIX)) {
try {
return new JarFile(toURI(jarFileUrl).getSchemeSpecificPart());
} catch (URISyntaxException ex) {
// Fallback for URLs that are not valid URIs (should hardly ever happen).
return new JarFile(jarFileUrl.substring(FILE_URL_PREFIX.length()));
}
} else {
return new JarFile(jarFileUrl);
}
}
/**
* Create a URI instance for the given location String,
* replacing spaces with "%20" quotes first.
*
* @param location the location String to convert into a URI instance
* @return the URI instance
* @throws URISyntaxException if the location wasn't a valid URI
*/
public static URI toURI(String location) throws URISyntaxException {
return new URI(location.replace(" ", "%20"));
}
}
|
LOGGER.trace("Scanning JAR file '{}'", urlFile);
int separatorIndex = urlFile.indexOf(JAR_URL_SEPARATOR);
JarFile jarFile = null;
String rootEntryPath;
try {
if (separatorIndex != -1) {
String jarFileUrl = urlFile.substring(0, separatorIndex);
rootEntryPath = urlFile.substring(separatorIndex + JAR_URL_SEPARATOR.length());
jarFile = getJarFile(jarFileUrl);
} else {
rootEntryPath = "";
jarFile = new JarFile(urlFile);
}
if (!"".equals(rootEntryPath) && !rootEntryPath.endsWith("/")) {
rootEntryPath = rootEntryPath + "/";
}
for (Enumeration<JarEntry> entries = jarFile.entries(); entries.hasMoreElements(); ) {
JarEntry entry = entries.nextElement();
String entryPath = entry.getName();
// class files inside entry
if (entryPath.startsWith(rootEntryPath) && entryPath.endsWith(".class")) {
LOGGER.trace("Visiting JAR entry {}", entryPath);
visitor.visit(jarFile.getInputStream(entry));
}
}
} finally {
if (jarFile != null) {
jarFile.close();
}
}
| 1,090 | 354 | 1,444 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/util/scanner/PluginCache.java
|
PluginCache
|
scanPlugins
|
class PluginCache {
public static final String PLUGIN_PATH = "org/hotswap/agent/plugin";
private Map<ClassLoader, Set<CtClass>> pluginDefs = new HashMap<>();
Scanner scanner = new ClassPathScanner();
public Set<CtClass> getPlugins(ClassLoader classLoader) {
if (pluginDefs.containsKey(classLoader))
return pluginDefs.get(classLoader);
else
return Collections.emptySet();
}
public Set<CtClass> scanPlugins(ClassLoader classLoader) throws IOException {<FILL_FUNCTION_BODY>}
}
|
if (!pluginDefs.containsKey(classLoader)) {
synchronized (pluginDefs) {
if (!pluginDefs.containsKey(classLoader)) {
final Set<CtClass> plugins = new HashSet<>();
final ClassPool classPool = ClassPool.getDefault();
scanner.scan(getClass().getClassLoader(), PLUGIN_PATH, new ScannerVisitor() {
@Override
public void visit(InputStream file) throws IOException {
plugins.add(classPool.makeClass(file));
}
});
}
}
}
return pluginDefs.get(classLoader);
| 168 | 159 | 327 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/util/signature/ClassSignatureBase.java
|
ClassSignatureBase
|
annotationToString
|
class ClassSignatureBase {
private static final String[] IGNORED_METHODS = new String[] { "annotationType", "equals", "hashCode", "toString" };
private final Set<ClassSignatureElement> elements = new HashSet<>();
protected static final String SWITCH_TABLE_METHOD_PREFIX = "$SWITCH_TABLE$"; // java stores switch table to class field, signature should ingore it
/**
* Evaluate and return signature value
*
* @return the signature value
* @throws Exception
*/
public abstract String getValue() throws Exception;
/**
* Adds the signature elements to set of used signature elements
*
* @param elems
*/
public void addSignatureElements(ClassSignatureElement elems[]) {
for (ClassSignatureElement element : elems) {
elements.add(element);
}
}
/**
* Check if given signature element is set.
*
* @param element
* @return true, if has given element
*/
public boolean hasElement(ClassSignatureElement element) {
return elements.contains(element);
}
protected String annotationToString(Object[] a) {<FILL_FUNCTION_BODY>}
private Object arrayToString(Object value) {
Object result = value;
try {
try {
Method toStringMethod = Arrays.class.getMethod("toString", value.getClass());
// maybe because value is a subclass of Object[]
result = toStringMethod.invoke(null, value);
} catch (NoSuchMethodException e) {
if (value instanceof Object[]) {
Method toStringMethod = Arrays.class.getMethod("toString", Object[].class);
result = toStringMethod.invoke(null, value);
}
}
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e ) {
}
return result;
}
protected String annotationToString(Object[][] a) {
if (a == null)
return "null";
int iMax = a.length - 1;
if (iMax == -1)
return "[]";
a = sort(a);
StringBuilder b = new StringBuilder();
b.append('[');
for (int i = 0;; i++) {
Object[] object = a[i];
b.append(annotationToString(object));
if (i == iMax)
return b.append(']').toString();
b.append(", ");
}
}
private <T> T[] sort(T[] a) {
a = Arrays.copyOf(a, a.length);
Arrays.sort(a, ToStringComparator.INSTANCE);
return a;
}
private <T> T[][] sort(T[][] a) {
a = Arrays.copyOf(a, a.length);
Arrays.sort(a, ToStringComparator.INSTANCE);
for (Object[] objects : a) {
Arrays.sort(objects, ToStringComparator.INSTANCE);
}
return a;
}
private Object getAnnotationValue(Annotation annotation, String attributeName) {
Method method = null;
boolean acessibleSet = false;
try {
method = annotation.annotationType().getDeclaredMethod(attributeName);
acessibleSet = makeAccessible(method);
return method.invoke(annotation);
} catch (Exception ex) {
return null;
} finally {
if (method != null && acessibleSet) {
method.setAccessible(false);
}
}
}
private boolean makeAccessible(Method method) {
if ((!Modifier.isPublic(method.getModifiers()) || !Modifier.isPublic(method.getDeclaringClass().getModifiers()))
&& !method.isAccessible()) {
method.setAccessible(true);
return true;
}
return false;
}
protected static class ToStringComparator implements Comparator<Object> {
public static final ToStringComparator INSTANCE = new ToStringComparator();
@Override
public int compare(Object o1, Object o2) {
return o1.toString().compareTo(o2.toString());
}
}
}
|
if (a == null)
return "null";
int iMax = a.length - 1;
if (iMax == -1)
return "[]";
a = sort(a);
StringBuilder b = new StringBuilder();
b.append('[');
for (int i = 0;i < a.length; i++) {
Annotation object = (Annotation) a[i];
Method[] declaredMethods = object.getClass().getDeclaredMethods();
b.append("(");
boolean printComma = false;
for (Method method : declaredMethods) {
if (Arrays.binarySearch(IGNORED_METHODS, method.getName()) < 0) {
Object value = getAnnotationValue(object, method.getName());
if (value != null) {
if (printComma) {
b.append(",");
} else {
printComma = true;
}
if (value.getClass().isArray()) {
value = arrayToString(value);
}
b.append(method.getName() + "=" + value.getClass() + ":" + value);
}
}
}
b.append(")");
// TODO : sometimes for CtFile object.annotationType() is not known an it fails here
// v.d. : uncommented in v1.1 alpha with javassist update (3.21) to check if there is still problem
b.append(object.annotationType().getName());
if (i<a.length-1) {
b.append(",");
}
}
b.append(']');
return b.toString();
| 1,082 | 414 | 1,496 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/util/signature/ClassSignatureComparerHelper.java
|
ClassSignatureComparerHelper
|
isDifferent
|
class ClassSignatureComparerHelper {
private static AgentLogger LOGGER = AgentLogger.getLogger(ClassSignatureComparerHelper.class);
public static String getCtClassSignature(CtClass ctClass, ClassSignatureElement[] signatureElements) throws Exception {
CtClassSignature signature = new CtClassSignature(ctClass);
signature.addSignatureElements(signatureElements);
return signature.getValue();
}
public static String getJavaClassSignature(Class<?> clazz, ClassSignatureElement[] signatureElements) throws Exception {
JavaClassSignature signature = new JavaClassSignature(clazz);
signature.addSignatureElements(signatureElements);
return signature.getValue();
}
/**
* @param ctClass new CtClass definition
* @param clazz old Class definition
* @return is signature different
*/
public static boolean isDifferent(CtClass ctClass, Class<?> clazz, ClassSignatureElement[] signatureElements) {
try {
String sig1 = getCtClassSignature(ctClass, signatureElements);
String sig2 = getJavaClassSignature(clazz, signatureElements);
return !sig1.equals(sig2);
} catch (Exception e) {
LOGGER.error("Error reading signature", e);
return false;
}
}
public static boolean isDifferent(Class<?> clazz1, Class<?> clazz2, ClassSignatureElement[] signatureElements) {<FILL_FUNCTION_BODY>}
/**
* @param clazz old Class definition
* @param cp ClassPool which should contain the new/compared definition
* @return is signature different
*/
public static boolean isPoolClassDifferent(Class<?> clazz, ClassPool cp, ClassSignatureElement[] signatureElements) {
try {
return isDifferent(cp.get(clazz.getName()), clazz, signatureElements);
} catch (NotFoundException e) {
LOGGER.error("Class not found ", e);
return false;
}
}
}
|
try {
String sig1 = getJavaClassSignature(clazz1, signatureElements);
String sig2 = getJavaClassSignature(clazz2, signatureElements);
return !sig1.equals(sig2);
} catch (Exception e) {
LOGGER.error("Error reading signature", e);
return false;
}
| 498 | 85 | 583 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/util/signature/CtClassSignature.java
|
CtClassSignature
|
getValue
|
class CtClassSignature extends ClassSignatureBase {
private CtClass ctClass;
/**
* @param ctClass the class for signature is to be counted
*/
public CtClassSignature(CtClass ctClass) {
this.ctClass = ctClass;
}
@Override
public String getValue() throws Exception {<FILL_FUNCTION_BODY>}
private String getName(CtClass ctClass) {
return ctClass.getName();
}
private String getConstructorString(CtConstructor method) throws ClassNotFoundException, NotFoundException {
StringBuilder strBuilder = new StringBuilder();
strBuilder.append(Modifier.toString(method.getModifiers()) + " ");
strBuilder.append(method.getDeclaringClass().getName());
strBuilder.append(getParams(method.getParameterTypes()));
if (hasElement(ClassSignatureElement.METHOD_ANNOTATION))
strBuilder.append(annotationToString(method.getAvailableAnnotations()));
if (hasElement(ClassSignatureElement.METHOD_PARAM_ANNOTATION))
strBuilder.append(annotationToString(method.getAvailableParameterAnnotations()));
if (hasElement(ClassSignatureElement.METHOD_EXCEPTION))
strBuilder.append(toStringException(method.getExceptionTypes()));
strBuilder.append(";");
return strBuilder.toString();
}
private String getMethodString(CtMethod method) throws NotFoundException, ClassNotFoundException {
StringBuilder strBuilder = new StringBuilder();
strBuilder.append(Modifier.toString(method.getModifiers()) + " ");
strBuilder.append(getName(method.getReturnType()) + " " + method.getName());
strBuilder.append(getParams(method.getParameterTypes()));
if (hasElement(ClassSignatureElement.METHOD_ANNOTATION))
strBuilder.append(annotationToString(method.getAvailableAnnotations()));
if (hasElement(ClassSignatureElement.METHOD_PARAM_ANNOTATION))
strBuilder.append(annotationToString(method.getAvailableParameterAnnotations()));
if (hasElement(ClassSignatureElement.METHOD_EXCEPTION))
strBuilder.append(toStringException(method.getExceptionTypes()));
strBuilder.append(";");
return strBuilder.toString();
}
private String getParams(CtClass[] ctClasses) {
StringBuilder strBuilder = new StringBuilder("(");
boolean first = true;
for (CtClass ctClass : ctClasses) {
if (!first)
strBuilder.append(",");
else
first = false;
strBuilder.append(getName(ctClass));
}
strBuilder.append(")");
return strBuilder.toString();
}
private String toStringException(CtClass[] a) {
if (a == null)
return "null";
int iMax = a.length - 1;
if (iMax == -1)
return "[]";
a = sort(a);
StringBuilder b = new StringBuilder();
b.append('[');
for (int i = 0;; i++) {
b.append("class " + a[i].getName());
if (i == iMax)
return b.append(']').toString();
b.append(", ");
}
}
private CtClass[] sort(CtClass[] a) {
a = Arrays.copyOf(a, a.length);
Arrays.sort(a, CtClassComparator.INSTANCE);
return a;
}
private static class CtClassComparator implements Comparator<CtClass> {
public static final CtClassComparator INSTANCE = new CtClassComparator();
@Override
public int compare(CtClass o1, CtClass o2) {
return o1.getName().compareTo(o2.getName());
}
}
}
|
List<String> strings = new ArrayList<>();
if (hasElement(ClassSignatureElement.METHOD)) {
boolean usePrivateMethod = hasElement(ClassSignatureElement.METHOD_PRIVATE);
boolean useStaticMethod = hasElement(ClassSignatureElement.METHOD_STATIC);
for (CtMethod method : ctClass.getDeclaredMethods()) {
if (!usePrivateMethod && Modifier.isPrivate(method.getModifiers()))
continue;
if (!useStaticMethod && Modifier.isStatic(method.getModifiers()))
continue;
if (method.getName().startsWith(SWITCH_TABLE_METHOD_PREFIX))
continue;
strings.add(getMethodString(method));
}
}
if (hasElement(ClassSignatureElement.CONSTRUCTOR)) {
boolean usePrivateConstructor = hasElement(ClassSignatureElement.CONSTRUCTOR_PRIVATE);
for (CtConstructor method : ctClass.getDeclaredConstructors()) {
if (!usePrivateConstructor && Modifier.isPrivate(method.getModifiers()))
continue;
strings.add(getConstructorString(method));
}
}
if (hasElement(ClassSignatureElement.CLASS_ANNOTATION)) {
strings.add(annotationToString(ctClass.getAvailableAnnotations()));
}
if (hasElement(ClassSignatureElement.INTERFACES)) {
for (CtClass iClass : ctClass.getInterfaces()) {
strings.add(iClass.getName());
}
}
if (hasElement(ClassSignatureElement.SUPER_CLASS)) {
String superclassName = ctClass.getSuperclassName();
if (superclassName != null && !superclassName.equals(Object.class.getName()))
strings.add(superclassName);
}
if (hasElement(ClassSignatureElement.FIELD)) {
boolean useStaticField = hasElement(ClassSignatureElement.FIELD_STATIC);
boolean useFieldAnnotation = hasElement(ClassSignatureElement.FIELD_ANNOTATION);
for (CtField field : ctClass.getDeclaredFields()) {
if (!useStaticField && Modifier.isStatic(field.getModifiers()))
continue;
if (field.getName().startsWith(SWITCH_TABLE_METHOD_PREFIX))
continue;
String fieldSignature = field.getType().getName() + " " + field.getName();
if (useFieldAnnotation) {
fieldSignature += annotationToString(field.getAvailableAnnotations());
}
strings.add(fieldSignature + ";");
}
}
Collections.sort(strings);
StringBuilder strBuilder = new StringBuilder();
for (String methodString : strings) {
strBuilder.append(methodString);
}
return strBuilder.toString();
| 974 | 688 | 1,662 |
<methods>public non-sealed void <init>() ,public void addSignatureElements(org.hotswap.agent.util.signature.ClassSignatureElement[]) ,public abstract java.lang.String getValue() throws java.lang.Exception,public boolean hasElement(org.hotswap.agent.util.signature.ClassSignatureElement) <variables>private static final java.lang.String[] IGNORED_METHODS,protected static final java.lang.String SWITCH_TABLE_METHOD_PREFIX,private final Set<org.hotswap.agent.util.signature.ClassSignatureElement> elements
|
HotswapProjects_HotswapAgent
|
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/util/signature/JavaClassSignature.java
|
JavaClassSignature
|
getValue
|
class JavaClassSignature extends ClassSignatureBase {
private Class<?> clazz;
public JavaClassSignature(Class<?> clazz) {
this.clazz = clazz;
}
@Override
public String getValue() throws Exception {<FILL_FUNCTION_BODY>}
private String getConstructorString(Constructor<?> method) {
StringBuilder strBuilder = new StringBuilder();
strBuilder.append(Modifier.toString(method.getModifiers()) + " ");
strBuilder.append(method.getName());
strBuilder.append(getParams(method.getParameterTypes()));
if (hasElement(ClassSignatureElement.METHOD_ANNOTATION))
strBuilder.append(annotationToString(method.getDeclaredAnnotations()));
if (hasElement(ClassSignatureElement.METHOD_PARAM_ANNOTATION))
strBuilder.append(annotationToString(method.getParameterAnnotations()));
if (hasElement(ClassSignatureElement.METHOD_EXCEPTION))
strBuilder.append(Arrays.toString(sort(method.getExceptionTypes())));
strBuilder.append(";");
return strBuilder.toString();
}
private String getMethodString(Method method) {
StringBuilder strBuilder = new StringBuilder();
strBuilder.append(Modifier.toString(method.getModifiers()) + " ");
strBuilder.append(getName(method.getReturnType()) + " " + method.getName());
strBuilder.append(getParams(method.getParameterTypes()));
if (hasElement(ClassSignatureElement.METHOD_ANNOTATION))
strBuilder.append(annotationToString(method.getDeclaredAnnotations()));
if (hasElement(ClassSignatureElement.METHOD_PARAM_ANNOTATION))
strBuilder.append(annotationToString(method.getParameterAnnotations()));
if (hasElement(ClassSignatureElement.METHOD_EXCEPTION))
strBuilder.append(Arrays.toString(sort(method.getExceptionTypes())));
strBuilder.append(";");
return strBuilder.toString();
}
private <T> T[] sort(T[] a) {
a = Arrays.copyOf(a, a.length);
Arrays.sort(a, ToStringComparator.INSTANCE);
return a;
}
private String getParams(Class<?>[] parameterTypes) {
StringBuilder strB = new StringBuilder("(");
boolean first = true;
for (Class<?> ctClass : parameterTypes) {
if (!first)
strB.append(",");
else
first = false;
strB.append(getName(ctClass));
}
strB.append(")");
return strB.toString();
}
private String getName(Class<?> ctClass) {
if (ctClass.isArray())
return Descriptor.toString(ctClass.getName());
else
return ctClass.getName();
}
}
|
List<String> strings = new ArrayList<>();
if (hasElement(ClassSignatureElement.METHOD)) {
boolean usePrivateMethod = hasElement(ClassSignatureElement.METHOD_PRIVATE);
boolean useStaticMethod = hasElement(ClassSignatureElement.METHOD_STATIC);
for (Method method : clazz.getDeclaredMethods()) {
if (!usePrivateMethod && Modifier.isPrivate(method.getModifiers()))
continue;
if (!useStaticMethod && Modifier.isStatic(method.getModifiers()))
continue;
if (method.getName().startsWith(SWITCH_TABLE_METHOD_PREFIX))
continue;
strings.add(getMethodString(method));
}
}
if (hasElement(ClassSignatureElement.CONSTRUCTOR)) {
boolean usePrivateConstructor = hasElement(ClassSignatureElement.CONSTRUCTOR_PRIVATE);
for (Constructor<?> method : clazz.getDeclaredConstructors()) {
if (!usePrivateConstructor && Modifier.isPrivate(method.getModifiers()))
continue;
strings.add(getConstructorString(method));
}
}
if (hasElement(ClassSignatureElement.CLASS_ANNOTATION)) {
strings.add(annotationToString(clazz.getAnnotations()));
}
if (hasElement(ClassSignatureElement.INTERFACES)) {
for (Class<?> iClass : clazz.getInterfaces()) {
strings.add(iClass.getName());
}
}
if (hasElement(ClassSignatureElement.SUPER_CLASS)) {
if (clazz.getSuperclass() != null && !clazz.getSuperclass().getName().equals(Object.class.getName()))
strings.add(clazz.getSuperclass().getName());
}
if (hasElement(ClassSignatureElement.FIELD)) {
boolean useStaticField = hasElement(ClassSignatureElement.FIELD_STATIC);
boolean useFieldAnnotation = hasElement(ClassSignatureElement.FIELD_ANNOTATION);
for (Field field : clazz.getDeclaredFields()) {
if (!useStaticField && Modifier.isStatic(field.getModifiers()))
continue;
if (field.getName().startsWith(SWITCH_TABLE_METHOD_PREFIX))
continue;
String fieldSignature = field.getType().getName() + " " + field.getName();
if (useFieldAnnotation) {
fieldSignature += annotationToString(field.getAnnotations());
}
strings.add(fieldSignature + ";");
}
}
Collections.sort(strings);
StringBuilder strBuilder = new StringBuilder();
for (String methodString : strings) {
strBuilder.append(methodString);
}
return strBuilder.toString();
| 723 | 685 | 1,408 |
<methods>public non-sealed void <init>() ,public void addSignatureElements(org.hotswap.agent.util.signature.ClassSignatureElement[]) ,public abstract java.lang.String getValue() throws java.lang.Exception,public boolean hasElement(org.hotswap.agent.util.signature.ClassSignatureElement) <variables>private static final java.lang.String[] IGNORED_METHODS,protected static final java.lang.String SWITCH_TABLE_METHOD_PREFIX,private final Set<org.hotswap.agent.util.signature.ClassSignatureElement> elements
|
HotswapProjects_HotswapAgent
|
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/util/spring/collections/LinkedMultiValueMap.java
|
LinkedMultiValueMap
|
deepCopy
|
class LinkedMultiValueMap<K, V> implements MultiValueMap<K, V>, Serializable {
private static final long serialVersionUID = 3801124242820219131L;
private final Map<K, List<V>> targetMap;
/**
* Create a new LinkedMultiValueMap that wraps a {@link LinkedHashMap}.
*/
public LinkedMultiValueMap() {
this.targetMap = new LinkedHashMap<K, List<V>>();
}
/**
* Create a new LinkedMultiValueMap that wraps a {@link LinkedHashMap} with
* the given initial capacity.
*
* @param initialCapacity
* the initial capacity
*/
public LinkedMultiValueMap(int initialCapacity) {
this.targetMap = new LinkedHashMap<K, List<V>>(initialCapacity);
}
/**
* Copy constructor: Create a new LinkedMultiValueMap with the same mappings
* as the specified Map. Note that this will be a shallow copy; its
* value-holding List entries will get reused and therefore cannot get
* modified independently.
*
* @param otherMap
* the Map whose mappings are to be placed in this Map
* @see #clone()
* @see #deepCopy()
*/
public LinkedMultiValueMap(Map<K, List<V>> otherMap) {
this.targetMap = new LinkedHashMap<K, List<V>>(otherMap);
}
// MultiValueMap implementation
@Override
public void add(K key, V value) {
List<V> values = this.targetMap.get(key);
if (values == null) {
values = new LinkedList<V>();
this.targetMap.put(key, values);
}
values.add(value);
}
@Override
public V getFirst(K key) {
List<V> values = this.targetMap.get(key);
return (values != null ? values.get(0) : null);
}
@Override
public void set(K key, V value) {
List<V> values = new LinkedList<V>();
values.add(value);
this.targetMap.put(key, values);
}
@Override
public void setAll(Map<K, V> values) {
for (Entry<K, V> entry : values.entrySet()) {
set(entry.getKey(), entry.getValue());
}
}
@Override
public Map<K, V> toSingleValueMap() {
LinkedHashMap<K, V> singleValueMap = new LinkedHashMap<K, V>(this.targetMap.size());
for (Entry<K, List<V>> entry : this.targetMap.entrySet()) {
singleValueMap.put(entry.getKey(), entry.getValue().get(0));
}
return singleValueMap;
}
// Map implementation
@Override
public int size() {
return this.targetMap.size();
}
@Override
public boolean isEmpty() {
return this.targetMap.isEmpty();
}
@Override
public boolean containsKey(Object key) {
return this.targetMap.containsKey(key);
}
@Override
public boolean containsValue(Object value) {
return this.targetMap.containsValue(value);
}
@Override
public List<V> get(Object key) {
return this.targetMap.get(key);
}
@Override
public List<V> put(K key, List<V> value) {
return this.targetMap.put(key, value);
}
@Override
public List<V> remove(Object key) {
return this.targetMap.remove(key);
}
@Override
public void putAll(Map<? extends K, ? extends List<V>> map) {
this.targetMap.putAll(map);
}
@Override
public void clear() {
this.targetMap.clear();
}
@Override
public Set<K> keySet() {
return this.targetMap.keySet();
}
@Override
public Collection<List<V>> values() {
return this.targetMap.values();
}
@Override
public Set<Entry<K, List<V>>> entrySet() {
return this.targetMap.entrySet();
}
/**
* Create a regular copy of this Map.
*
* @return a shallow copy of this Map, reusing this Map's value-holding List
* entries
* @since 4.2
* @see LinkedMultiValueMap#LinkedMultiValueMap(Map)
* @see #deepCopy()
*/
@Override
public LinkedMultiValueMap<K, V> clone() {
return new LinkedMultiValueMap<K, V>(this);
}
/**
* Create a deep copy of this Map.
*
* @return a copy of this Map, including a copy of each value-holding List
* entry
* @since 4.2
* @see #clone()
*/
public LinkedMultiValueMap<K, V> deepCopy() {<FILL_FUNCTION_BODY>}
@Override
public boolean equals(Object obj) {
return this.targetMap.equals(obj);
}
@Override
public int hashCode() {
return this.targetMap.hashCode();
}
@Override
public String toString() {
return this.targetMap.toString();
}
}
|
LinkedMultiValueMap<K, V> copy = new LinkedMultiValueMap<K, V>(this.targetMap.size());
for (Map.Entry<K, List<V>> entry : this.targetMap.entrySet()) {
copy.put(entry.getKey(), new LinkedList<V>(entry.getValue()));
}
return copy;
| 1,440 | 89 | 1,529 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/util/spring/io/loader/ClassRelativeResourceLoader.java
|
ClassRelativeContextResource
|
createRelative
|
class ClassRelativeContextResource extends ClassPathResource implements ContextResource {
private final Class<?> clazz;
public ClassRelativeContextResource(String path, Class<?> clazz) {
super(path, clazz);
this.clazz = clazz;
}
@Override
public String getPathWithinContext() {
return getPath();
}
@Override
public Resource createRelative(String relativePath) {<FILL_FUNCTION_BODY>}
}
|
String pathToUse = StringUtils.applyRelativePath(getPath(), relativePath);
return new ClassRelativeContextResource(pathToUse, this.clazz);
| 128 | 43 | 171 |
<methods>public void <init>() ,public void <init>(java.lang.ClassLoader) ,public java.lang.ClassLoader getClassLoader() ,public org.hotswap.agent.util.spring.io.resource.Resource getResource(java.lang.String) ,public void setClassLoader(java.lang.ClassLoader) <variables>private java.lang.ClassLoader classLoader
|
HotswapProjects_HotswapAgent
|
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/util/spring/io/loader/DefaultResourceLoader.java
|
DefaultResourceLoader
|
getResource
|
class DefaultResourceLoader implements ResourceLoader {
private ClassLoader classLoader;
/**
* Create a new DefaultResourceLoader.
* <p>
* ClassLoader access will happen using the thread context class loader at
* the time of this ResourceLoader's initialization.
*
* @see java.lang.Thread#getContextClassLoader()
*/
public DefaultResourceLoader() {
this.classLoader = ClassUtils.getDefaultClassLoader();
}
/**
* Create a new DefaultResourceLoader.
*
* @param classLoader
* the ClassLoader to load class path resources with, or
* {@code null} for using the thread context class loader at the
* time of actual resource access
*/
public DefaultResourceLoader(ClassLoader classLoader) {
this.classLoader = classLoader;
}
/**
* Specify the ClassLoader to load class path resources with, or
* {@code null} for using the thread context class loader at the time of
* actual resource access.
* <p>
* The default is that ClassLoader access will happen using the thread
* context class loader at the time of this ResourceLoader's initialization.
*/
public void setClassLoader(ClassLoader classLoader) {
this.classLoader = classLoader;
}
/**
* Return the ClassLoader to load class path resources with.
* <p>
* Will get passed to ClassPathResource's constructor for all
* ClassPathResource objects created by this resource loader.
*
* @see ClassPathResource
*/
@Override
public ClassLoader getClassLoader() {
return (this.classLoader != null ? this.classLoader : ClassUtils.getDefaultClassLoader());
}
@Override
public Resource getResource(String location) {<FILL_FUNCTION_BODY>}
/**
* Return a Resource handle for the resource at the given path.
* <p>
* The default implementation supports class path locations. This should be
* appropriate for standalone implementations but can be overridden, e.g.
* for implementations targeted at a Servlet container.
*
* @param path
* the path to the resource
* @return the corresponding Resource handle
* @see ClassPathResource
* @see org.springframework.context.support.FileSystemXmlApplicationContext#getResourceByPath
* @see org.springframework.web.context.support.XmlWebApplicationContext#getResourceByPath
*/
protected Resource getResourceByPath(String path) {
return new ClassPathContextResource(path, getClassLoader());
}
/**
* ClassPathResource that explicitly expresses a context-relative path
* through implementing the ContextResource interface.
*/
protected static class ClassPathContextResource extends ClassPathResource implements ContextResource {
public ClassPathContextResource(String path, ClassLoader classLoader) {
super(path, classLoader);
}
@Override
public String getPathWithinContext() {
return getPath();
}
@Override
public Resource createRelative(String relativePath) {
String pathToUse = StringUtils.applyRelativePath(getPath(), relativePath);
return new ClassPathContextResource(pathToUse, getClassLoader());
}
}
}
|
Assert.notNull(location, "Location must not be null");
if (location.startsWith("/")) {
return getResourceByPath(location);
} else if (location.startsWith(CLASSPATH_URL_PREFIX)) {
return new ClassPathResource(location.substring(CLASSPATH_URL_PREFIX.length()), getClassLoader());
} else {
try {
// Try to parse the location as a URL...
URL url = new URL(location);
return new UrlResource(url);
} catch (MalformedURLException ex) {
// No URL -> resolve as resource path.
return getResourceByPath(location);
}
}
| 818 | 170 | 988 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/util/spring/io/loader/FileSystemResourceLoader.java
|
FileSystemResourceLoader
|
getResourceByPath
|
class FileSystemResourceLoader extends DefaultResourceLoader {
/**
* Resolve resource paths as file system paths.
* <p>
* Note: Even if a given path starts with a slash, it will get interpreted
* as relative to the current VM working directory.
*
* @param path
* the path to the resource
* @return the corresponding Resource handle
* @see FileSystemResource
* @see org.springframework.web.context.support.ServletContextResourceLoader#getResourceByPath
*/
@Override
protected Resource getResourceByPath(String path) {<FILL_FUNCTION_BODY>}
/**
* FileSystemResource that explicitly expresses a context-relative path
* through implementing the ContextResource interface.
*/
private static class FileSystemContextResource extends FileSystemResource implements ContextResource {
public FileSystemContextResource(String path) {
super(path);
}
@Override
public String getPathWithinContext() {
return getPath();
}
}
}
|
if (path != null && path.startsWith("/")) {
path = path.substring(1);
}
return new FileSystemContextResource(path);
| 260 | 45 | 305 |
<methods>public void <init>() ,public void <init>(java.lang.ClassLoader) ,public java.lang.ClassLoader getClassLoader() ,public org.hotswap.agent.util.spring.io.resource.Resource getResource(java.lang.String) ,public void setClassLoader(java.lang.ClassLoader) <variables>private java.lang.ClassLoader classLoader
|
HotswapProjects_HotswapAgent
|
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/util/spring/io/resource/AbstractFileResolvingResource.java
|
AbstractFileResolvingResource
|
lastModified
|
class AbstractFileResolvingResource extends AbstractResource {
/**
* This implementation returns a File reference for the underlying class
* path resource, provided that it refers to a file in the file system.
*
* @see org.hotswap.agent.util.spring.util.springframework.util.ResourceUtils#getFile(java.net.URL,
* String)
*/
@Override
public File getFile() throws IOException {
URL url = getURL();
if (url.getProtocol().startsWith(ResourceUtils.URL_PROTOCOL_VFS)) {
return VfsResourceDelegate.getResource(url).getFile();
}
return ResourceUtils.getFile(url, getDescription());
}
/**
* This implementation determines the underlying File (or jar file, in case
* of a resource in a jar/zip).
*/
@Override
protected File getFileForLastModifiedCheck() throws IOException {
URL url = getURL();
if (ResourceUtils.isJarURL(url)) {
URL actualUrl = ResourceUtils.extractJarFileURL(url);
if (actualUrl.getProtocol().startsWith(ResourceUtils.URL_PROTOCOL_VFS)) {
return VfsResourceDelegate.getResource(actualUrl).getFile();
}
return ResourceUtils.getFile(actualUrl, "Jar URL");
} else {
return getFile();
}
}
/**
* This implementation returns a File reference for the underlying class
* path resource, provided that it refers to a file in the file system.
*
* @see org.hotswap.agent.util.spring.util.springframework.util.ResourceUtils#getFile(java.net.URI,
* String)
*/
protected File getFile(URI uri) throws IOException {
if (uri.getScheme().startsWith(ResourceUtils.URL_PROTOCOL_VFS)) {
return VfsResourceDelegate.getResource(uri).getFile();
}
return ResourceUtils.getFile(uri, getDescription());
}
@Override
public boolean exists() {
try {
URL url = getURL();
if (ResourceUtils.isFileURL(url)) {
// Proceed with file system resolution...
return getFile().exists();
} else {
// Try a URL connection content-length header...
URLConnection con = url.openConnection();
customizeConnection(con);
HttpURLConnection httpCon = (con instanceof HttpURLConnection ? (HttpURLConnection) con : null);
if (httpCon != null) {
int code = httpCon.getResponseCode();
if (code == HttpURLConnection.HTTP_OK) {
return true;
} else if (code == HttpURLConnection.HTTP_NOT_FOUND) {
return false;
}
}
if (con.getContentLength() >= 0) {
return true;
}
if (httpCon != null) {
// no HTTP OK status, and no content-length header: give up
httpCon.disconnect();
return false;
} else {
// Fall back to stream existence: can we open the stream?
try (InputStream is = getInputStream()) {
return true;
}
}
}
} catch (IOException ex) {
return false;
}
}
@Override
public boolean isReadable() {
try {
URL url = getURL();
if (ResourceUtils.isFileURL(url)) {
// Proceed with file system resolution...
File file = getFile();
return (file.canRead() && !file.isDirectory());
} else {
return true;
}
} catch (IOException ex) {
return false;
}
}
@Override
public long contentLength() throws IOException {
URL url = getURL();
if (ResourceUtils.isFileURL(url)) {
// Proceed with file system resolution...
return getFile().length();
} else {
// Try a URL connection content-length header...
URLConnection con = url.openConnection();
customizeConnection(con);
return con.getContentLength();
}
}
@Override
public long lastModified() throws IOException {<FILL_FUNCTION_BODY>}
/**
* Customize the given {@link URLConnection}, obtained in the course of an
* {@link #exists()}, {@link #contentLength()} or {@link #lastModified()}
* call.
* <p>
* Calls {@link ResourceUtils#useCachesIfNecessary(URLConnection)} and
* delegates to {@link #customizeConnection(HttpURLConnection)} if possible.
* Can be overridden in subclasses.
*
* @param con
* the URLConnection to customize
* @throws IOException
* if thrown from URLConnection methods
*/
protected void customizeConnection(URLConnection con) throws IOException {
ResourceUtils.useCachesIfNecessary(con);
if (con instanceof HttpURLConnection) {
customizeConnection((HttpURLConnection) con);
}
}
/**
* Customize the given {@link HttpURLConnection}, obtained in the course of
* an {@link #exists()}, {@link #contentLength()} or {@link #lastModified()}
* call.
* <p>
* Sets request method "HEAD" by default. Can be overridden in subclasses.
*
* @param con
* the HttpURLConnection to customize
* @throws IOException
* if thrown from HttpURLConnection methods
*/
protected void customizeConnection(HttpURLConnection con) throws IOException {
con.setRequestMethod("HEAD");
}
/**
* Inner delegate class, avoiding a hard JBoss VFS API dependency at
* runtime.
*/
private static class VfsResourceDelegate {
public static Resource getResource(URL url) throws IOException {
return new VfsResource(VfsUtils.getRoot(url));
}
public static Resource getResource(URI uri) throws IOException {
return new VfsResource(VfsUtils.getRoot(uri));
}
}
}
|
URL url = getURL();
if (ResourceUtils.isFileURL(url) || ResourceUtils.isJarURL(url)) {
// Proceed with file system resolution...
return super.lastModified();
} else {
// Try a URL connection last-modified header...
URLConnection con = url.openConnection();
customizeConnection(con);
return con.getLastModified();
}
| 1,544 | 104 | 1,648 |
<methods>public non-sealed void <init>() ,public long contentLength() throws java.io.IOException,public org.hotswap.agent.util.spring.io.resource.Resource createRelative(java.lang.String) throws java.io.IOException,public boolean equals(java.lang.Object) ,public boolean exists() ,public java.io.File getFile() throws java.io.IOException,public java.lang.String getFilename() ,public java.net.URI getURI() throws java.io.IOException,public java.net.URL getURL() throws java.io.IOException,public int hashCode() ,public boolean isOpen() ,public boolean isReadable() ,public long lastModified() throws java.io.IOException,public java.lang.String toString() <variables>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/util/spring/io/resource/AbstractResource.java
|
AbstractResource
|
exists
|
class AbstractResource implements Resource {
/**
* This implementation checks whether a File can be opened, falling back to
* whether an InputStream can be opened. This will cover both directories
* and content resources.
*/
@Override
public boolean exists() {<FILL_FUNCTION_BODY>}
/**
* This implementation always returns {@code true}.
*/
@Override
public boolean isReadable() {
return true;
}
/**
* This implementation always returns {@code false}.
*/
@Override
public boolean isOpen() {
return false;
}
/**
* This implementation throws a FileNotFoundException, assuming that the
* resource cannot be resolved to a URL.
*/
@Override
public URL getURL() throws IOException {
throw new FileNotFoundException(getDescription() + " cannot be resolved to URL");
}
/**
* This implementation builds a URI based on the URL returned by
* {@link #getURL()}.
*/
@Override
public URI getURI() throws IOException {
URL url = getURL();
try {
return ResourceUtils.toURI(url);
} catch (URISyntaxException ex) {
throw new NestedIOException("Invalid URI [" + url + "]", ex);
}
}
/**
* This implementation throws a FileNotFoundException, assuming that the
* resource cannot be resolved to an absolute file path.
*/
@Override
public File getFile() throws IOException {
throw new FileNotFoundException(getDescription() + " cannot be resolved to absolute file path");
}
/**
* This implementation reads the entire InputStream to calculate the content
* length. Subclasses will almost always be able to provide a more optimal
* version of this, e.g. checking a File length.
*
* @see #getInputStream()
* @throws IllegalStateException
* if {@link #getInputStream()} returns null.
*/
@Override
public long contentLength() throws IOException {
try (InputStream is = this.getInputStream()) {
Assert.state(is != null, "resource input stream must not be null");
long size = 0;
byte[] buf = new byte[255];
int read;
while ((read = is.read(buf)) != -1) {
size += read;
}
return size;
}
}
/**
* This implementation checks the timestamp of the underlying File, if
* available.
*
* @see #getFileForLastModifiedCheck()
*/
@Override
public long lastModified() throws IOException {
long lastModified = getFileForLastModifiedCheck().lastModified();
if (lastModified == 0L) {
throw new FileNotFoundException(getDescription() + " cannot be resolved in the file system for resolving its last-modified timestamp");
}
return lastModified;
}
/**
* Determine the File to use for timestamp checking.
* <p>
* The default implementation delegates to {@link #getFile()}.
*
* @return the File to use for timestamp checking (never {@code null})
* @throws IOException
* if the resource cannot be resolved as absolute file path,
* i.e. if the resource is not available in a file system
*/
protected File getFileForLastModifiedCheck() throws IOException {
return getFile();
}
/**
* This implementation throws a FileNotFoundException, assuming that
* relative resources cannot be created for this resource.
*/
@Override
public Resource createRelative(String relativePath) throws IOException {
throw new FileNotFoundException("Cannot create a relative resource for " + getDescription());
}
/**
* This implementation always returns {@code null}, assuming that this
* resource type does not have a filename.
*/
@Override
public String getFilename() {
return null;
}
/**
* This implementation returns the description of this resource.
*
* @see #getDescription()
*/
@Override
public String toString() {
return getDescription();
}
/**
* This implementation compares description strings.
*
* @see #getDescription()
*/
@Override
public boolean equals(Object obj) {
return (obj == this || (obj instanceof Resource && ((Resource) obj).getDescription().equals(getDescription())));
}
/**
* This implementation returns the description's hash code.
*
* @see #getDescription()
*/
@Override
public int hashCode() {
return getDescription().hashCode();
}
}
|
// Try file existence: can we find the file in the file system?
try {
return getFile().exists();
} catch (IOException ex) {
// Fall back to stream existence: can we open the stream?
try (InputStream is = getInputStream()) {
return true;
} catch (Throwable isEx) {
return false;
}
}
| 1,171 | 94 | 1,265 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/util/spring/io/resource/ClassPathResource.java
|
ClassPathResource
|
resolveURL
|
class ClassPathResource extends AbstractFileResolvingResource {
private final String path;
private ClassLoader classLoader;
private Class<?> clazz;
/**
* Create a new {@code ClassPathResource} for {@code ClassLoader} usage. A
* leading slash will be removed, as the ClassLoader resource access methods
* will not accept it.
* <p>
* The thread context class loader will be used for loading the resource.
*
* @param path
* the absolute path within the class path
* @see java.lang.ClassLoader#getResourceAsStream(String)
* @see org.springframework.util.ClassUtils#getDefaultClassLoader()
*/
public ClassPathResource(String path) {
this(path, (ClassLoader) null);
}
/**
* Create a new {@code ClassPathResource} for {@code ClassLoader} usage. A
* leading slash will be removed, as the ClassLoader resource access methods
* will not accept it.
*
* @param path
* the absolute path within the classpath
* @param classLoader
* the class loader to load the resource with, or {@code null}
* for the thread context class loader
* @see ClassLoader#getResourceAsStream(String)
*/
public ClassPathResource(String path, ClassLoader classLoader) {
Assert.notNull(path, "Path must not be null");
String pathToUse = StringUtils.cleanPath(path);
if (pathToUse.startsWith("/")) {
pathToUse = pathToUse.substring(1);
}
this.path = pathToUse;
this.classLoader = (classLoader != null ? classLoader : ClassUtils.getDefaultClassLoader());
}
/**
* Create a new {@code ClassPathResource} for {@code Class} usage. The path
* can be relative to the given class, or absolute within the classpath via
* a leading slash.
*
* @param path
* relative or absolute path within the class path
* @param clazz
* the class to load resources with
* @see java.lang.Class#getResourceAsStream
*/
public ClassPathResource(String path, Class<?> clazz) {
Assert.notNull(path, "Path must not be null");
this.path = StringUtils.cleanPath(path);
this.clazz = clazz;
}
/**
* Create a new {@code ClassPathResource} with optional {@code ClassLoader}
* and {@code Class}. Only for internal usage.
*
* @param path
* relative or absolute path within the classpath
* @param classLoader
* the class loader to load the resource with, if any
* @param clazz
* the class to load resources with, if any
*/
protected ClassPathResource(String path, ClassLoader classLoader, Class<?> clazz) {
this.path = StringUtils.cleanPath(path);
this.classLoader = classLoader;
this.clazz = clazz;
}
/**
* Return the path for this resource (as resource path within the class
* path).
*/
public final String getPath() {
return this.path;
}
/**
* Return the ClassLoader that this resource will be obtained from.
*/
public final ClassLoader getClassLoader() {
return (this.clazz != null ? this.clazz.getClassLoader() : this.classLoader);
}
/**
* This implementation checks for the resolution of a resource URL.
*
* @see java.lang.ClassLoader#getResource(String)
* @see java.lang.Class#getResource(String)
*/
@Override
public boolean exists() {
return (resolveURL() != null);
}
/**
* Resolves a URL for the underlying class path resource.
*
* @return the resolved URL, or {@code null} if not resolvable
*/
protected URL resolveURL() {<FILL_FUNCTION_BODY>}
/**
* This implementation opens an InputStream for the given class path
* resource.
*
* @see java.lang.ClassLoader#getResourceAsStream(String)
* @see java.lang.Class#getResourceAsStream(String)
*/
@Override
public InputStream getInputStream() throws IOException {
InputStream is;
if (this.clazz != null) {
is = this.clazz.getResourceAsStream(this.path);
} else if (this.classLoader != null) {
is = this.classLoader.getResourceAsStream(this.path);
} else {
is = ClassLoader.getSystemResourceAsStream(this.path);
}
if (is == null) {
throw new FileNotFoundException(getDescription() + " cannot be opened because it does not exist");
}
return is;
}
/**
* This implementation returns a URL for the underlying class path resource,
* if available.
*
* @see java.lang.ClassLoader#getResource(String)
* @see java.lang.Class#getResource(String)
*/
@Override
public URL getURL() throws IOException {
URL url = resolveURL();
if (url == null) {
throw new FileNotFoundException(getDescription() + " cannot be resolved to URL because it does not exist");
}
return url;
}
/**
* This implementation creates a ClassPathResource, applying the given path
* relative to the path of the underlying resource of this descriptor.
*
* @see org.springframework.util.StringUtils#applyRelativePath(String,
* String)
*/
@Override
public Resource createRelative(String relativePath) {
String pathToUse = StringUtils.applyRelativePath(this.path, relativePath);
return new ClassPathResource(pathToUse, this.classLoader, this.clazz);
}
/**
* This implementation returns the name of the file that this class path
* resource refers to.
*
* @see org.springframework.util.StringUtils#getFilename(String)
*/
@Override
public String getFilename() {
return StringUtils.getFilename(this.path);
}
/**
* This implementation returns a description that includes the class path
* location.
*/
@Override
public String getDescription() {
StringBuilder builder = new StringBuilder("class path resource [");
String pathToUse = path;
if (this.clazz != null && !pathToUse.startsWith("/")) {
builder.append(ClassUtils.classPackageAsResourcePath(this.clazz));
builder.append('/');
}
if (pathToUse.startsWith("/")) {
pathToUse = pathToUse.substring(1);
}
builder.append(pathToUse);
builder.append(']');
return builder.toString();
}
/**
* This implementation compares the underlying class path locations.
*/
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj instanceof ClassPathResource) {
ClassPathResource otherRes = (ClassPathResource) obj;
return (this.path.equals(otherRes.path) && ObjectUtils.nullSafeEquals(this.classLoader, otherRes.classLoader) && ObjectUtils.nullSafeEquals(this.clazz, otherRes.clazz));
}
return false;
}
/**
* This implementation returns the hash code of the underlying class path
* location.
*/
@Override
public int hashCode() {
return this.path.hashCode();
}
}
|
if (this.clazz != null) {
return this.clazz.getResource(this.path);
} else if (this.classLoader != null) {
return this.classLoader.getResource(this.path);
} else {
return ClassLoader.getSystemResource(this.path);
}
| 1,964 | 83 | 2,047 |
<methods>public non-sealed void <init>() ,public long contentLength() throws java.io.IOException,public boolean exists() ,public java.io.File getFile() throws java.io.IOException,public boolean isReadable() ,public long lastModified() throws java.io.IOException<variables>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/util/spring/io/resource/FileSystemResource.java
|
FileSystemResource
|
equals
|
class FileSystemResource extends AbstractResource implements WritableResource {
private final File file;
private final String path;
/**
* Create a new {@code FileSystemResource} from a {@link File} handle.
* <p>
* Note: When building relative resources via {@link #createRelative}, the
* relative path will apply <i>at the same directory level</i>: e.g. new
* File("C:/dir1"), relative path "dir2" -> "C:/dir2"! If you prefer to have
* relative paths built underneath the given root directory, use the
* {@link #FileSystemResource(String) constructor with a file path} to
* append a trailing slash to the root path: "C:/dir1/", which indicates
* this directory as root for all relative paths.
*
* @param file
* a File handle
*/
public FileSystemResource(File file) {
Assert.notNull(file, "File must not be null");
this.file = file;
this.path = StringUtils.cleanPath(file.getPath());
}
/**
* Create a new {@code FileSystemResource} from a file path.
* <p>
* Note: When building relative resources via {@link #createRelative}, it
* makes a difference whether the specified resource base path here ends
* with a slash or not. In the case of "C:/dir1/", relative paths will be
* built underneath that root: e.g. relative path "dir2" -> "C:/dir1/dir2".
* In the case of "C:/dir1", relative paths will apply at the same directory
* level: relative path "dir2" -> "C:/dir2".
*
* @param path
* a file path
*/
public FileSystemResource(String path) {
Assert.notNull(path, "Path must not be null");
this.file = new File(path);
this.path = StringUtils.cleanPath(path);
}
/**
* Return the file path for this resource.
*/
public final String getPath() {
return this.path;
}
/**
* This implementation returns whether the underlying file exists.
*
* @see java.io.File#exists()
*/
@Override
public boolean exists() {
return this.file.exists();
}
/**
* This implementation checks whether the underlying file is marked as
* readable (and corresponds to an actual file with content, not to a
* directory).
*
* @see java.io.File#canRead()
* @see java.io.File#isDirectory()
*/
@Override
public boolean isReadable() {
return (this.file.canRead() && !this.file.isDirectory());
}
/**
* This implementation opens a FileInputStream for the underlying file.
*
* @see java.io.FileInputStream
*/
@Override
public InputStream getInputStream() throws IOException {
return new FileInputStream(this.file);
}
/**
* This implementation returns a URL for the underlying file.
*
* @see java.io.File#toURI()
*/
@Override
public URL getURL() throws IOException {
return this.file.toURI().toURL();
}
/**
* This implementation returns a URI for the underlying file.
*
* @see java.io.File#toURI()
*/
@Override
public URI getURI() throws IOException {
return this.file.toURI();
}
/**
* This implementation returns the underlying File reference.
*/
@Override
public File getFile() {
return this.file;
}
/**
* This implementation returns the underlying File's length.
*/
@Override
public long contentLength() throws IOException {
return this.file.length();
}
/**
* This implementation creates a FileSystemResource, applying the given path
* relative to the path of the underlying file of this resource descriptor.
*
* @see org.hotswap.agent.util.spring.util.springframework.util.StringUtils#applyRelativePath(String,
* String)
*/
@Override
public Resource createRelative(String relativePath) {
String pathToUse = StringUtils.applyRelativePath(this.path, relativePath);
return new FileSystemResource(pathToUse);
}
/**
* This implementation returns the name of the file.
*
* @see java.io.File#getName()
*/
@Override
public String getFilename() {
return this.file.getName();
}
/**
* This implementation returns a description that includes the absolute path
* of the file.
*
* @see java.io.File#getAbsolutePath()
*/
@Override
public String getDescription() {
return "file [" + this.file.getAbsolutePath() + "]";
}
// implementation of WritableResource
/**
* This implementation checks whether the underlying file is marked as
* writable (and corresponds to an actual file with content, not to a
* directory).
*
* @see java.io.File#canWrite()
* @see java.io.File#isDirectory()
*/
@Override
public boolean isWritable() {
return (this.file.canWrite() && !this.file.isDirectory());
}
/**
* This implementation opens a FileOutputStream for the underlying file.
*
* @see java.io.FileOutputStream
*/
@Override
public OutputStream getOutputStream() throws IOException {
return new FileOutputStream(this.file);
}
/**
* This implementation compares the underlying File references.
*/
@Override
public boolean equals(Object obj) {<FILL_FUNCTION_BODY>}
/**
* This implementation returns the hash code of the underlying File
* reference.
*/
@Override
public int hashCode() {
return this.path.hashCode();
}
}
|
return (obj == this || (obj instanceof FileSystemResource && this.path.equals(((FileSystemResource) obj).path)));
| 1,559 | 33 | 1,592 |
<methods>public non-sealed void <init>() ,public long contentLength() throws java.io.IOException,public org.hotswap.agent.util.spring.io.resource.Resource createRelative(java.lang.String) throws java.io.IOException,public boolean equals(java.lang.Object) ,public boolean exists() ,public java.io.File getFile() throws java.io.IOException,public java.lang.String getFilename() ,public java.net.URI getURI() throws java.io.IOException,public java.net.URL getURL() throws java.io.IOException,public int hashCode() ,public boolean isOpen() ,public boolean isReadable() ,public long lastModified() throws java.io.IOException,public java.lang.String toString() <variables>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/util/spring/io/resource/InputStreamResource.java
|
InputStreamResource
|
getInputStream
|
class InputStreamResource extends AbstractResource {
private final InputStream inputStream;
private final String description;
private boolean read = false;
/**
* Create a new InputStreamResource.
*
* @param inputStream
* the InputStream to use
*/
public InputStreamResource(InputStream inputStream) {
this(inputStream, "resource loaded through InputStream");
}
/**
* Create a new InputStreamResource.
*
* @param inputStream
* the InputStream to use
* @param description
* where the InputStream comes from
*/
public InputStreamResource(InputStream inputStream, String description) {
if (inputStream == null) {
throw new IllegalArgumentException("InputStream must not be null");
}
this.inputStream = inputStream;
this.description = (description != null ? description : "");
}
/**
* This implementation always returns {@code true}.
*/
@Override
public boolean exists() {
return true;
}
/**
* This implementation always returns {@code true}.
*/
@Override
public boolean isOpen() {
return true;
}
/**
* This implementation throws IllegalStateException if attempting to read
* the underlying stream multiple times.
*/
@Override
public InputStream getInputStream() throws IOException, IllegalStateException {<FILL_FUNCTION_BODY>}
/**
* This implementation returns a description that includes the passed-in
* description, if any.
*/
@Override
public String getDescription() {
return "InputStream resource [" + this.description + "]";
}
/**
* This implementation compares the underlying InputStream.
*/
@Override
public boolean equals(Object obj) {
return (obj == this || (obj instanceof InputStreamResource && ((InputStreamResource) obj).inputStream.equals(this.inputStream)));
}
/**
* This implementation returns the hash code of the underlying InputStream.
*/
@Override
public int hashCode() {
return this.inputStream.hashCode();
}
}
|
if (this.read) {
throw new IllegalStateException("InputStream has already been read - " + "do not use InputStreamResource if a stream needs to be read multiple times");
}
this.read = true;
return this.inputStream;
| 537 | 64 | 601 |
<methods>public non-sealed void <init>() ,public long contentLength() throws java.io.IOException,public org.hotswap.agent.util.spring.io.resource.Resource createRelative(java.lang.String) throws java.io.IOException,public boolean equals(java.lang.Object) ,public boolean exists() ,public java.io.File getFile() throws java.io.IOException,public java.lang.String getFilename() ,public java.net.URI getURI() throws java.io.IOException,public java.net.URL getURL() throws java.io.IOException,public int hashCode() ,public boolean isOpen() ,public boolean isReadable() ,public long lastModified() throws java.io.IOException,public java.lang.String toString() <variables>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/util/spring/io/resource/NestedExceptionUtils.java
|
NestedExceptionUtils
|
buildMessage
|
class NestedExceptionUtils {
/**
* Build a message for the given base message and root cause.
*
* @param message
* the base message
* @param cause
* the root cause
* @return the full exception message
*/
public static String buildMessage(String message, Throwable cause) {<FILL_FUNCTION_BODY>}
}
|
if (cause != null) {
StringBuilder sb = new StringBuilder();
if (message != null) {
sb.append(message).append("; ");
}
sb.append("nested exception is ").append(cause);
return sb.toString();
} else {
return message;
}
| 100 | 84 | 184 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/util/spring/io/resource/PathResource.java
|
PathResource
|
getInputStream
|
class PathResource extends AbstractResource implements WritableResource {
private final Path path;
/**
* Create a new PathResource from a Path handle.
* <p>
* Note: Unlike {@link FileSystemResource}, when building relative resources
* via {@link #createRelative}, the relative path will be built
* <i>underneath</i> the given root: e.g. Paths.get("C:/dir1/"), relative
* path "dir2" -> "C:/dir1/dir2"!
*
* @param path
* a Path handle
*/
public PathResource(Path path) {
Assert.notNull(path, "Path must not be null");
this.path = path.normalize();
}
/**
* Create a new PathResource from a Path handle.
* <p>
* Note: Unlike {@link FileSystemResource}, when building relative resources
* via {@link #createRelative}, the relative path will be built
* <i>underneath</i> the given root: e.g. Paths.get("C:/dir1/"), relative
* path "dir2" -> "C:/dir1/dir2"!
*
* @param path
* a path
* @see java.nio.file.Paths#get(String, String...)
*/
public PathResource(String path) {
Assert.notNull(path, "Path must not be null");
this.path = Paths.get(path).normalize();
}
/**
* Create a new PathResource from a Path handle.
* <p>
* Note: Unlike {@link FileSystemResource}, when building relative resources
* via {@link #createRelative}, the relative path will be built
* <i>underneath</i> the given root: e.g. Paths.get("C:/dir1/"), relative
* path "dir2" -> "C:/dir1/dir2"!
*
* @see java.nio.file.Paths#get(URI)
* @param uri
* a path URI
*/
public PathResource(URI uri) {
Assert.notNull(uri, "URI must not be null");
this.path = Paths.get(uri).normalize();
}
/**
* Return the file path for this resource.
*/
public final String getPath() {
return this.path.toString();
}
/**
* This implementation returns whether the underlying file exists.
*
* @see org.hotswap.agent.util.spring.io.resource.springframework.core.io.PathResource#exists()
*/
@Override
public boolean exists() {
return Files.exists(this.path);
}
/**
* This implementation checks whether the underlying file is marked as
* readable (and corresponds to an actual file with content, not to a
* directory).
*
* @see java.nio.file.Files#isReadable(Path)
* @see java.nio.file.Files#isDirectory(Path, java.nio.file.LinkOption...)
*/
@Override
public boolean isReadable() {
return (Files.isReadable(this.path) && !Files.isDirectory(this.path));
}
/**
* This implementation opens a InputStream for the underlying file.
*
* @see java.nio.file.spi.FileSystemProvider#newInputStream(Path,
* OpenOption...)
*/
@Override
public InputStream getInputStream() throws IOException {<FILL_FUNCTION_BODY>}
/**
* This implementation returns a URL for the underlying file.
*
* @see java.nio.file.Path#toUri()
* @see java.net.URI#toURL()
*/
@Override
public URL getURL() throws IOException {
return this.path.toUri().toURL();
}
/**
* This implementation returns a URI for the underlying file.
*
* @see java.nio.file.Path#toUri()
*/
@Override
public URI getURI() throws IOException {
return this.path.toUri();
}
/**
* This implementation returns the underlying File reference.
*/
@Override
public File getFile() throws IOException {
try {
return this.path.toFile();
} catch (UnsupportedOperationException ex) {
// only Paths on the default file system can be converted to a File
// do exception translation for cases where conversion is not
// possible
throw new FileNotFoundException(this.path + " cannot be resolved to " + "absolute file path");
}
}
/**
* This implementation returns the underlying File's length.
*/
@Override
public long contentLength() throws IOException {
return Files.size(this.path);
}
/**
* This implementation returns the underlying File's timestamp.
*
* @see java.nio.file.Files#getLastModifiedTime(Path,
* java.nio.file.LinkOption...)
*/
@Override
public long lastModified() throws IOException {
// we can not use the super class method since it uses conversion to a
// File and
// only Paths on the default file system can be converted to a File
return Files.getLastModifiedTime(path).toMillis();
}
/**
* This implementation creates a FileResource, applying the given path
* relative to the path of the underlying file of this resource descriptor.
*
* @see java.nio.file.Path#resolve(String)
*/
@Override
public Resource createRelative(String relativePath) throws IOException {
return new PathResource(this.path.resolve(relativePath));
}
/**
* This implementation returns the name of the file.
*
* @see java.nio.file.Path#getFileName()
*/
@Override
public String getFilename() {
return this.path.getFileName().toString();
}
@Override
public String getDescription() {
return "path [" + this.path.toAbsolutePath() + "]";
}
// implementation of WritableResource
/**
* This implementation checks whether the underlying file is marked as
* writable (and corresponds to an actual file with content, not to a
* directory).
*
* @see java.nio.file.Files#isWritable(Path)
* @see java.nio.file.Files#isDirectory(Path, java.nio.file.LinkOption...)
*/
@Override
public boolean isWritable() {
return Files.isWritable(this.path) && !Files.isDirectory(this.path);
}
/**
* This implementation opens a OutputStream for the underlying file.
*
* @see java.nio.file.spi.FileSystemProvider#newOutputStream(Path,
* OpenOption...)
*/
@Override
public OutputStream getOutputStream() throws IOException {
if (Files.isDirectory(this.path)) {
throw new FileNotFoundException(getPath() + " (is a directory)");
}
return Files.newOutputStream(this.path);
}
/**
* This implementation compares the underlying Path references.
*/
@Override
public boolean equals(Object obj) {
return (this == obj || (obj instanceof PathResource && this.path.equals(((PathResource) obj).path)));
}
/**
* This implementation returns the hash code of the underlying Path
* reference.
*/
@Override
public int hashCode() {
return this.path.hashCode();
}
}
|
if (!exists()) {
throw new FileNotFoundException(getPath() + " (no such file or directory)");
}
if (Files.isDirectory(this.path)) {
throw new FileNotFoundException(getPath() + " (is a directory)");
}
return Files.newInputStream(this.path);
| 1,960 | 82 | 2,042 |
<methods>public non-sealed void <init>() ,public long contentLength() throws java.io.IOException,public org.hotswap.agent.util.spring.io.resource.Resource createRelative(java.lang.String) throws java.io.IOException,public boolean equals(java.lang.Object) ,public boolean exists() ,public java.io.File getFile() throws java.io.IOException,public java.lang.String getFilename() ,public java.net.URI getURI() throws java.io.IOException,public java.net.URL getURL() throws java.io.IOException,public int hashCode() ,public boolean isOpen() ,public boolean isReadable() ,public long lastModified() throws java.io.IOException,public java.lang.String toString() <variables>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/util/spring/io/resource/VfsResource.java
|
VfsResource
|
getURL
|
class VfsResource extends AbstractResource {
private final Object resource;
public VfsResource(Object resource) {
Assert.notNull(resource, "VirtualFile must not be null");
this.resource = resource;
}
@Override
public InputStream getInputStream() throws IOException {
return VfsUtils.getInputStream(this.resource);
}
@Override
public boolean exists() {
return VfsUtils.exists(this.resource);
}
@Override
public boolean isReadable() {
return VfsUtils.isReadable(this.resource);
}
@Override
public URL getURL() throws IOException {<FILL_FUNCTION_BODY>}
@Override
public URI getURI() throws IOException {
try {
return VfsUtils.getURI(this.resource);
} catch (Exception ex) {
throw new NestedIOException("Failed to obtain URI for " + this.resource, ex);
}
}
@Override
public File getFile() throws IOException {
return VfsUtils.getFile(this.resource);
}
@Override
public long contentLength() throws IOException {
return VfsUtils.getSize(this.resource);
}
@Override
public long lastModified() throws IOException {
return VfsUtils.getLastModified(this.resource);
}
@Override
public Resource createRelative(String relativePath) throws IOException {
if (!relativePath.startsWith(".") && relativePath.contains("/")) {
try {
return new VfsResource(VfsUtils.getChild(this.resource, relativePath));
} catch (IOException ex) {
// fall back to getRelative
}
}
return new VfsResource(VfsUtils.getRelative(new URL(getURL(), relativePath)));
}
@Override
public String getFilename() {
return VfsUtils.getName(this.resource);
}
@Override
public String getDescription() {
return "VFS resource [" + this.resource + "]";
}
@Override
public boolean equals(Object obj) {
return (obj == this || (obj instanceof VfsResource && this.resource.equals(((VfsResource) obj).resource)));
}
@Override
public int hashCode() {
return this.resource.hashCode();
}
}
|
try {
return VfsUtils.getURL(this.resource);
} catch (Exception ex) {
throw new NestedIOException("Failed to obtain URL for file " + this.resource, ex);
}
| 603 | 55 | 658 |
<methods>public non-sealed void <init>() ,public long contentLength() throws java.io.IOException,public org.hotswap.agent.util.spring.io.resource.Resource createRelative(java.lang.String) throws java.io.IOException,public boolean equals(java.lang.Object) ,public boolean exists() ,public java.io.File getFile() throws java.io.IOException,public java.lang.String getFilename() ,public java.net.URI getURI() throws java.io.IOException,public java.net.URL getURL() throws java.io.IOException,public int hashCode() ,public boolean isOpen() ,public boolean isReadable() ,public long lastModified() throws java.io.IOException,public java.lang.String toString() <variables>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/util/spring/path/VfsPatternUtils.java
|
VfsPatternUtils
|
visit
|
class VfsPatternUtils extends VfsUtils {
static Object getVisitorAttribute() {
return doGetVisitorAttribute();
}
static String getPath(Object resource) {
return doGetPath(resource);
}
static Object findRoot(URL url) throws IOException {
return getRoot(url);
}
static void visit(Object resource, InvocationHandler visitor) throws IOException {<FILL_FUNCTION_BODY>}
}
|
Object visitorProxy = Proxy.newProxyInstance(VIRTUAL_FILE_VISITOR_INTERFACE.getClassLoader(), new Class<?>[] { VIRTUAL_FILE_VISITOR_INTERFACE }, visitor);
invokeVfsMethod(VIRTUAL_FILE_METHOD_VISIT, resource, visitorProxy);
| 116 | 89 | 205 |
<methods>public non-sealed void <init>() ,public static boolean exists(java.lang.Object) ,public static T getChild(java.lang.Object, java.lang.String) throws java.io.IOException,public static java.io.File getFile(java.lang.Object) throws java.io.IOException,public static java.io.InputStream getInputStream(java.lang.Object) throws java.io.IOException,public static long getLastModified(java.lang.Object) throws java.io.IOException,public static java.lang.String getName(java.lang.Object) ,public static T getRelative(java.net.URL) throws java.io.IOException,public static T getRoot(java.net.URI) throws java.io.IOException,public static T getRoot(java.net.URL) throws java.io.IOException,public static long getSize(java.lang.Object) throws java.io.IOException,public static java.net.URI getURI(java.lang.Object) throws java.io.IOException,public static java.net.URL getURL(java.lang.Object) throws java.io.IOException,public static boolean isReadable(java.lang.Object) <variables>private static java.lang.reflect.Method GET_PHYSICAL_FILE,private static final org.hotswap.agent.logging.AgentLogger LOGGER,private static final java.lang.String VFS3_PKG,private static java.lang.reflect.Method VFS_METHOD_GET_ROOT_URI,private static java.lang.reflect.Method VFS_METHOD_GET_ROOT_URL,private static final java.lang.String VFS_NAME,private static java.lang.reflect.Method VIRTUAL_FILE_METHOD_EXISTS,private static java.lang.reflect.Method VIRTUAL_FILE_METHOD_GET_CHILD,private static java.lang.reflect.Method VIRTUAL_FILE_METHOD_GET_INPUT_STREAM,private static java.lang.reflect.Method VIRTUAL_FILE_METHOD_GET_LAST_MODIFIED,private static java.lang.reflect.Method VIRTUAL_FILE_METHOD_GET_NAME,private static java.lang.reflect.Method VIRTUAL_FILE_METHOD_GET_PATH_NAME,private static java.lang.reflect.Method VIRTUAL_FILE_METHOD_GET_SIZE,private static java.lang.reflect.Method VIRTUAL_FILE_METHOD_TO_URI,private static java.lang.reflect.Method VIRTUAL_FILE_METHOD_TO_URL,protected static java.lang.reflect.Method VIRTUAL_FILE_METHOD_VISIT,protected static Class<?> VIRTUAL_FILE_VISITOR_INTERFACE,private static java.lang.reflect.Field VISITOR_ATTRIBUTES_FIELD_RECURSE,private static volatile boolean initialized
|
HotswapProjects_HotswapAgent
|
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/util/spring/util/PatternMatchUtils.java
|
PatternMatchUtils
|
simpleMatch
|
class PatternMatchUtils {
private final static Map<String, Pattern> patterns = new HashMap<>();
public static boolean regexMatch(String pattern, String str) {
if (StringUtils.isEmpty(pattern)) {
return true;
}
Pattern p = patterns.get(pattern);
if (p == null) {
p = Pattern.compile(pattern);
patterns.put(pattern, p);
}
boolean matched = p.matcher(str).matches();
return matched;
}
/**
* Match a String against the given pattern, supporting the following simple
* pattern styles: "xxx*", "*xxx", "*xxx*" and "xxx*yyy" matches (with an
* arbitrary number of pattern parts), as well as direct equality.
*
* @param pattern
* the pattern to match against
* @param str
* the String to match
* @return whether the String matches the given pattern
*/
public static boolean simpleMatch(String pattern, String str) {<FILL_FUNCTION_BODY>}
/**
* Match a String against the given patterns, supporting the following
* simple pattern styles: "xxx*", "*xxx", "*xxx*" and "xxx*yyy" matches
* (with an arbitrary number of pattern parts), as well as direct equality.
*
* @param patterns
* the patterns to match against
* @param str
* the String to match
* @return whether the String matches any of the given patterns
*/
public static boolean simpleMatch(String[] patterns, String str) {
if (patterns != null) {
for (String pattern : patterns) {
if (simpleMatch(pattern, str)) {
return true;
}
}
}
return false;
}
}
|
if (pattern == null || str == null) {
return false;
}
int firstIndex = pattern.indexOf('*');
if (firstIndex == -1) {
return pattern.equals(str);
}
if (firstIndex == 0) {
if (pattern.length() == 1) {
return true;
}
int nextIndex = pattern.indexOf('*', firstIndex + 1);
if (nextIndex == -1) {
return str.endsWith(pattern.substring(1));
}
String part = pattern.substring(1, nextIndex);
if ("".equals(part)) {
return simpleMatch(pattern.substring(nextIndex), str);
}
int partIndex = str.indexOf(part);
while (partIndex != -1) {
if (simpleMatch(pattern.substring(nextIndex), str.substring(partIndex + part.length()))) {
return true;
}
partIndex = str.indexOf(part, partIndex + 1);
}
return false;
}
return (str.length() >= firstIndex && pattern.substring(0, firstIndex).equals(str.substring(0, firstIndex)) && simpleMatch(pattern.substring(firstIndex), str.substring(firstIndex)));
| 457 | 321 | 778 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/util/spring/util/WeakReferenceMonitor.java
|
MonitoringProcess
|
run
|
class MonitoringProcess implements Runnable {
@Override
public void run() {<FILL_FUNCTION_BODY>}
}
|
logger.debug("Starting reference monitor thread");
// Check if there are any tracked entries left.
while (keepMonitoringThreadAlive()) {
try {
Reference<?> reference = handleQueue.remove();
// Stop tracking this reference.
ReleaseListener entry = removeEntry(reference);
if (entry != null) {
// Invoke listener callback.
try {
entry.released();
} catch (Throwable ex) {
logger.warning("Reference release listener threw exception", ex);
}
}
} catch (InterruptedException ex) {
synchronized (WeakReferenceMonitor.class) {
monitoringThread = null;
}
logger.debug("Reference monitor thread interrupted", ex);
break;
}
}
| 37 | 192 | 229 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/versions/ArtifactVersion.java
|
ArtifactVersion
|
parseVersion
|
class ArtifactVersion implements Comparable<ArtifactVersion> {
/** The version. */
private final String version;
/** The major version. */
private Integer majorVersion;
/** The minor version. */
private Integer minorVersion;
/** The incremental version. */
private Integer incrementalVersion;
/** The build number. */
private Integer buildNumber;
/** The qualifier. */
private String qualifier;
/** The comparable. */
private ComparableVersion comparable;
/**
* Instantiates a new artifact version.
*
* @param version the version
*/
public ArtifactVersion(String version) {
this.version = version != null ? version.trim() : "";
parseVersion(version);
}
/**
* Gets the version.
*
* @return the version
*/
public String getVersion() {
return version;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return 11 + comparable.hashCode();
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof ArtifactVersion)) {
return false;
}
return compareTo(ArtifactVersion.class.cast(other)) == 0;
}
/* (non-Javadoc)
* @see java.lang.Comparable#compareTo(java.lang.Object)
*/
public int compareTo(ArtifactVersion otherVersion) {
return this.comparable.compareTo(otherVersion.comparable);
}
/**
* Gets the major version.
*
* @return the major version
*/
public int getMajorVersion() {
return majorVersion != null ? majorVersion : 0;
}
/**
* Gets the minor version.
*
* @return the minor version
*/
public int getMinorVersion() {
return minorVersion != null ? minorVersion : 0;
}
/**
* Gets the incremental version.
*
* @return the incremental version
*/
public int getIncrementalVersion() {
return incrementalVersion != null ? incrementalVersion : 0;
}
/**
* Gets the builds the number.
*
* @return the builds the number
*/
public int getBuildNumber() {
return buildNumber != null ? buildNumber : 0;
}
/**
* Gets the qualifier.
*
* @return the qualifier
*/
public String getQualifier() {
return qualifier;
}
/**
* Parses the version.
*
* @param version the version
*/
public final void parseVersion(String version) {<FILL_FUNCTION_BODY>}
/**
* Gets the next integer token.
*
* @param tok the tok
* @return the next integer token
*/
private static Integer getNextIntegerToken(StringTokenizer tok) {
try {
String s = tok.nextToken();
if ((s.length() > 1) && s.startsWith("0")) {
throw new NumberFormatException("Number part has a leading 0: '" + s + "'");
}
return Integer.valueOf(s);
} catch (NoSuchElementException e) {
throw new NumberFormatException("Number is invalid");
}
}
/**
* Dump.
*
* @return the string
*/
public String dump() {
return "ArtifactVersion [version=" + version + ", majorVersion=" + majorVersion + ", minorVersion=" + minorVersion + ", incrementalVersion=" + incrementalVersion + ", buildNumber=" + buildNumber + ", qualifier=" + qualifier + ", comparable=" + comparable + "]";
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return comparable.toString();
}
}
|
comparable = new ComparableVersion(version);
int index = version.indexOf("-");
String part1;
String part2 = null;
if (index < 0) {
part1 = version;
} else {
part1 = version.substring(0, index);
part2 = version.substring(index + 1);
}
if (part2 != null) {
try {
if ((part2.length() == 1) || !part2.startsWith("0")) {
buildNumber = Integer.valueOf(part2);
} else {
qualifier = part2;
}
} catch (NumberFormatException e) {
qualifier = part2;
}
}
if ((!part1.contains(".")) && !part1.startsWith("0")) {
try {
majorVersion = Integer.valueOf(part1);
} catch (NumberFormatException e) {
// qualifier is the whole version, including "-"
qualifier = version;
buildNumber = null;
}
} else {
boolean fallback = false;
StringTokenizer tok = new StringTokenizer(part1, ".");
try {
majorVersion = getNextIntegerToken(tok);
if (tok.hasMoreTokens()) {
minorVersion = getNextIntegerToken(tok);
}
if (tok.hasMoreTokens()) {
incrementalVersion = getNextIntegerToken(tok);
}
if (tok.hasMoreTokens()) {
qualifier = tok.nextToken();
fallback = Pattern.compile("\\d+").matcher(qualifier).matches();
}
// string tokenzier won't detect these and ignores them
if (part1.contains("..") || part1.startsWith(".") || part1.endsWith(".")) {
fallback = true;
}
} catch (NumberFormatException e) {
fallback = true;
}
if (fallback) {
// qualifier is the whole version, including "-"
qualifier = version;
majorVersion = null;
minorVersion = null;
incrementalVersion = null;
buildNumber = null;
}
}
| 1,097 | 563 | 1,660 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/versions/ComparableVersion.java
|
ListItem
|
main
|
class ListItem extends ArrayList<Item>implements Item {
/** The Constant serialVersionUID. */
private static final long serialVersionUID = 1L;
/* (non-Javadoc)
* @see org.hotswap.agent.versions.ComparableVersion.Item#getType()
*/
public int getType() {
return LIST_ITEM;
}
/* (non-Javadoc)
* @see org.hotswap.agent.versions.ComparableVersion.Item#isNull()
*/
public boolean isNull() {
return (size() == 0);
}
/**
* Normalize.
*/
void normalize() {
for (int i = size() - 1; i >= 0; i--) {
Item lastItem = get(i);
if (lastItem.isNull()) {
// remove null trailing items: 0, "", empty list
remove(i);
} else if (!(lastItem instanceof ListItem)) {
break;
}
}
}
/* (non-Javadoc)
* @see org.hotswap.agent.versions.ComparableVersion.Item#compareTo(org.hotswap.agent.versions.ComparableVersion.Item)
*/
public int compareTo(Item item) {
if (item == null) {
if (size() == 0) {
return 0; // 1-0 = 1- (normalize) = 1
}
Item first = get(0);
return first.compareTo(null);
}
switch (item.getType()) {
case INTEGER_ITEM:
return -1; // 1-1 < 1.0.x
case STRING_ITEM:
return 1; // 1-1 > 1-sp
case LIST_ITEM:
Iterator<Item> left = iterator();
Iterator<Item> right = ((ListItem) item).iterator();
while (left.hasNext() || right.hasNext()) {
Item l = left.hasNext() ? left.next() : null;
Item r = right.hasNext() ? right.next() : null;
// if this is shorter, then invert the compare and mul with
// -1
int result = l == null ? (r == null ? 0 : -1 * r.compareTo(l)) : l.compareTo(r);
if (result != 0) {
return result;
}
}
return 0;
default:
throw new RuntimeException("invalid item: " + item.getClass());
}
}
/* (non-Javadoc)
* @see java.util.AbstractCollection#toString()
*/
public String toString() {
StringBuilder buffer = new StringBuilder();
for (Item item : this) {
if (buffer.length() > 0) {
buffer.append((item instanceof ListItem) ? '-' : '.');
}
buffer.append(item);
}
return buffer.toString();
}
}
/**
* Instantiates a new comparable version.
*
* @param version the version
*/
public ComparableVersion(String version) {
parseVersion(version);
}
/**
* Parses the version.
*
* @param version the version
*/
public final void parseVersion(String version) {
this.value = version;
items = new ListItem();
version = version.toLowerCase(Locale.ENGLISH);
ListItem list = items;
Stack<Item> stack = new Stack<>();
stack.push(list);
boolean isDigit = false;
int startIndex = 0;
for (int i = 0; i < version.length(); i++) {
char c = version.charAt(i);
if (c == '.') {
if (i == startIndex) {
list.add(IntegerItem.ZERO);
} else {
list.add(parseItem(isDigit, version.substring(startIndex, i)));
}
startIndex = i + 1;
} else if (c == '-') {
if (i == startIndex) {
list.add(IntegerItem.ZERO);
} else {
list.add(parseItem(isDigit, version.substring(startIndex, i)));
}
startIndex = i + 1;
list.add(list = new ListItem());
stack.push(list);
} else if (Character.isDigit(c)) {
if (!isDigit && i > startIndex) {
list.add(new StringItem(version.substring(startIndex, i), true));
startIndex = i;
list.add(list = new ListItem());
stack.push(list);
}
isDigit = true;
} else {
if (isDigit && i > startIndex) {
list.add(parseItem(true, version.substring(startIndex, i)));
startIndex = i;
list.add(list = new ListItem());
stack.push(list);
}
isDigit = false;
}
}
if (version.length() > startIndex) {
list.add(parseItem(isDigit, version.substring(startIndex)));
}
while (!stack.isEmpty()) {
list = (ListItem) stack.pop();
list.normalize();
}
canonical = items.toString();
}
/**
* Parses the item.
*
* @param isDigit the is digit
* @param buf the buf
* @return the item
*/
private static Item parseItem(boolean isDigit, String buf) {
return isDigit ? new IntegerItem(buf) : new StringItem(buf, false);
}
/* (non-Javadoc)
* @see java.lang.Comparable#compareTo(java.lang.Object)
*/
public int compareTo(ComparableVersion o) {
return items.compareTo(o.items);
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
public String toString() {
return value;
}
/**
* Gets the canonical.
*
* @return the canonical
*/
public String getCanonical() {
return canonical;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
public boolean equals(Object o) {
return (o instanceof ComparableVersion) && canonical.equals(ComparableVersion.class.cast(o).canonical);
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
public int hashCode() {
return canonical.hashCode();
}
/**
* Main to test version parsing and comparison.
*
* @param args
* the version strings to parse and compare
*/
public static void main(String... args) {<FILL_FUNCTION_BODY>
|
System.out.println("Display parameters as parsed by Maven (in canonical form) and comparison result:");
if (args.length == 0) {
return;
}
ComparableVersion prev = null;
int i = 1;
for (String version : args) {
ComparableVersion c = new ComparableVersion(version);
if (prev != null) {
int compare = prev.compareTo(c);
System.out.println(" " + prev.toString() + ' ' + ((compare == 0) ? "==" : ((compare < 0) ? "<" : ">")) + ' ' + version);
}
System.out.println(String.valueOf(i++) + ". " + version + " == " + c.getCanonical());
prev = c;
}
| 1,836 | 207 | 2,043 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/versions/ManifestInfo.java
|
ManifestInfo
|
equals
|
class ManifestInfo {
/** The mf. */
private final Manifest mf;
/** The attr. */
private final Attributes attr;
/** The main. */
private final Attributes main;
private final Map<String, Attributes> entries;
/**
* Instantiates a new manifest info.
*
* @param mf the mf
*/
public ManifestInfo(Manifest mf) {
this.mf = mf;
if (mf != null) {
attr = mf.getAttributes("");
main = mf.getMainAttributes();
entries = mf.getEntries();
} else {
attr = null;
main = null;
entries = null;
}
}
/**
* Checks if is empty.
*
* @return true, if is empty
*/
public boolean isEmpty() {
return mf == null || ((attr == null || attr.size() == 0) && (main == null || main.size() == 0));
}
/**
* Gets the value.
*
* @param name the name
* @return the value
*/
public String getValue(Name... name) {
if (name == null || isEmpty()) {
return null;
}
return getAttribute(attr, main, entries, name);
}
/**
* Gets the value.
*
* @param path the path
* @param name the name
* @return the value
*/
public String getValue(String path, Name... name) {
if (name == null || isEmpty()) {
return null;
}
return getAttribute(StringUtils.isEmpty(path) ? attr : mf.getAttributes(path), main, entries, name);
}
/**
* Gets the attribute.
*
* @param attr the attr
* @param main the main
* @param names the names
* @return the attribute
*/
private static String getAttribute(Attributes attr, Attributes main, Map<String, Attributes> entries, Name... names) {
if (names == null || names.length == 0) {
return null;
}
String ret = getAttributeByName(main, names);
if (ret != null) {
return ret;
}
ret = getAttributeByName(attr, names);
if (ret != null) {
return ret;
}
if (entries != null) {
for (Iterator<Map.Entry<String, Attributes>> it = entries.entrySet().iterator();it.hasNext();) {
Map.Entry<String, Attributes> entry = it.next();
ret = getAttributeByName(entry.getValue(), names);
if (ret != null) {
return ret;
}
}
}
return null;
}
private static String getAttributeByName(Attributes attr, Name... names) {
if (attr != null) {
String value;
for (Name name : names) {
value = attr.getValue(name);
if (value != null && !value.isEmpty()) {
return value;
}
}
}
return null;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {<FILL_FUNCTION_BODY>}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((mf == null) ? 0 : mf.hashCode());
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
if (mf != null) {
return "ManifestInfo [" + ManifestMiniDumper.dump(mf.getMainAttributes()) + ", entries:" + mf.getEntries() + "]";
} else {
return "ManifestInfo [null]";
}
}
// public static String dump(Attributes a) {
// if(a == null) {
// return "null";
// }
// StringBuilder sb = new StringBuilder();
// for(Map.Entry<Object,Object> e: a.entrySet()){
// sb.append("[").append(e.getKey()).append("=").append(e.getValue()).append("],");
// }
// return sb.toString();
// }
}
|
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
ManifestInfo other = (ManifestInfo) obj;
if (mf == null) {
if (other.mf != null) {
return false;
}
} else if (!mf.equals(other.mf)) {
return false;
}
return true;
| 1,196 | 131 | 1,327 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/versions/ManifestMiniDumper.java
|
ManifestMiniDumper
|
getAttribute
|
class ManifestMiniDumper {
/**
* <code>Name</code> object for <code>Extension-List</code> manifest
* attribute used for declaring dependencies on installed extensions.
*
* @see <a href=
* "../../../../technotes/guides/extensions/spec.html#dependency">
* Installed extension dependency</a>
*/
public static final Name EXTENSION_LIST = new Name("Extension-List");
/**
* <code>Name</code> object for <code>Extension-Name</code> manifest
* attribute used for declaring dependencies on installed extensions.
*
* @see <a href=
* "../../../../technotes/guides/extensions/spec.html#dependency">
* Installed extension dependency</a>
*/
public static final Name EXTENSION_NAME = new Name("Extension-Name");
/**
* <code>Name</code> object for <code>Implementation-Title</code> manifest
* attribute used for package versioning.
*
* @see <a href=
* "../../../../technotes/guides/versioning/spec/versioning2.html#wp90779">
* Java Product Versioning Specification</a>
*/
public static final Name IMPLEMENTATION_TITLE = new Name("Implementation-Title");
/**
* <code>Name</code> object for <code>Implementation-Version</code> manifest
* attribute used for package versioning.
*
* @see <a href=
* "../../../../technotes/guides/versioning/spec/versioning2.html#wp90779">
* Java Product Versioning Specification</a>
*/
public static final Name IMPLEMENTATION_VERSION = new Name("Implementation-Version");
/**
* <code>Name</code> object for <code>Implementation-Vendor</code> manifest
* attribute used for package versioning.
*
* @see <a href=
* "../../../../technotes/guides/versioning/spec/versioning2.html#wp90779">
* Java Product Versioning Specification</a>
*/
public static final Name IMPLEMENTATION_VENDOR = new Name("Implementation-Vendor");
/**
* <code>Name</code> object for <code>Implementation-Vendor-Id</code>
* manifest attribute used for package versioning. Extension mechanism will
* be removed in a future release. Use class path instead.
*
* @see <a href=
* "../../../../technotes/guides/extensions/versioning.html#applet">
* Optional Package Versioning</a>
*/
public static final Name IMPLEMENTATION_VENDOR_ID = new Name("Implementation-Vendor-Id");
/**
* <code>Name</code> object for <code>Specification-Version</code> manifest
* attribute used for package versioning.
*
* @see <a href=
* "../../../../technotes/guides/versioning/spec/versioning2.html#wp90779">
* Java Product Versioning Specification</a>
*/
public static final Name SPECIFICATION_VERSION = new Name("Specification-Version");
/**
* <code>Name</code> object for <code>Specification-Vendor</code> manifest
* attribute used for package versioning.
*
* @see <a href=
* "../../../../technotes/guides/versioning/spec/versioning2.html#wp90779">
* Java Product Versioning Specification</a>
*/
public static final Name SPECIFICATION_VENDOR = new Name("Specification-Vendor");
/**
* <code>Name</code> object for <code>Specification-Title</code> manifest
* attribute used for package versioning.
*
* @see <a href=
* "../../../../technotes/guides/versioning/spec/versioning2.html#wp90779">
* Java Product Versioning Specification</a>
*/
public static final Name SPECIFICATION_TITLE = new Name("Specification-Title");
/** The Constant BUNDLE_SYMBOLIC_NAME. */
// Bundle-SymbolicName: javax.servlet-api
public static final Name BUNDLE_SYMBOLIC_NAME = new Name("Bundle-SymbolicName");
/** The Constant BUNDLE_NAME. */
// Bundle-Name: Java Servlet API
public static final Name BUNDLE_NAME = new Name("Bundle-Name");
/** The Constant BUNDLE_VERSION. */
// Bundle-Version: 2.2.9
public static final Name BUNDLE_VERSION = new Name("Bundle-Version");
/** The Constant VERSIONS. */
public static final Name[] VERSIONS = new Name[] { BUNDLE_VERSION, IMPLEMENTATION_VERSION, SPECIFICATION_VENDOR };
/** The Constant PACKAGE. */
public static final Name[] PACKAGE = new Name[] { BUNDLE_SYMBOLIC_NAME, IMPLEMENTATION_VENDOR_ID, SPECIFICATION_VENDOR };
/** The Constant TITLE. */
public static final Name[] TITLE = new Name[] { BUNDLE_NAME, IMPLEMENTATION_TITLE, SPECIFICATION_VENDOR };
/**
* Dump.
*
* @param attr the attr
* @return the string
*/
public static String dump(Attributes attr) {
String version = getAttribute(attr, null, VERSIONS);
String pack = getAttribute(attr, null, PACKAGE);
String title = getAttribute(attr, null, TITLE);
return "version=" + version + ", package=" + pack + ", title=" + title;
}
/**
* Gets the attribute.
*
* @param main the main
* @param attr the attr
* @param names the names
* @return the attribute
*/
private static String getAttribute(Attributes main, Attributes attr, Name... names) {<FILL_FUNCTION_BODY>}
}
|
if (names == null) {
return null;
}
if (main != null) {
String value;
for (Name name : names) {
value = main.getValue(name);
if (value != null && !value.isEmpty()) {
return value;
}
}
}
if (attr != null) {
String value;
for (Name name : names) {
value = attr.getValue(name);
if (value != null && !value.isEmpty()) {
return value;
}
}
}
return null;
| 1,616 | 155 | 1,771 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/versions/MavenInfo.java
|
MavenInfo
|
hashCode
|
class MavenInfo {
/** The group id. */
private final String groupId;
/** The artifact id. */
private final String artifactId;
/** The version. */
private final ArtifactVersion version;
/**
* Instantiates a new maven info.
*
* @param groupId the group id
* @param artifactId the artifact id
* @param version the version
*/
public MavenInfo(String groupId, String artifactId, String version) {
super();
this.groupId = groupId;
this.artifactId = artifactId;
this.version = new ArtifactVersion(version);
}
/**
* Gets the artifact id.
*
* @return the artifact id
*/
public String getArtifactId() {
return artifactId;
}
/**
* Gets the group id.
*
* @return the group id
*/
public String getGroupId() {
return groupId;
}
/**
* Gets the version.
*
* @return the version
*/
public ArtifactVersion getVersion() {
return version;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
MavenInfo other = (MavenInfo) obj;
if (artifactId == null) {
if (other.artifactId != null) {
return false;
}
} else if (!artifactId.equals(other.artifactId)) {
return false;
}
if (groupId == null) {
if (other.groupId != null) {
return false;
}
} else if (!groupId.equals(other.groupId)) {
return false;
}
if (version == null) {
if (other.version != null) {
return false;
}
} else if (!version.equals(other.version)) {
return false;
}
return true;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {<FILL_FUNCTION_BODY>}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "MavenInfo [groupId=" + groupId + ", artifactId=" + artifactId + ", version=" + version + "]";
}
}
|
final int prime = 31;
int result = 1;
result = prime * result + ((artifactId == null) ? 0 : artifactId.hashCode());
result = prime * result + ((groupId == null) ? 0 : groupId.hashCode());
result = prime * result + ((version == null) ? 0 : version.hashCode());
return result;
| 708 | 92 | 800 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/versions/Restriction.java
|
Restriction
|
hashCode
|
class Restriction {
/** The lower bound. */
private final ArtifactVersion lowerBound;
/** The lower bound inclusive. */
private final boolean lowerBoundInclusive;
/** The upper bound. */
private final ArtifactVersion upperBound;
/** The upper bound inclusive. */
private final boolean upperBoundInclusive;
/** The Constant EVERYTHING. */
public static final Restriction EVERYTHING = new Restriction(null, false, null, false);
/** The Constant NONE. */
public static final Restriction NONE = new Restriction(new ArtifactVersion("0"), true, new ArtifactVersion(String.valueOf(Integer.MAX_VALUE)), true);
/**
* Instantiates a new restriction.
*
* @param lowerBound the lower bound
* @param lowerBoundInclusive the lower bound inclusive
* @param upperBound the upper bound
* @param upperBoundInclusive the upper bound inclusive
*/
public Restriction(ArtifactVersion lowerBound, boolean lowerBoundInclusive, ArtifactVersion upperBound, boolean upperBoundInclusive) {
this.lowerBound = lowerBound;
this.lowerBoundInclusive = lowerBoundInclusive;
this.upperBound = upperBound;
this.upperBoundInclusive = upperBoundInclusive;
}
/**
* Gets the lower bound.
*
* @return the lower bound
*/
public ArtifactVersion getLowerBound() {
return lowerBound;
}
/**
* Checks if is lower bound inclusive.
*
* @return true, if is lower bound inclusive
*/
public boolean isLowerBoundInclusive() {
return lowerBoundInclusive;
}
/**
* Gets the upper bound.
*
* @return the upper bound
*/
public ArtifactVersion getUpperBound() {
return upperBound;
}
/**
* Checks if is upper bound inclusive.
*
* @return true, if is upper bound inclusive
*/
public boolean isUpperBoundInclusive() {
return upperBoundInclusive;
}
/**
* Contains version.
*
* @param version the version
* @return true, if successful
*/
public boolean containsVersion(ArtifactVersion version) {
if (lowerBound != null) {
int comparison = lowerBound.compareTo(version);
if ((comparison == 0) && !lowerBoundInclusive) {
return false;
}
if (comparison > 0) {
return false;
}
}
if (upperBound != null) {
int comparison = upperBound.compareTo(version);
if ((comparison == 0) && !upperBoundInclusive) {
return false;
}
if (comparison < 0) {
return false;
}
}
return true;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {<FILL_FUNCTION_BODY>}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof Restriction)) {
return false;
}
Restriction restriction = (Restriction) other;
if (lowerBound != null) {
if (!lowerBound.equals(restriction.lowerBound)) {
return false;
}
} else if (restriction.lowerBound != null) {
return false;
}
if (lowerBoundInclusive != restriction.lowerBoundInclusive) {
return false;
}
if (upperBound != null) {
if (!upperBound.equals(restriction.upperBound)) {
return false;
}
} else if (restriction.upperBound != null) {
return false;
}
return upperBoundInclusive == restriction.upperBoundInclusive;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
public String toString() {
StringBuilder buf = new StringBuilder();
buf.append(isLowerBoundInclusive() ? "[" : "(");
if (getLowerBound() != null) {
buf.append(getLowerBound().toString());
}
buf.append(",");
if (getUpperBound() != null) {
buf.append(getUpperBound().toString());
}
buf.append(isUpperBoundInclusive() ? "]" : ")");
return buf.toString();
}
}
|
int result = 13;
if (lowerBound == null) {
result += 1;
} else {
result += lowerBound.hashCode();
}
result *= lowerBoundInclusive ? 1 : 2;
if (upperBound == null) {
result -= 3;
} else {
result -= upperBound.hashCode();
}
result *= upperBoundInclusive ? 2 : 3;
return result;
| 1,200 | 123 | 1,323 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/versions/matcher/AbstractMatcher.java
|
AbstractMatcher
|
matches
|
class AbstractMatcher implements VersionMatcher{
/** The logger. */
protected AgentLogger LOGGER = AgentLogger.getLogger(getClass());
/** The matchers. */
protected final List<VersionMatcher> matchers = new ArrayList<>();
/** The should apply. */
protected boolean shouldApply = Boolean.FALSE;
/**
* Instantiates a new abstract matcher.
*
* @param versions the versions
*/
public AbstractMatcher(Versions versions) {
if(versions == null) {
return;
}
Maven[] maven = versions.maven();
Manifest[] manifest = versions.manifest();
if (maven != null) {
for (Maven cfg : maven) {
try {
MavenMatcher m = new MavenMatcher(cfg);
if (m.isApply()) {
matchers.add(m);
shouldApply = true;
}
} catch (InvalidVersionSpecificationException e) {
LOGGER.error("Unable to parse Maven info for {}", e, cfg);
}
}
}
if (manifest != null) {
for (Manifest cfg : manifest) {
try {
ManifestMatcher m = new ManifestMatcher(cfg);
if (m.isApply()) {
matchers.add(m);
shouldApply = true;
}
} catch (InvalidVersionSpecificationException e) {
LOGGER.error("Unable to parse Manifest info for {}", e, cfg);
}
}
}
}
/* (non-Javadoc)
* @see org.hotswap.agent.config.ArtifactMatcher#isApply()
*/
@Override
public boolean isApply() {
return shouldApply;
}
/* (non-Javadoc)
* @see org.hotswap.agent.config.ArtifactMatcher#matches(org.hotswap.agent.versions.DeploymentInfo)
*/
@Override
public VersionMatchResult matches(DeploymentInfo info) {<FILL_FUNCTION_BODY>}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "AbstractMatcher [matchers=" + matchers + ", shouldApply=" + shouldApply + "]";
}
}
|
if (matchers.size() == 0) {
return VersionMatchResult.SKIPPED;
}
for (VersionMatcher m : matchers) {
VersionMatchResult result = m.matches(info);
if(VersionMatchResult.MATCHED.equals(result)) {
LOGGER.debug("Matched:{}", m);
return VersionMatchResult.MATCHED;
}else if(VersionMatchResult.REJECTED.equals(result)) {
LOGGER.debug("Rejected:{}", m);
return VersionMatchResult.REJECTED;
}
}
// There were matchers, none succeeded
LOGGER.debug("Rejected: Matchers existed, none matched!");
return VersionMatchResult.REJECTED;
| 620 | 198 | 818 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/versions/matcher/ManifestMatcher.java
|
ManifestMatcher
|
match
|
class ManifestMatcher implements VersionMatcher {
private static AgentLogger LOGGER = AgentLogger.getLogger(ManifestMatcher.class);
/** The included versions range */
private final VersionRange includes;
/** The excluded versions range */
private final VersionRange excludes;
/** The properties. */
private final Map<Name, String> properties;
/** The includes string. */
private final String includesString;
/** The excludes string. */
private final String excludesString;
/** The version. */
private final Name[] version;
/**
* Instantiates a new manifest matcher.
*
* @param cfg the cfg
* @throws InvalidVersionSpecificationException the invalid version specification exception
*/
public ManifestMatcher(Manifest cfg) throws InvalidVersionSpecificationException {
if (StringUtils.hasText(cfg.value())) {
this.includesString = cfg.value().trim();
this.includes = VersionRange.createFromVersionSpec(includesString);
} else {
this.includes = null;
this.includesString = null;
}
if (StringUtils.hasText(cfg.excludeVersion())) {
this.excludesString = cfg.excludeVersion().trim();
this.excludes = VersionRange.createFromVersionSpec(excludesString);
} else {
this.excludes = null;
this.excludesString = null;
}
if(cfg.versionName() == null || cfg.versionName().length == 0) {
version = null;
} else {
List<Name >versions = new ArrayList<>();
for(String versionName: cfg.versionName()) {
if (StringUtils.hasText(versionName)) {
versions.add(new Name(versionName));
}
}
version = versions.toArray(new Name[versions.size()]);
}
if (cfg.names() != null && cfg.names().length > 0) {
this.properties = new HashMap<>();
for (org.hotswap.agent.annotation.Name name : cfg.names()) {
if(StringUtils.hasText(name.key()) && StringUtils.hasText(name.value())) {
this.properties.put(new Name(name.key()), name.value());
}
}
} else {
this.properties = Collections.emptyMap();
}
}
/**
* Gets the included versions range
*
* @return the included versions range
*/
public VersionRange getIncludes() {
return includes;
}
/**
* Gets the excluded versions range
*
* @return the excluded versions range
*/
public VersionRange getExcludes() {
return excludes;
}
/**
* Gets the properties.
*
* @return the properties
*/
public Map<Name, String> getProperties() {
return properties;
}
/* (non-Javadoc)
* @see org.hotswap.agent.config.ArtifactMatcher#matches(org.hotswap.agent.versions.DeploymentInfo)
*/
public VersionMatchResult matches(DeploymentInfo info) {
// Skip if no manifest configuration
if(info.getManifest() == null || info.getManifest().size() == 0) {
return VersionMatchResult.SKIPPED;
}
for (ManifestInfo manifest: info.getManifest()) {
VersionMatchResult result = match(manifest);
if(VersionMatchResult.MATCHED.equals(result)){
LOGGER.debug("Matched {} with {}", this, manifest);
return VersionMatchResult.MATCHED;
}
if(VersionMatchResult.REJECTED.equals(result)){
LOGGER.debug("Rejected {} with {}", this, manifest);
return VersionMatchResult.REJECTED;
}
}
// There were no matches (maybe another matcher will pass)
return VersionMatchResult.SKIPPED;
}
/**
* Match.
*
* @param manifest the manifest
* @return the version match result
*/
private VersionMatchResult match(ManifestInfo manifest) {<FILL_FUNCTION_BODY>}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "ManifestMatcher [properties=" + properties + ", includes=" + includes + ", excludes=" + excludes + "]";
}
/* (non-Javadoc)
* @see org.hotswap.agent.config.ArtifactMatcher#isApply()
*/
@Override
public boolean isApply() {
return (StringUtils.hasText(includesString) || StringUtils.hasText(excludesString)) && (version != null);
}
}
|
if(manifest == null) {
return VersionMatchResult.SKIPPED;
}
// We need a version...
String artifactVersion = manifest.getValue(this.version);
if(StringUtils.isEmpty(artifactVersion)){
return VersionMatchResult.SKIPPED;
}
// if no properties, then skip
if(properties.size() == 0) {
return VersionMatchResult.SKIPPED;
} else {
for(Map.Entry<Name,String> e: properties.entrySet()) {
String v = manifest.getValue(e.getKey());
// ALL patterns MUST match, else skip
if(!StringUtils.hasText(v) || !PatternMatchUtils.regexMatch(e.getValue(), v)) {
return VersionMatchResult.SKIPPED;
}
}
}
ArtifactVersion version = new ArtifactVersion(artifactVersion);
if(excludes != null && excludes.containsVersion(version)) {
return VersionMatchResult.REJECTED;
}
if(includes != null && !includes.containsVersion(version)) {
return VersionMatchResult.REJECTED;
} else {
return VersionMatchResult.MATCHED;
}
| 1,251 | 313 | 1,564 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/versions/matcher/MavenMatcher.java
|
MavenMatcher
|
matches
|
class MavenMatcher implements VersionMatcher {
private static AgentLogger LOGGER = AgentLogger.getLogger(MavenMatcher.class);
/** The included versions. */
private final VersionRange includes;
/** The excluded versions. */
private final VersionRange excludes;
/** The artifact id. */
private final String artifactId;
/** The group id. */
private final String groupId;
/** The include versions as string. */
private final String includesString;
/** The exclude versions as string. */
private final String excludesString;
/**
* Instantiates a new maven matcher.
*
* @param cfg the Maven annotation
* @throws InvalidVersionSpecificationException the invalid version specification exception
*/
public MavenMatcher(Maven cfg) throws InvalidVersionSpecificationException {
this.artifactId = cfg.artifactId();
this.groupId = cfg.groupId();
if(StringUtils.hasText(cfg.value())) {
this.includesString = cfg.value().trim();
this.includes = VersionRange.createFromVersionSpec(includesString);
} else {
this.includes = null;
this.includesString = null;
}
if(StringUtils.hasText(cfg.excludeVersion())){
this.excludesString = cfg.excludeVersion().trim();
this.excludes = VersionRange.createFromVersionSpec(excludesString);
} else {
this.excludes = null;
this.excludesString = null;
}
}
/**
* Gets the included versions range.
*
* @return the included versions range
*/
public VersionRange getIncludes() {
return includes;
}
/**
* Gets the excluded versions range
*
* @return the excluded versions range
*/
public VersionRange getExcludes() {
return excludes;
}
/**
* Gets the artifact id.
*
* @return the artifact id
*/
public String getArtifactId() {
return artifactId;
}
/**
* Gets the group id.
*
* @return the group id
*/
public String getGroupId() {
return groupId;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "MavenMatcher [groupId=" + groupId + ", artifactId=" + artifactId + ", includes=" + includes
+ ", excludes=" + excludes + "]";
}
/* (non-Javadoc)
* @see org.hotswap.agent.config.ArtifactMatcher#matches(org.hotswap.agent.versions.DeploymentInfo)
*/
@Override
public VersionMatchResult matches(DeploymentInfo info) {<FILL_FUNCTION_BODY>}
/* (non-Javadoc)
* @see org.hotswap.agent.config.ArtifactMatcher#isApply()
*/
@Override
public boolean isApply() {
return (StringUtils.hasText(artifactId) && StringUtils.hasText(groupId)) && (StringUtils.hasText(includesString) || StringUtils.hasText(excludesString));
}
}
|
if(info.getMaven() == null || info.getMaven().size() == 0) {
return VersionMatchResult.SKIPPED;
}
// A jar can carry multiple maven properties.
for (MavenInfo mi : info.getMaven()) {
if (PatternMatchUtils.regexMatch(groupId, mi.getGroupId()) && PatternMatchUtils.regexMatch(artifactId, mi.getArtifactId())) {
if ((includes == null || includes.containsVersion(mi.getVersion())) && (excludes ==null || !excludes.containsVersion(mi.getVersion()))) {
LOGGER.debug("Matched {} with {}", this, mi);
return VersionMatchResult.MATCHED;
}
// If it is explicitly excluded, then false!
if (excludes !=null && excludes.containsVersion(mi.getVersion())) {
LOGGER.debug("Rejected {} with {}", this, mi);
return VersionMatchResult.REJECTED;
}
}
}
// There were no matches (maybe another matcher will pass)
return VersionMatchResult.SKIPPED;
| 806 | 288 | 1,094 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/watch/WatcherFactory.java
|
WatcherFactory
|
getVersion
|
class WatcherFactory {
public static double JAVA_VERSION = getVersion();
static double getVersion() {<FILL_FUNCTION_BODY>}
public static boolean IS_WINDOWS = isWindows();
static boolean isWindows() {
return System.getProperty("os.name").startsWith("Windows");
}
public Watcher getWatcher() throws IOException {
if (JAVA_VERSION >= 1.7) {
if (IS_WINDOWS) {
return new TreeWatcherNIO();
} else {
return new WatcherNIO2();
}
} else {
throw new UnsupportedOperationException("Watcher is implemented only for Java 1.7 (NIO2). " +
"JNotify implementation should be added in the future for older Java version support.");
}
}
}
|
String version = System.getProperty("java.version");
int pos = 0;
boolean decimalPart = false;
for (; pos < version.length(); pos++) {
char c = version.charAt(pos);
if ((c < '0' || c > '9') && c != '.') break;
if (c == '.') {
if (decimalPart) break;
decimalPart = true;
}
}
return Double.parseDouble(version.substring(0, pos));
| 219 | 132 | 351 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/watch/nio/EventDispatcher.java
|
Event
|
run
|
class Event {
/** The event. */
final WatchEvent<Path> event;
/** The path. */
final Path path;
/**
* Instantiates a new event.
*
* @param event
* the event
* @param path
* the path
*/
public Event(WatchEvent<Path> event, Path path) {
super();
this.event = event;
this.path = path;
}
}
/** The map of listeners. This is managed by the watcher service*/
private final Map<Path, List<WatchEventListener>> listeners;
/** The working queue. The event queue is drained and all pending events are added in this list */
private final ArrayList<Event> working = new ArrayList<>();
/** The runnable. */
private Thread runnable = null;
/**
* Instantiates a new event dispatcher.
*
* @param listeners
* the listeners
*/
public EventDispatcher(Map<Path, List<WatchEventListener>> listeners) {
super();
this.listeners = listeners;
}
/** The event queue. */
private final ArrayBlockingQueue<Event> eventQueue = new ArrayBlockingQueue<>(500);
/*
* (non-Javadoc)
*
* @see java.lang.Runnable#run()
*/
@Override
public void run() {<FILL_FUNCTION_BODY>
|
/*
* The algorithm is naive:
* a) work with not processed (in case);
* b) drain the queue
* c) work on newly collected
* d) empty working queue
*/
while (true) {
// finish any pending ones
for (Event e : working) {
callListeners(e.event, e.path);
if (Thread.interrupted()) {
return;
}
Thread.yield();
}
// drain the event queue
eventQueue.drainTo(working);
// work on new events.
for (Event e : working) {
callListeners(e.event, e.path);
if (Thread.interrupted()) {
return;
}
Thread.yield();
}
// crear the working queue.
working.clear();
try {
Thread.sleep(50);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
return;
}
}
| 426 | 300 | 726 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/watch/nio/HotswapWatchFileEvent.java
|
HotswapWatchFileEvent
|
equals
|
class HotswapWatchFileEvent implements WatchFileEvent {
private final WatchEvent<?> event;
private final Path path;
public HotswapWatchFileEvent(WatchEvent<?> event, Path path) {
this.event = event;
this.path = path;
}
@Override
public FileEvent getEventType() {
return toAgentEvent(event.kind());
}
@Override
public URI getURI() {
return path.toUri();
}
@Override
public boolean isFile() {
// return Files.isRegularFile(path); - did not work in some cases
return !isDirectory();
}
@Override
public boolean isDirectory() {
return Files.isDirectory(path);
}
@Override
public String toString() {
return "WatchFileEvent on path " + path + " for event " + event.kind();
}
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
int result = event.hashCode();
result = 31 * result + path.hashCode();
return result;
}
// translate constants between NIO event and ageent event
static FileEvent toAgentEvent(WatchEvent.Kind<?> kind) {
if (kind == ENTRY_CREATE) {
return FileEvent.CREATE;
} else if (kind == ENTRY_MODIFY) {
return FileEvent.MODIFY;
} else if (kind == ENTRY_DELETE) {
return FileEvent.DELETE;
} else {
throw new IllegalArgumentException("Unknown event type " + kind.name());
}
}
}
|
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
HotswapWatchFileEvent that = (HotswapWatchFileEvent) o;
if (!event.equals(that.event)) {
return false;
}
if (!path.equals(that.path)) {
return false;
}
return true;
| 501 | 137 | 638 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/watch/nio/TreeWatcherNIO.java
|
TreeWatcherNIO
|
register
|
class TreeWatcherNIO extends AbstractNIO2Watcher {
private final static WatchEvent.Modifier HIGH;
private final static WatchEvent.Modifier FILE_TREE;
private final static WatchEvent.Modifier[] MODIFIERS;
static {
// try to set high sensitivity
HIGH = getWatchEventModifier("com.sun.nio.file.SensitivityWatchEventModifier","HIGH");
// try to set file tree modifier
FILE_TREE = getWatchEventModifier("com.sun.nio.file.ExtendedWatchEventModifier", "FILE_TREE");
if(FILE_TREE != null) {
MODIFIERS = new WatchEvent.Modifier[] { FILE_TREE, HIGH };
} else {
MODIFIERS = new WatchEvent.Modifier[] { HIGH };
}
}
/**
* Instantiates a new tree watcher nio.
*
* @throws IOException Signals that an I/O exception has occurred.
*/
public TreeWatcherNIO() throws IOException {
super();
}
/**
* Register the given directory with the WatchService.
*
* @param dir the directory to register watch on
* @throws IOException Signals that an I/O exception has occurred.
*/
private void register(Path dir) throws IOException {<FILL_FUNCTION_BODY>}
/**
* Register the given directory, with the
* WatchService. Sub-directories are automatically watched (filesystem supported)
*
* @param dir the dir
* @throws IOException Signals that an I/O exception has occurred.
*/
@Override
protected void registerAll(Path dir) throws IOException {
LOGGER.info("Registering directory {} ", dir);
register(dir);
}
}
|
for(Path p: keys.values()) {
// This may NOT be correct for all cases (ensure resolve will work!)
if(dir.startsWith(p)) {
LOGGER.debug("Path {} watched via {}", dir, p);
return;
}
}
if (FILE_TREE == null) {
LOGGER.debug("WATCHING:ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY - high} {}", dir);
} else {
LOGGER.debug("WATCHING: ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY - fileTree,high {}", dir);
}
final WatchKey key = dir.register(watcher, KINDS, MODIFIERS);
keys.put(key, dir);
| 507 | 221 | 728 |
<methods>public void <init>() throws java.io.IOException,public void addDirectory(java.nio.file.Path) throws java.io.IOException,public synchronized void addEventListener(java.lang.ClassLoader, java.net.URI, org.hotswap.agent.watch.WatchEventListener) ,public void addEventListener(java.lang.ClassLoader, java.net.URL, org.hotswap.agent.watch.WatchEventListener) ,public void closeClassLoader(java.lang.ClassLoader) ,public void run() ,public void stop() <variables>protected static final Kind<?>[] KINDS,protected org.hotswap.agent.logging.AgentLogger LOGGER,protected Map<org.hotswap.agent.watch.WatchEventListener,java.lang.ClassLoader> classLoaderListeners,protected final non-sealed org.hotswap.agent.watch.nio.EventDispatcher dispatcher,protected final non-sealed Map<java.nio.file.WatchKey,java.nio.file.Path> keys,private final Map<java.nio.file.Path,List<org.hotswap.agent.watch.WatchEventListener>> listeners,private java.lang.Thread runner,private volatile boolean stopped,protected java.nio.file.WatchService watcher
|
HotswapProjects_HotswapAgent
|
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/watch/nio/WatcherNIO2.java
|
WatcherNIO2
|
register
|
class WatcherNIO2 extends AbstractNIO2Watcher {
private final static WatchEvent.Modifier HIGH;
static {
HIGH = getWatchEventModifier("com.sun.nio.file.SensitivityWatchEventModifier","HIGH");
}
public WatcherNIO2() throws IOException {
super();
}
@Override
protected void registerAll(final Path dir) throws IOException {
// register directory and sub-directories
LOGGER.debug("Registering directory {}", dir);
Files.walkFileTree(dir, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
register(dir);
return FileVisitResult.CONTINUE;
}
});
}
/**
* Register the given directory with the WatchService
*/
private void register(Path dir) throws IOException {<FILL_FUNCTION_BODY>}
}
|
// try to set high sensitivity
final WatchKey key = HIGH == null ? dir.register(watcher, KINDS) : dir.register(watcher, KINDS, HIGH);
keys.put(key, dir);
| 301 | 63 | 364 |
<methods>public void <init>() throws java.io.IOException,public void addDirectory(java.nio.file.Path) throws java.io.IOException,public synchronized void addEventListener(java.lang.ClassLoader, java.net.URI, org.hotswap.agent.watch.WatchEventListener) ,public void addEventListener(java.lang.ClassLoader, java.net.URL, org.hotswap.agent.watch.WatchEventListener) ,public void closeClassLoader(java.lang.ClassLoader) ,public void run() ,public void stop() <variables>protected static final Kind<?>[] KINDS,protected org.hotswap.agent.logging.AgentLogger LOGGER,protected Map<org.hotswap.agent.watch.WatchEventListener,java.lang.ClassLoader> classLoaderListeners,protected final non-sealed org.hotswap.agent.watch.nio.EventDispatcher dispatcher,protected final non-sealed Map<java.nio.file.WatchKey,java.nio.file.Path> keys,private final Map<java.nio.file.Path,List<org.hotswap.agent.watch.WatchEventListener>> listeners,private java.lang.Thread runner,private volatile boolean stopped,protected java.nio.file.WatchService watcher
|
HotswapProjects_HotswapAgent
|
HotswapAgent/hotswap-agent/src/main/java/org/hotswap/agent/distribution/PluginDocs.java
|
PluginDocs
|
writeMainReadme
|
class PluginDocs {
public static final String TARGET_DIR = "/target/web-sources/";
MarkdownProcessor markdownProcessor = new MarkdownProcessor();
/**
* Generate the docs.
* @param args no arguments necessary.
*/
public static void main(String[] args) {
try {
new PluginDocs().scan();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* From a class definition resolve base URL common for all files in a maven project (project base directory).
*
* @param clazz class to use
* @return base path (e.g. file:/J:/HotswapAgent/HibernatePlugin)
*/
public static String getBaseURL(Class clazz) {
String clazzUrl = clazz.getResource(clazz.getSimpleName() + ".class").toString();
// strip path to the plugin from maven root directory
String classPath = clazz.getName().replace(".", "/");
return clazzUrl.replace("/target/classes/" + classPath, "").replace(".class", "");
}
/**
*
* @throws Exception
*/
public void scan() throws Exception {
StringBuilder html = new StringBuilder();
addHtmlHeader(html);
ClassPathAnnotationScanner scanner = new ClassPathAnnotationScanner(Plugin.class.getName(), new ClassPathScanner());
for (String plugin : scanner.scanPlugins(getClass().getClassLoader(), PluginManager.PLUGIN_PACKAGE.replace(".", "/"))) {
Class pluginClass = Class.forName(plugin);
Plugin pluginAnnotation = (Plugin) pluginClass.getAnnotation(Plugin.class);
String pluginName = pluginAnnotation.name();
String pluginDocFile = "plugin/" + pluginName + ".html";
String pluginLink = "ha-plugins/" + pluginName.toLowerCase() + "-plugin";
URL url = new URL(getBaseURL(getClass()) + TARGET_DIR + pluginDocFile);
boolean docExists = markdownProcessor.processPlugin(pluginClass, url);
addHtmlRow(html, pluginAnnotation, docExists ? pluginLink : null);
}
addHtmlFooter(html);
writeHtml(new URL(getBaseURL(getClass()) + TARGET_DIR + "plugins.html"), html.toString());
String mainReadme = markdownProcessor.markdownToHtml(IOUtils.streamToString(new URL(
getBaseURL(getClass()) + "/../README.md"
).openStream()));
writeMainReadme(mainReadme);
}
private void writeMainReadme(String mainReadme) throws MalformedURLException {<FILL_FUNCTION_BODY>}
private void addHtmlRow(StringBuilder html, Plugin annot, String pluginDocFile) {
html.append("<tr>");
html.append("<td>");
html.append(annot.name());
html.append("</td>");
html.append("<td>");
html.append(annot.description());
html.append("</td>");
html.append("<td>");
commaSeparated(html, annot.testedVersions());
html.append("</td>");
html.append("<td>");
commaSeparated(html, annot.expectedVersions());
html.append("</td>");
html.append("<td>");
if (pluginDocFile != null) {
html.append("<a href='");
html.append(pluginDocFile);
html.append("'>Documentation</a>");
}
html.append("</td>");
html.append("</tr>");
}
private void addHtmlHeader(StringBuilder html) {
html.append("<table>");
}
private void addHtmlFooter(StringBuilder html) {
html.append("</table>");
}
private void commaSeparated(StringBuilder html, String[] strings) {
boolean first = true;
for (String s : strings) {
if (!first)
html.append(", ");
html.append(s);
first = false;
}
}
private void writeHtml(URL url, String html) {
try {
assertDirExists(url);
PrintWriter out = new PrintWriter(url.getFile());
out.print(html);
out.close();
} catch (FileNotFoundException e) {
throw new IllegalArgumentException("Unable to open file " + url + " to write HTML content.");
}
}
/**
* Create all required directories in path for a file
*/
public static void assertDirExists(URL targetFile) {
File parent = null;
try {
parent = new File(targetFile.toURI()).getParentFile();
} catch (URISyntaxException e) {
throw new IllegalStateException(e);
}
if(!parent.exists() && !parent.mkdirs()){
throw new IllegalStateException("Couldn't create dir: " + parent);
}
}
}
|
writeHtml(new URL(getBaseURL(getClass()) + TARGET_DIR + "README.html"), mainReadme);
// each <h1> section
for (String section : mainReadme.split("\\<h1\\>")) {
if (section.isEmpty())
continue;
// create label as content between <h1> and </h1>
int h1EndIndex = section.indexOf("</h1>");
if (h1EndIndex > 0) {
String label = section.substring(0, h1EndIndex);
// strip off header, the web page already contains it
String content = section.substring(h1EndIndex+5);
// make user-friendly valid file name
label = label.replaceAll("\\s", "-");
label = label.replaceAll("[^A-Za-z0-9-]", "");
label = label.toLowerCase();
// name file after section name
writeHtml(new URL(getBaseURL(getClass()) + TARGET_DIR + "section/" + label + ".html"), content);
}
}
| 1,300 | 283 | 1,583 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/hotswap-agent/src/main/java/org/hotswap/agent/distribution/markdown/MarkdownProcessor.java
|
MarkdownProcessor
|
processPlugin
|
class MarkdownProcessor {
PegDownProcessor pegDownProcessor;
public MarkdownProcessor() {
pegDownProcessor = new PegDownProcessor();
}
/**
* Main method to process plugin documentation.
*
* @param plugin plugin class
* @param targetFile file where to save HTML
* @return true if documentation is resolved and created
*/
public boolean processPlugin(Class plugin, URL targetFile) {<FILL_FUNCTION_BODY>}
/**
* Convert markdown to HTML
* @param src markdown content
* @return html content
*/
public String markdownToHtml(String src) {
return pegDownProcessor.markdownToHtml(src);
}
/**
* Resolve README.md file from plugin package and from main plugin directory.
* @param plugin plugin class
* @return the content of README.md or null (if no documentation exists)
*/
public String resolveMarkdownDoc(Class plugin) {
InputStream is = resolveSamePackageReadme(plugin);
if (is == null) {
is = resolveMavenMainDirectoryReadme(plugin);
}
if (is != null)
return IOUtils.streamToString(is);
else
return null;
}
// find README.md in a same package as the plugin. If found, it has precedence before main plugin documentation
private InputStream resolveSamePackageReadme(Class plugin) {
// locate in the same package
return plugin.getResourceAsStream("README.md");
}
// find README.md in file e.g. 'file:/J:/HotswapAgent/HotswapAgent/README.md'
private InputStream resolveMavenMainDirectoryReadme(Class plugin) {
try {
URI uri = new URI(PluginDocs.getBaseURL(plugin) + "/README.md");
if (uri.toString().endsWith("/HotswapAgent/README.md")) {
// embedded plugin in HotswapAgent itself, but without documentation. Resolved
// documentation is for the agent not for the plugin
return null;
} else {
return new FileInputStream(new File(uri));
}
} catch (FileNotFoundException e) {
return null;
} catch (URISyntaxException e) {
throw new IllegalStateException(e);
}
}
}
|
String markdown = resolveMarkdownDoc(plugin);
if (markdown == null)
return false;
String html = markdownToHtml(markdown);
// first caption is always name of plugin - strip it off to not duplicate on web page
if (html.startsWith("<h1>")) {
int h1EndIndex = html.indexOf("</h1>");
if (h1EndIndex > 0) {
html = html.substring(h1EndIndex + 5);
}
}
PluginDocs.assertDirExists(targetFile);
try {
PrintWriter out = new PrintWriter(targetFile.getFile());
out.print(html);
out.close();
} catch (FileNotFoundException e) {
throw new IllegalArgumentException("Unable to open file " + targetFile + " to write HTML content.");
}
return true;
| 604 | 227 | 831 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/plugin/hotswap-agent-cxf-plugin/src/main/java/org/hotswap/agent/plugin/cxf/jaxrs/ClassResourceInfoProxyHelper.java
|
ClassResourceInfoProxyHelper
|
updateResourceProvider
|
class ClassResourceInfoProxyHelper {
private static AgentLogger LOGGER = AgentLogger.getLogger(ClassResourceInfoProxyHelper.class);
private static Class<?> classResourceInfoProxyClass = null;
private static final ThreadLocal<Boolean> DISABLE_PROXY_GENERATION = new ThreadLocal<Boolean>() {
@Override
protected Boolean initialValue() {
return false;
}
};
private static synchronized void createProxyClass(ClassResourceInfo cri) {
if (classResourceInfoProxyClass == null) {
ProxyFactory f = new ProxyFactory();
f.setSuperclass(cri.getClass());
f.setFilter(new MethodFilter() {
public boolean isHandled(Method m) {
return true;
}
});
classResourceInfoProxyClass = f.createClass();
}
}
/**
* Creates the class resource info proxy
*
* @param classResourceInfo the class resource info
* @param generatorParams the generator params
* @return the class resource info
*/
public static ClassResourceInfo createProxy(ClassResourceInfo classResourceInfo, Class<?> generatorTypes[], Object generatorParams[]) {
if (!DISABLE_PROXY_GENERATION.get()) {
try {
createProxyClass(classResourceInfo);
ClassResourceInfo result = (ClassResourceInfo) classResourceInfoProxyClass.newInstance();
CriProxyMethodHandler methodHandler = new CriProxyMethodHandler(result, generatorTypes, generatorParams);
((Proxy)result).setHandler(methodHandler);
methodHandler.delegate = classResourceInfo;
methodHandler.generatorTypes = generatorTypes;
methodHandler.generatorParams = generatorParams;
return result;
} catch (Exception e) {
LOGGER.error("Unable to create ClassResourceInfo proxy for {}", e, classResourceInfo);
}
}
return classResourceInfo;
}
public static void reloadClassResourceInfo(ClassResourceInfo classResourceInfoProxy) {
try {
DISABLE_PROXY_GENERATION.set(true);
CriProxyMethodHandler criMethodHandler = (CriProxyMethodHandler) ((ProxyObject)classResourceInfoProxy).getHandler();
ClassResourceInfo newClassResourceInfo = (ClassResourceInfo) ReflectionHelper.invoke(null, ResourceUtils.class, "createClassResourceInfo",
criMethodHandler.generatorTypes, criMethodHandler.generatorParams);
ClassResourceInfo oldClassResourceInfo = criMethodHandler.delegate;
ResourceProvider resourceProvider = oldClassResourceInfo.getResourceProvider();
updateResourceProvider(resourceProvider);
newClassResourceInfo.setResourceProvider(resourceProvider);
criMethodHandler.delegate = newClassResourceInfo;
} catch (Exception e) {
LOGGER.error("reloadClassResourceInfo() exception {}", e.getMessage());
} finally {
DISABLE_PROXY_GENERATION.remove();
}
}
private static void updateResourceProvider(ResourceProvider resourceProvider) {<FILL_FUNCTION_BODY>}
public static class CriProxyMethodHandler implements MethodHandler {
ClassResourceInfo delegate;
Object[] generatorParams;
Class<?>[] generatorTypes;
public CriProxyMethodHandler(ClassResourceInfo delegate, Class<?> generatorTypes[], Object[] generatorParams) {
this.generatorTypes = generatorTypes; }
public Object invoke(Object self, Method method, Method proceed, Object[] args) throws Throwable {
// simple delegate to delegate object
if (method.getName() == "setResourceProvider" &&
args != null &&
args[0] != null &&
args[0] instanceof SingletonResourceProvider) {
try {
SingletonResourceProvider resourceProvider = (SingletonResourceProvider) args[0];
ClassLoader pluginClassLoader = delegate.getServiceClass().getClassLoader();
Object pluginInstance = PluginManager.getInstance().getPlugin(CxfJAXRSPlugin.class.getName(), pluginClassLoader);
if (pluginInstance != null) {
ReflectionHelper.invoke(pluginInstance, pluginInstance.getClass(),
"registerServiceInstance", new Class[] {Object.class}, resourceProvider.getInstance(null));
} else {
LOGGER.error("registerServiceInstance() CxfJAXRSPlugin not found in classLoader {}", pluginClassLoader);
}
} catch (Exception e) {
LOGGER.error("registerServiceInstance() exception {}", e);
}
}
return method.invoke(delegate, args);
}
}
}
|
if (resourceProvider.getClass().getName().equals("org.apache.cxf.jaxrs.spring.SpringResourceFactory")){
try {
ReflectionHelper.invoke(resourceProvider, resourceProvider.getClass(), "clearSingletonInstance", null, null);
} catch (Exception e) {
LOGGER.error("updateResourceProvider() clearSingletonInstance failed. {}", e);
}
}
| 1,123 | 103 | 1,226 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/plugin/hotswap-agent-cxf-plugin/src/main/java/org/hotswap/agent/plugin/cxf/jaxrs/CxfJAXRSCommand.java
|
CxfJAXRSCommand
|
equals
|
class CxfJAXRSCommand extends MergeableCommand {
private static AgentLogger LOGGER = AgentLogger.getLogger(CxfJAXRSCommand.class);
private ClassLoader classLoader;
private ClassResourceInfo criProxy;
private String resourceClassPath;
public void setupCmd(ClassLoader classLoader, Object criProxy) {
this.classLoader = classLoader;
this.criProxy = (ClassResourceInfo) criProxy;
resourceClassPath = this.criProxy.getServiceClass().toString();
}
@Override
public void executeCommand() {
LOGGER.debug("Reloading service={}, in classLoader={}", criProxy.getServiceClass(), classLoader);
ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(classLoader);
ClassResourceInfoProxyHelper.reloadClassResourceInfo(criProxy);
LOGGER.info("Resource class {} reloaded.", criProxy.getResourceClass().getName());
} catch (Exception e) {
LOGGER.error("Could not reload JAXRS service class {}", e, criProxy.getServiceClass());
} finally {
Thread.currentThread().setContextClassLoader(oldClassLoader);
}
}
@Override
public boolean equals(Object object) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return Objects.hash(resourceClassPath);
}
@Override
public String toString() {
return "CxfJAXRSCommand[classLoader=" + classLoader + ", service class =" + criProxy.getServiceClass() + "]";
}
}
|
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
CxfJAXRSCommand that = (CxfJAXRSCommand) object;
return Objects.equals(resourceClassPath, that.resourceClassPath);
| 432 | 73 | 505 |
<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-cxf-plugin/src/main/java/org/hotswap/agent/plugin/cxf/jaxrs/CxfJAXRSPlugin.java
|
CxfJAXRSPlugin
|
getServiceInstances
|
class CxfJAXRSPlugin {
private static AgentLogger LOGGER = AgentLogger.getLogger(CxfJAXRSPlugin.class);
private static final Set<String> PATH_ANNOTATIONS = new HashSet<>(Arrays.asList("jakarta.ws.rs.Path", "javax.ws.rs.Path"));
private static final int WAIT_ON_REDEFINE = 300; // Should be bigger then DI plugins (CDI..)
private static final int WAIT_ON_CREATE = 600; // Should be bigger then DI plugins (CDI..)
@Init
ClassLoader appClassLoader;
@Init
Scheduler scheduler;
Map<String, Object> classResourceInfoRegistry = new HashMap<>();
WeakHashMap<Object, Boolean> serviceInstances = new WeakHashMap<>();
WeakHashMap<Object, Boolean> jaxbProviderRegistry = new WeakHashMap<>();
@Init
public void init(PluginConfiguration pluginConfiguration) {
LOGGER.info("CxfJAXRSPlugin initialized.");
}
public void registerClassResourceInfo(Class<?> serviceClass, Object classResourceInfo) {
classResourceInfoRegistry.put(serviceClass.getName(), classResourceInfo);
LOGGER.debug("Registered service {} ", serviceClass.getClass().getName());
}
public void registerJAXBProvider(Object jaxbProvider) {
jaxbProviderRegistry.put(jaxbProvider, Boolean.TRUE);
LOGGER.debug("Registered JAXB Provider {} ", jaxbProvider);
}
public boolean containsServiceInstance(Class<?> serviceClass) {
for (Object provider: serviceInstances.keySet()) {
if (provider.getClass().getName().equals(serviceClass.getName())) {
return true;
}
}
return false;
}
public List<Object> getServiceInstances(Class<?> serviceClass) {<FILL_FUNCTION_BODY>}
public void registerServiceInstance(Object serviceInstance) {
serviceInstances.put(serviceInstance, Boolean.TRUE);
}
@OnClassLoadEvent(classNameRegexp = ".*", events = LoadEvent.REDEFINE)
public void classReload(ClassLoader classLoader, CtClass clazz, Class<?> original) {
if (isSyntheticClass(clazz.getName())) {
LOGGER.trace("Skipping synthetic class {}.", clazz.getName());
return;
}
if (AnnotationHelper.hasAnnotation(original, PATH_ANNOTATIONS)
|| AnnotationHelper.hasAnnotation(clazz, PATH_ANNOTATIONS)) {
if(LOGGER.isLevelEnabled(Level.TRACE)) {
LOGGER.trace("Reload @Path annotated class {}", clazz.getName());
}
refreshClass(classLoader, clazz.getName(), original, WAIT_ON_REDEFINE);
}
clearJAXBProviderContexts();
}
/*
@OnClassFileEvent(classNameRegexp = ".*", events = { FileEvent.CREATE })
public void newClass(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, WAIT_ON_CREATE);
}
}
*/
private void refreshClass(ClassLoader classLoader, String className, Class<?> original, int timeout) {
try {
Object classResourceInfoProxy = classResourceInfoRegistry.get(className);
if (classResourceInfoProxy == null) {
LOGGER.debug("refreshClass() ClassResourceInfo proxy not found for classResourceInfo={}.", className);
return;
}
Class<?> cmdClass = Class.forName(CxfJAXRSCommand.class.getName(), true, appClassLoader);
Command cmd = (Command) cmdClass.newInstance();
ReflectionHelper.invoke(cmd, cmdClass, "setupCmd", new Class[] { ClassLoader.class, Object.class },
classLoader, classResourceInfoProxy);
scheduler.scheduleCommand(cmd, timeout);
} catch (Exception e) {
LOGGER.error("refreshClass() exception {}.", e.getMessage());
}
}
private void clearJAXBProviderContexts() {
try {
for (Object provider: jaxbProviderRegistry.keySet()) {
ReflectionHelper.invoke(provider, provider.getClass(), "clearContexts", null, null);
}
} catch (Exception e) {
LOGGER.error("clearJAXBProviderContexts() exception {}.", e.getMessage());
}
}
private boolean isSyntheticClass(String className) {
return className.contains("$$");
}
}
|
List<Object> result = new ArrayList<>();
for (Object service: serviceInstances.keySet()) {
if (service.getClass().getName().equals(serviceClass.getName())) {
result.add(service);
}
}
return result;
| 1,236 | 68 | 1,304 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/plugin/hotswap-agent-cxf-plugin/src/main/java/org/hotswap/agent/plugin/cxf/jaxrs/CxfJAXRSTransformer.java
|
CxfJAXRSTransformer
|
patchResourceUtils
|
class CxfJAXRSTransformer {
private static AgentLogger LOGGER = AgentLogger.getLogger(CxfJAXRSTransformer.class);
@OnClassLoadEvent(classNameRegexp = "org.apache.cxf.jaxrs.utils.ResourceUtils")
public static void patchResourceUtils(CtClass ctClass, ClassPool classPool){<FILL_FUNCTION_BODY>}
@OnClassLoadEvent(classNameRegexp = "org.apache.cxf.jaxrs.model.ClassResourceInfo")
public static void patchClassResourceInfo(CtClass ctClass, ClassPool classPool) {
try {
// Add default constructor used in proxy creation
CtConstructor c = CtNewConstructor.make("public " + ctClass.getSimpleName() + "() { super(null); }", ctClass);
ctClass.addConstructor(c);
} catch (CannotCompileException e) {
LOGGER.error("Error patching ClassResourceInfo", e);
}
}
@OnClassLoadEvent(classNameRegexp = "org.apache.cxf.cdi.JAXRSCdiResourceExtension")
public static void patchCxfJARSCdiExtension(CtClass ctClass, ClassPool classPool){
try{
CtMethod loadMethod = ctClass.getDeclaredMethod("load");
loadMethod.insertAfter( "{ " +
"ClassLoader $$cl = java.lang.Thread.currentThread().getContextClassLoader();" +
"if ($$cl==null) $$cl = this.bus.getClass().getClassLoader();" +
"Object $$plugin =" + PluginManagerInvoker.buildInitializePlugin(CxfJAXRSPlugin.class, "$$cl") +
HaCdiExtraCxfContext.class.getName() + ".registerExtraContext($$plugin);" +
"}"
);
} catch(NotFoundException | CannotCompileException e){
LOGGER.error("Error patching ResourceUtils", e);
}
}
@OnClassLoadEvent(classNameRegexp = "org.apache.cxf.jaxrs.spring.SpringResourceFactory")
public static void patchSpringResourceFactory(CtClass ctClass, ClassPool classPool){
try{
CtMethod loadMethod = ctClass.getDeclaredMethod("getInstance");
loadMethod.insertBefore( "{ " +
"if(isSingleton() && this.singletonInstance==null){ " +
"try{" +
"this.singletonInstance=ac.getBean(beanId);" +
"}catch (Exception ex) {}" +
"}" +
"}"
);
ctClass.addMethod(CtMethod.make(
"public void clearSingletonInstance() { this.singletonInstance=null; }", ctClass));
} catch(NotFoundException | CannotCompileException e){
LOGGER.error("Error patching ResourceUtils", e);
}
}
@OnClassLoadEvent(classNameRegexp = "org.apache.cxf.jaxrs.provider.AbstractJAXBProvider")
public static void patchAbstractJAXBProvider(CtClass ctClass, ClassPool classPool){
try{
CtMethod loadMethod = ctClass.getDeclaredMethod("init");
loadMethod.insertAfter( "{ " +
"ClassLoader $$cl = java.lang.Thread.currentThread().getContextClassLoader();" +
"if ($$cl==null) $$cl = getClass().getClassLoader();" +
PluginManagerInvoker.buildInitializePlugin(CxfJAXRSPlugin.class, "$$cl") +
PluginManagerInvoker.buildCallPluginMethod("$$cl", CxfJAXRSPlugin.class, "registerJAXBProvider",
"this", "java.lang.Object") +
"}"
);
} catch(NotFoundException | CannotCompileException e){
LOGGER.error("Error patching ResourceUtils", e);
}
}
}
|
try{
CtMethod createCriMethods[] = ctClass.getDeclaredMethods("createClassResourceInfo");
for (CtMethod method: createCriMethods) {
if (method.getParameterTypes()[0].getName().equals(Class.class.getName())) {
method.insertAfter(
"if($_ != null && !$_.getClass().getName().contains(\"$$\") ) { " +
"ClassLoader $$cl = java.lang.Thread.currentThread().getContextClassLoader();" +
"if ($$cl==null) $$cl = $1.getClassLoader();" +
PluginManagerInvoker.buildInitializePlugin(CxfJAXRSPlugin.class, "$$cl") +
"try {" +
org.hotswap.agent.javassist.runtime.Desc.class.getName() + ".setUseContextClassLoaderLocally();" +
"$_ = " + ClassResourceInfoProxyHelper.class.getName() + ".createProxy($_, $sig, $args);" +
"} finally {"+
org.hotswap.agent.javassist.runtime.Desc.class.getName() + ".resetUseContextClassLoaderLocally();" +
"}" +
"if ($_.getClass().getName().contains(\"$$\")) {" +
PluginManagerInvoker.buildCallPluginMethod("$$cl", CxfJAXRSPlugin.class, "registerClassResourceInfo",
"$_.getServiceClass()", "java.lang.Class", "$_", "java.lang.Object") +
"}" +
"}" +
"return $_;"
);
}
}
} catch(NotFoundException | CannotCompileException e){
LOGGER.error("Error patching ResourceUtils", e);
}
| 992 | 439 | 1,431 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/plugin/hotswap-agent-cxf-plugin/src/main/java/org/hotswap/agent/plugin/cxf/jaxrs/HaCdiExtraCxfContext.java
|
HaCdiExtraCxfContext
|
containsBeanInstances
|
class HaCdiExtraCxfContext implements HaCdiExtraContext {
private static AgentLogger LOGGER = AgentLogger.getLogger(HaCdiExtraCxfContext.class);
public static void registerExtraContext(Object pluginInstance) {
HaCdiExtraCxfContext context = new HaCdiExtraCxfContext(pluginInstance);
HaCdiCommons.registerExtraContext(context);
}
WeakReference<Object> pluginReference;
HaCdiExtraCxfContext(Object plugin) {
pluginReference = new WeakReference<>(plugin);
}
public boolean containsBeanInstances(Class<?> beanClass) {<FILL_FUNCTION_BODY>}
@SuppressWarnings("unchecked")
public List<Object> getBeanInstances(Class<?> beanClass) {
Object plugin = pluginReference.get();
if (plugin != null) {
try {
return (List<Object>) ReflectionHelper.invoke(plugin, plugin.getClass(), "getServiceInstances",
new Class[] { Class.class }, beanClass);
} catch (Exception e) {
LOGGER.error("getBeanInstances() exception {}", e);
}
}
return null;
}
}
|
Object plugin = pluginReference.get();
if (plugin != null) {
try {
return (boolean) ReflectionHelper.invoke(plugin, plugin.getClass(), "containsServiceInstance",
new Class[] { Class.class }, beanClass);
} catch (Exception e) {
LOGGER.error("containsBeanInstances() exception {}", e);
}
}
return false;
| 310 | 101 | 411 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/plugin/hotswap-agent-deltaspike-plugin/src/main/java/org/hotswap/agent/plugin/deltaspike/DeltaSpikePlugin.java
|
DeltaSpikePlugin
|
registerRepoProxy
|
class DeltaSpikePlugin {
private static AgentLogger LOGGER = AgentLogger.getLogger(DeltaSpikePlugin.class);
private static final String REPOSITORY_ANNOTATION = "org.apache.deltaspike.data.api.Repository";
public static final int WAIT_ON_REDEFINE = 500;
@Init
ClassLoader appClassLoader;
@Init
Scheduler scheduler;
Map<Object, String> registeredPartialBeans = new WeakHashMap<>();
Map<Object, List<String>> registeredViewConfExtRootClasses = new WeakHashMap<>();
Set<Object> registeredWindowContexts = Collections.newSetFromMap(new WeakHashMap<Object, Boolean>());
// ds<1.9
Map<Object, String> registeredRepoComponents = new WeakHashMap<>();
// ds>=1.9
Map<Object, String> registeredRepoProxies = new WeakHashMap<>();
List<Class<?>> repositoryClasses;
@Init
public void init(PluginConfiguration pluginConfiguration) {
LOGGER.info("Deltaspike plugin initialized.");
}
// ds<1.9
public void registerRepoComponent(Object repoComponent, Class<?> repositoryClass) {
if (!registeredRepoComponents.containsKey(repoComponent)) {
LOGGER.debug("DeltaspikePlugin - Repository Component registered : {}", repositoryClass.getName());
}
registeredRepoComponents.put(repoComponent, repositoryClass.getName());
}
public void registerRepositoryClasses(List<Class<?>> repositoryClassesList) {
this.repositoryClasses = new ArrayList<>(repositoryClassesList);
}
// ds>=1.9
public void registerRepoProxy(Object repoProxy, Class<?> repositoryClass) {<FILL_FUNCTION_BODY>}
public void registerPartialBean(Object bean, Class<?> partialBeanClass) {
synchronized(registeredPartialBeans) {
registeredPartialBeans.put(bean, partialBeanClass.getName());
}
LOGGER.debug("Partial bean '{}' registered", partialBeanClass.getName());
}
public void registerWindowContext(Object windowContext) {
if (windowContext != null && !registeredWindowContexts.contains(windowContext)) {
registeredWindowContexts.add(windowContext);
LOGGER.debug("Window context '{}' registered.", windowContext.getClass().getName());
}
}
@OnClassLoadEvent(classNameRegexp = ".*", events = LoadEvent.REDEFINE)
public void classReload(CtClass clazz, Class original, ClassPool classPool) throws NotFoundException {
checkRefreshViewConfigExtension(clazz, original);
PartialBeanClassRefreshCommand cmd = checkRefreshPartialBean(clazz, original, classPool);
if (cmd != null) {
checkRefreshRepository(clazz, classPool, cmd);
}
}
private PartialBeanClassRefreshCommand checkRefreshPartialBean(CtClass clazz, Class original, ClassPool classPool) throws NotFoundException {
PartialBeanClassRefreshCommand cmd = null;
Object partialBean = getObjectByName(registeredPartialBeans, clazz.getName());
if (partialBean != null) {
String oldSignForProxyCheck = DeltaspikeClassSignatureHelper.getSignaturePartialBeanClass(original);
cmd = new PartialBeanClassRefreshCommand(appClassLoader, partialBean, clazz.getName(), oldSignForProxyCheck, scheduler);
scheduler.scheduleCommand(cmd, WAIT_ON_REDEFINE);
}
return cmd;
}
private void checkRefreshRepository(CtClass clazz, ClassPool classPool, PartialBeanClassRefreshCommand masterCmd) throws NotFoundException {
if (isRepository(clazz, classPool)) {
Object repositoryComponent = getObjectByName(registeredRepoComponents, clazz.getName());
RepositoryRefreshCommand cmd = null;
if (repositoryComponent != null) {
// for ds < 1.9
cmd = new RepositoryRefreshCommand(appClassLoader, clazz.getName(), repositoryComponent);
} else if (repositoryClasses!= null) {
cmd = new RepositoryRefreshCommand(appClassLoader, clazz.getName(), getRepositoryProxies(clazz.getName()));
}
if (cmd != null) {
masterCmd.addChainedCommand(cmd);
}
}
}
private List<Object> getRepositoryProxies(String repositoryClassName) {
List<Object> result = new ArrayList<>();
for (Entry<Object, String> entry: registeredRepoProxies.entrySet()) {
if (repositoryClassName.equals(entry.getValue())) {
result.add(entry.getKey());
}
}
return result;
}
private boolean isRepository(CtClass clazz, ClassPool classPool) throws NotFoundException {
if (isSyntheticCdiClass(clazz.getName())) {
return false;
}
CtClass ctInvocationHandler = classPool.get("java.lang.reflect.InvocationHandler");
if (clazz.subtypeOf(ctInvocationHandler)) {
return false;
}
if (AnnotationHelper.hasAnnotation(clazz, REPOSITORY_ANNOTATION)) {
return true;
}
CtClass superClass = clazz.getSuperclass();
if (superClass != null) {
return isRepository(superClass, classPool);
}
return false;
}
private Object getObjectByName(Map<Object, String> registeredComponents, String className) {
for (Entry<Object, String> entry : registeredComponents.entrySet()) {
if (className.equals(entry.getValue())) {
return entry.getKey();
}
}
return null;
}
private void checkRefreshViewConfigExtension(CtClass clazz, Class original) {
String className = original.getName();
int index = className.indexOf("$");
String rootClassName = (index!=-1) ? className.substring(0, index) : className;
for (Entry<Object, List<String>> entry: registeredViewConfExtRootClasses.entrySet()) {
List<String> rootClassNameList = entry.getValue();
for (String viewConfigClassName: rootClassNameList) {
if (viewConfigClassName.equals(rootClassName)) {
scheduler.scheduleCommand(new ViewConfigReloadCommand(appClassLoader, entry.getKey(), entry.getValue()), WAIT_ON_REDEFINE);
return;
}
}
}
}
public void registerViewConfigRootClasses(Object viewConfigExtension, List rootClassList) {
if (rootClassList != null ) {
List<String> rootClassNameList = new ArrayList<>();
for (Object viewConfigClassObj : rootClassList) {
Class<?> viewConfigClass = (Class<?>) viewConfigClassObj;
LOGGER.debug("ViewConfigRoot class '{}' registered.", viewConfigClass.getName());
rootClassNameList.add(viewConfigClass.getName());
}
registeredViewConfExtRootClasses.put(viewConfigExtension, rootClassNameList);
}
}
private boolean isSyntheticCdiClass(String className) {
return className.contains("$$");
}
}
|
if (repositoryClasses == null) {
return;
}
if (!registeredRepoProxies.containsKey(repoProxy)) {
LOGGER.debug("DeltaspikePlugin - repository proxy registered : {}", repositoryClass.getName());
}
Class<?> checkedClass = repositoryClass;
while(checkedClass != null && !repositoryClasses.contains(checkedClass)) {
checkedClass = checkedClass.getSuperclass();
}
if (checkedClass != null) {
registeredRepoProxies.put(repoProxy, repositoryClass.getName());
}
| 1,865 | 147 | 2,012 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/plugin/hotswap-agent-deltaspike-plugin/src/main/java/org/hotswap/agent/plugin/deltaspike/DeltaspikeClassSignatureHelper.java
|
DeltaspikeClassSignatureHelper
|
getSignaturePartialBeanClass
|
class DeltaspikeClassSignatureHelper {
private static AgentLogger LOGGER = AgentLogger.getLogger(DeltaspikeClassSignatureHelper.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
};
/**
* Gets the class signature for partial bean class comparison
*
* @param clazz the clazz for which signature is calculated
* @return the java class signature
*/
public static String getSignaturePartialBeanClass(Class<?> clazz) {<FILL_FUNCTION_BODY>}
}
|
try {
return ClassSignatureComparerHelper.getJavaClassSignature(clazz, SIGNATURE_ELEM_PROXY);
} catch (Exception e) {
LOGGER.error("getSignatureForProxyClass(): Error reading signature", e);
return null;
}
| 256 | 71 | 327 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/plugin/hotswap-agent-deltaspike-plugin/src/main/java/org/hotswap/agent/plugin/deltaspike/command/PartialBeanClassRefreshAgent.java
|
PartialBeanClassRefreshAgent
|
refreshPartialBeanClass
|
class PartialBeanClassRefreshAgent {
private static AgentLogger LOGGER = AgentLogger.getLogger(PartialBeanClassRefreshAgent.class);
public static void refreshPartialBeanClass(ClassLoader classLoader, Object partialBean, String oldSignaturesForProxyCheck) {<FILL_FUNCTION_BODY>}
}
|
ClassLoader oldContextClassLoader = Thread.currentThread().getContextClassLoader();
Bean<?> bean = (Bean<?>) partialBean;
Class<?> beanClass = bean.getBeanClass();
String newClassSignature = DeltaspikeClassSignatureHelper.getSignaturePartialBeanClass(beanClass);
if (newClassSignature != null && newClassSignature.equals(oldSignaturesForProxyCheck)) {
return;
}
ProxyClassLoadingDelegate.beginProxyRegeneration();
try {
Thread.currentThread().setContextClassLoader(classLoader);
Object lifecycle = (Object) ReflectionHelper.get(partialBean, "lifecycle");
if (lifecycle != null) {
Class<?> targetClass = (Class) ReflectionHelper.get(lifecycle, "targetClass");
PartialBeanProxyFactory proxyFactory = PartialBeanProxyFactory.getInstance();
try {
// Deltaspike 1.5
Method m3 = PartialBeanProxyFactory.class.getMethod("getProxyClass", new Class[] { BeanManager.class, Class.class, Class.class} );
Class<? extends InvocationHandler> delegateInvocationHandlerClass = (Class) ReflectionHelper.get(lifecycle, "delegateInvocationHandlerClass");
m3.invoke(proxyFactory, new Object[] {BeanManagerProvider.getInstance().getBeanManager(), targetClass, delegateInvocationHandlerClass} );
} catch (NoSuchMethodException e) {
// Deltaspike 1.7
Method m2 = PartialBeanProxyFactory.class.getMethod("getProxyClass", new Class[] { BeanManager.class, Class.class } );
m2.invoke(proxyFactory, new Object[] {BeanManagerProvider.getInstance().getBeanManager(), targetClass} );
}
}
} catch (Exception e) {
LOGGER.error("Deltaspike proxy redefinition failed", e);
} finally {
Thread.currentThread().setContextClassLoader(oldContextClassLoader);
ProxyClassLoadingDelegate.endProxyRegeneration();
}
| 80 | 524 | 604 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/plugin/hotswap-agent-deltaspike-plugin/src/main/java/org/hotswap/agent/plugin/deltaspike/command/PartialBeanClassRefreshCommand.java
|
PartialBeanClassRefreshCommand
|
equals
|
class PartialBeanClassRefreshCommand extends MergeableCommand {
private static AgentLogger LOGGER = AgentLogger.getLogger(PartialBeanClassRefreshCommand.class);
ClassLoader appClassLoader;
Object partialBean;
String className;
private Scheduler scheduler;
String oldSignForProxyCheck;
List<Command> chainedCommands = new ArrayList<>();
public PartialBeanClassRefreshCommand(ClassLoader classLoader, Object partialBean, String className, String oldSignForProxyCheck, Scheduler scheduler) {
this.appClassLoader = classLoader;
this.partialBean = partialBean;
this.className = className;
this.oldSignForProxyCheck = oldSignForProxyCheck;
this.scheduler = scheduler;
}
public void addChainedCommand(Command cmd) {
chainedCommands.add(cmd);
}
@Override
public void executeCommand() {
boolean reloaded = false;
try {
LOGGER.debug("Executing PartialBeanClassRefreshAgent.refreshPartialBeanClass('{}')", className);
Class<?> agentClazz = Class.forName(PartialBeanClassRefreshAgent.class.getName(), true, appClassLoader);
Method m = agentClazz.getDeclaredMethod("refreshPartialBeanClass", new Class[] {ClassLoader.class, Object.class, String.class});
m.invoke(null, appClassLoader, partialBean, oldSignForProxyCheck);
reloaded = true;
} catch (NoSuchMethodException e) {
throw new IllegalStateException("Plugin error, method not found", e);
} catch (InvocationTargetException e) {
LOGGER.error("Error refreshing class {} in appClassLoader {}", e, className, appClassLoader);
} catch (IllegalAccessException e) {
throw new IllegalStateException("Plugin error, illegal access", e);
} catch (ClassNotFoundException e) {
throw new IllegalStateException("Plugin error, CDI class not found in classloader", e);
}
if (reloaded) {
for (Command cmd: chainedCommands) {
scheduler.scheduleCommand(cmd, DeltaSpikePlugin.WAIT_ON_REDEFINE);
}
}
}
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
int result = appClassLoader.hashCode();
result = 31 * result + partialBean.hashCode();
return result;
}
@Override
public String toString() {
return "PartialBeanClassRefreshCommand{" +
"appClassLoader=" + appClassLoader +
", partialBean='" + partialBean + '\'' +
'}';
}
}
|
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PartialBeanClassRefreshCommand that = (PartialBeanClassRefreshCommand) o;
if (!appClassLoader.equals(that.appClassLoader)) return false;
if (!partialBean.equals(that.partialBean)) return false;
if (!className.equals(that.className)) return false;
return true;
| 699 | 116 | 815 |
<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-deltaspike-plugin/src/main/java/org/hotswap/agent/plugin/deltaspike/command/ProxyClassLoadingDelegate.java
|
ProxyClassLoadingDelegate
|
loadClass
|
class ProxyClassLoadingDelegate {
private static AgentLogger LOGGER = AgentLogger.getLogger(ProxyClassLoadingDelegate.class);
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();
}
// Deltaspike 1.7
public static Class<?> tryToLoadClassForName(String proxyClassName, Class<?> targetClass, ClassLoader classLoader) {
if (MAGIC_IN_PROGRESS.get()) {
return null;
}
return (Class<?>) ReflectionHelper.invoke(null, org.apache.deltaspike.core.util.ClassUtils.class, "tryToLoadClassForName",
new Class[] { String.class, Class.class, ClassLoader.class },
proxyClassName, targetClass, classLoader);
}
// Deltaspike 1.5
public static Class<?> tryToLoadClassForName(String proxyClassName, Class<?> targetClass) {
if (MAGIC_IN_PROGRESS.get()) {
return null;
}
return org.apache.deltaspike.core.util.ClassUtils.tryToLoadClassForName(proxyClassName, targetClass);
}
public static Class<?> loadClass(ClassLoader loader, String className, byte[] bytes, ProtectionDomain protectionDomain) {<FILL_FUNCTION_BODY>}
// for DS >= 1.9.6
public static Class<?> defineClass(ClassLoader loader, String className, byte[] bytes, Class<?> originalClass, ProtectionDomain protectionDomain) {
if (MAGIC_IN_PROGRESS.get()) {
try {
final Class<?> originalProxyClass = loader.loadClass(className);
try {
Map<Class<?>, byte[]> reloadMap = new HashMap<>();
reloadMap.put(originalProxyClass, bytes);
PluginManager.getInstance().hotswap(reloadMap);
return originalProxyClass;
} catch (Exception e) {
throw new RuntimeException(e);
}
} catch (ClassNotFoundException e) {
//it has not actually been loaded yet
}
}
try {
Class<?> classDefiner = null;
try {
// ClassDefiner introduced in ds 1.9.6
classDefiner = loader.loadClass("org.apache.deltaspike.proxy.impl.ClassDefiner");
} catch (ClassNotFoundException e1) {
LOGGER.error("ClassDefiner class not found!");
}
if (classDefiner != null) {
return (Class<?>) ReflectionHelper.invoke(null, classDefiner, "defineClass",
new Class[]{ClassLoader.class, String.class, byte[].class, Class.class, ProtectionDomain.class},
loader, className, bytes, originalClass, protectionDomain);
}
} catch (Exception e) {
LOGGER.error("loadClass() exception {}", e.getMessage());
}
return null;
}
}
|
if (MAGIC_IN_PROGRESS.get()) {
try {
final Class<?> originalProxyClass = loader.loadClass(className);
try {
Map<Class<?>, byte[]> reloadMap = new HashMap<>();
reloadMap.put(originalProxyClass, bytes);
PluginManager.getInstance().hotswap(reloadMap);
return originalProxyClass;
} catch (Exception e) {
throw new RuntimeException(e);
}
} catch (ClassNotFoundException e) {
//it has not actually been loaded yet
}
}
try {
Class<?> proxyClassGeneratorClass = null;
try {
// proxy generator from ds1.9
proxyClassGeneratorClass = loader.loadClass("org.apache.deltaspike.proxy.impl.AsmDeltaSpikeProxyClassGenerator");
} catch (ClassNotFoundException e1) {
try {
// proxy generator from ds<1.9
proxyClassGeneratorClass = loader.loadClass("org.apache.deltaspike.proxy.impl.AsmProxyClassGenerator");
} catch (ClassNotFoundException e2) {
LOGGER.error("DeltaspikeProxyClassGenerator class not found!");
}
}
if (proxyClassGeneratorClass != null) {
return (Class<?>) ReflectionHelper.invoke(null, proxyClassGeneratorClass, "loadClass",
new Class[]{ClassLoader.class, String.class, byte[].class, ProtectionDomain.class},
loader, className, bytes, protectionDomain);
}
} catch (Exception e) {
LOGGER.error("loadClass() exception {}", e.getMessage());
}
return null;
| 853 | 428 | 1,281 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/plugin/hotswap-agent-deltaspike-plugin/src/main/java/org/hotswap/agent/plugin/deltaspike/command/RepositoryRefreshAgent.java
|
RepositoryRefreshAgent
|
resolve
|
class RepositoryRefreshAgent {
private static AgentLogger LOGGER = AgentLogger.getLogger(RepositoryRefreshAgent.class);
public static boolean reloadFlag = false;
/**
* Reload bean in existing bean manager. Called by a reflection command from BeanRefreshCommand transformer.
*
* @param appClassLoader the application class loader
* @param repoClassName the repo class name
*/
public static void refreshHandler(ClassLoader appClassLoader, String repoClassName, List repositoryProxies) {
ClassLoader oldContextClassLoader = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(appClassLoader);
Class<?> repoClass = appClassLoader.loadClass(repoClassName);
RepositoryMetadataHandler handler = getInstance(RepositoryMetadataHandler.class);
if (handler != null) {
ReflectionHelper.invoke(handler, handler.getClass(), RepositoryTransformer.REINITIALIZE_METHOD, new Class[] { Class.class }, repoClass);
} else {
LOGGER.debug("{} bean not found.", RepositoryMetadataHandler.class.getName());
}
Method[] delegateMethods = PartialBeanProxyFactory.getInstance().getDelegateMethods(repoClass);
for (Object proxyObject: repositoryProxies) {
if (proxyObject instanceof DeltaSpikeProxy) {
((DeltaSpikeProxy) proxyObject).setDelegateMethods(delegateMethods);
}
}
DeltaSpikeProxyInterceptorLookup lookup = getInstance(DeltaSpikeProxyInterceptorLookup.class);
if (lookup != null) {
Map cache = (Map) ReflectionHelper.get(lookup, "cache");
if (cache != null) {
cache.clear();
}
}
LOGGER.info("Deltaspike repository {} refreshed.", repoClassName);
RepositoryRefreshAgent.reloadFlag = true;
} catch (ClassNotFoundException e) {
LOGGER.error("Repository class '{}' not found.", repoClassName, e);
} finally {
Thread.currentThread().setContextClassLoader(oldContextClassLoader);
}
}
public static <T> T getInstance(Class<T> beanClass) {
BeanManager beanManager = CDI.current().getBeanManager();
Bean<T> bean = resolve(beanManager, beanClass);
return getInstance(beanManager, bean);
}
private static <T> Bean<T> resolve(BeanManager beanManager, Class<T> beanClass) {<FILL_FUNCTION_BODY>}
private static <T> T getInstance(BeanManager beanManager, Bean<T> bean) {
Context context = beanManager.getContext(bean.getScope());
return context.get(bean);
}
}
|
Set<Bean<?>> beans = beanManager.getBeans(beanClass);
for (Bean<?> bean : beans) {
if (bean.getBeanClass() == beanClass) {
return (Bean<T>) beanManager.resolve(Collections.<Bean<?>> singleton(bean));
}
}
return (Bean<T>) beanManager.resolve(beans);
| 707 | 100 | 807 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/plugin/hotswap-agent-deltaspike-plugin/src/main/java/org/hotswap/agent/plugin/deltaspike/command/RepositoryRefreshCommand.java
|
RepositoryRefreshCommand
|
equals
|
class RepositoryRefreshCommand extends MergeableCommand {
private static AgentLogger LOGGER = AgentLogger.getLogger(RepositoryRefreshCommand.class);
ClassLoader appClassLoader;
String repoClassName;
Object repositoryComponent;
private List<Object> repositoryProxies;
public RepositoryRefreshCommand(ClassLoader appClassLoader, String repoClassName, Object repositoryComponent) {
this.appClassLoader = appClassLoader;
this.repositoryComponent = repositoryComponent;
this.repoClassName = repoClassName;
}
public RepositoryRefreshCommand(ClassLoader appClassLoader, String repoClassName, List<Object> repositoryProxies) {
this.appClassLoader = appClassLoader;
this.repoClassName = repoClassName;
this.repositoryProxies = repositoryProxies;
}
@Override
public void executeCommand() {
if (repositoryComponent != null) {
refreshRepository1();
} else {
refreshRepository2();
}
}
// ds<1.9
private void refreshRepository1() {
try {
Method reinitializeMethod = resolveClass("org.apache.deltaspike.data.impl.meta.RepositoryComponent")
.getDeclaredMethod(RepositoryTransformer.REINITIALIZE_METHOD);
reinitializeMethod.invoke(repositoryComponent);
LOGGER.info("Deltaspike repository {} refreshed.", repoClassName);
RepositoryRefreshAgent.reloadFlag = true;
} catch (Exception e) {
LOGGER.error("Error reinitializing repository {}", e, repoClassName);
}
}
private Class<?> resolveClass(String name) throws ClassNotFoundException {
return Class.forName(name, true, appClassLoader);
}
// ds>=1.9
private void refreshRepository2() {
try {
LOGGER.debug( "Executing RepositoryRefreshAgent.refreshHandler('{}')", repoClassName);
Class<?> agentClazz = Class.forName(
RepositoryRefreshAgent.class.getName(), true,
appClassLoader);
Method agentMethod = agentClazz.getDeclaredMethod("refreshHandler", new Class[] { ClassLoader.class, String.class, List.class });
agentMethod.invoke(null, appClassLoader, repoClassName, repositoryProxies);
} catch (NoSuchMethodException e) {
throw new IllegalStateException("Plugin error, method not found", e);
} catch (InvocationTargetException e) {
LOGGER.error("Error refreshing handler {} in appClassLoader {}", e, repoClassName, appClassLoader);
} catch (IllegalAccessException e) {
throw new IllegalStateException("Plugin error, illegal access", e);
} catch (ClassNotFoundException e) {
throw new IllegalStateException("Plugin error, CDI class not found in classloader", e);
}
}
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
int result = appClassLoader.hashCode();
result = 31 * result + repoClassName.hashCode();
return result;
}
@Override
public String toString() {
return "PartialBeanClassRefreshCommand{" +
"appClassLoader=" + appClassLoader +
"repoClassName=" + repoClassName +
'}';
}
}
|
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
RepositoryRefreshCommand that = (RepositoryRefreshCommand) o;
if (!appClassLoader.equals(that.appClassLoader)) return false;
if (!repoClassName.equals(that.repoClassName)) return false;
return true;
| 863 | 98 | 961 |
<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-deltaspike-plugin/src/main/java/org/hotswap/agent/plugin/deltaspike/jsf/ViewConfigReloadCommand.java
|
ViewConfigReloadCommand
|
executeCommand
|
class ViewConfigReloadCommand extends MergeableCommand {
private static AgentLogger LOGGER = AgentLogger.getLogger(ViewConfigReloadCommand.class);
ClassLoader classLoader;
Object viewConfigExtension;
List<String> rootClassNameList;
public ViewConfigReloadCommand(ClassLoader classLoader, Object viewConfigExtension, List<String> rootClassNameList) {
this.classLoader = classLoader;
this.viewConfigExtension = viewConfigExtension;
this.rootClassNameList = rootClassNameList;
}
@Override
public void executeCommand() {<FILL_FUNCTION_BODY>}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ViewConfigReloadCommand that = (ViewConfigReloadCommand) o;
if (!classLoader.equals(that.classLoader)) return false;
if (!viewConfigExtension.equals(that.viewConfigExtension)) return false;
if (!rootClassNameList.equals(that.rootClassNameList)) return false;
return true;
}
@Override
public int hashCode() {
int result = classLoader.hashCode();
result = 31 * result + (rootClassNameList != null ? rootClassNameList.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "ViewConfigExtensionRefreshCommand{" +
"appClassLoader=" + classLoader +
", viewConfigRootClassNames='" + rootClassNameList + '\'' +
'}';
}
}
|
try {
LOGGER.debug("Executing ViewConfigReloader.reloadViewConfig('{}')", rootClassNameList);
Class<?> reloaderClazz = Class.forName(ViewConfigReloader.class.getName(), true, classLoader);
Method m = reloaderClazz.getDeclaredMethod("reloadViewConfig", new Class[] {ClassLoader.class, Object.class, java.util.List.class});
m.invoke(null, classLoader, viewConfigExtension, rootClassNameList);
} catch (NoSuchMethodException e) {
throw new IllegalStateException("Plugin error, method not found", e);
} catch (InvocationTargetException e) {
LOGGER.error("Error refreshing classes '{}' in appClassLoader {}", e, rootClassNameList, classLoader);
} catch (IllegalAccessException e) {
throw new IllegalStateException("Plugin error, illegal access", e);
} catch (ClassNotFoundException e) {
throw new IllegalStateException("Plugin error, CDI class not found in classloader", e);
}
| 418 | 261 | 679 |
<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-deltaspike-plugin/src/main/java/org/hotswap/agent/plugin/deltaspike/jsf/ViewConfigReloader.java
|
ViewConfigReloader
|
doAddPageDefinition
|
class ViewConfigReloader {
private static AgentLogger LOGGER = AgentLogger.getLogger(ViewConfigReloader.class);
public static void reloadViewConfig(ClassLoader classLoader, Object viewConfigExtensionObj, List rootClassNameList) {
try {
ViewConfigExtension viewConfigExtension = (ViewConfigExtension) viewConfigExtensionObj;
viewConfigExtension.freeViewConfigCache(null);
ReflectionHelper.invoke(viewConfigExtension, viewConfigExtension.getClass(), "resetRootNode", null);
for (Object oClass : rootClassNameList) {
Class<?> viewConfigRootClass = Class.forName((String)oClass, true, classLoader);
if (viewConfigRootClass != null) {
doAddPageDefinition(classLoader, viewConfigExtension, viewConfigRootClass);
}
}
viewConfigExtension.buildViewConfig(null);
} catch (ClassNotFoundException e) {
LOGGER.error("Deltaspike view config reloading failed.", e);
}
}
private static void doAddPageDefinition(ClassLoader classLoader, ViewConfigExtension viewConfigExtension, Class<?> viewConfigClass) {<FILL_FUNCTION_BODY>}
}
|
if (ViewConfigUtils.isFolderConfig(viewConfigClass)) {
viewConfigExtension.addFolderDefinition(viewConfigClass);
} else if (ViewConfig.class.isAssignableFrom(viewConfigClass)){
viewConfigExtension.addPageDefinition((Class<? extends ViewConfig>) viewConfigClass);
}
for (Class<?> subClass: viewConfigClass.getDeclaredClasses()) {
Class<?> reloadedSubclass;
try {
reloadedSubclass = Class.forName(subClass.getName(), true, classLoader);
if (reloadedSubclass != null) {
doAddPageDefinition(classLoader, viewConfigExtension, reloadedSubclass);
}
} catch (ClassNotFoundException e) {
LOGGER.debug("ViewConfig subclass '{}' removed", subClass.getName());
}
}
| 296 | 211 | 507 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/plugin/hotswap-agent-deltaspike-plugin/src/main/java/org/hotswap/agent/plugin/deltaspike/jsf/ViewConfigResolverUtils.java
|
ViewConfigResolverUtils
|
findViewConfigRootClasses
|
class ViewConfigResolverUtils {
public static List findViewConfigRootClasses(ViewConfigNode configNode) {<FILL_FUNCTION_BODY>}
}
|
List result = new ArrayList<>();
if (configNode != null) {
if (configNode.getSource() != null) {
result.add(configNode.getSource());
} else {
for (ViewConfigNode childNode : configNode.getChildren()) {
if (childNode.getSource() != null) {
result.add(childNode.getSource());
}
}
}
}
return result;
| 40 | 116 | 156 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/plugin/hotswap-agent-deltaspike-plugin/src/main/java/org/hotswap/agent/plugin/deltaspike/transformer/DeltaSpikeProxyContextualLifecycleTransformer.java
|
DeltaSpikeProxyContextualLifecycleTransformer
|
patchDeltaSpikeProxyContextualLifecycle
|
class DeltaSpikeProxyContextualLifecycleTransformer {
private static AgentLogger LOGGER = AgentLogger.getLogger(DeltaSpikeProxyContextualLifecycleTransformer.class);
/**
* Register DeltaspikePlugin and add hook to create method to DeltaSpikeProxyContextualLifecycle.
*
* @param classPool the class pool
* @param ctClass the ctclass
* @throws CannotCompileException the cannot compile exception
* @throws NotFoundException the not found exception
*/
@OnClassLoadEvent(classNameRegexp = "org.apache.deltaspike.proxy.api.DeltaSpikeProxyContextualLifecycle")
public static void patchDeltaSpikeProxyContextualLifecycle(ClassPool classPool, CtClass ctClass) throws CannotCompileException, NotFoundException {<FILL_FUNCTION_BODY>}
}
|
if (HaCdiCommons.isJakarta(classPool)) {
return;
}
CtMethod methodCreate = ctClass.getDeclaredMethod("create");
methodCreate.insertAfter(
"{" +
PluginManagerInvoker.buildInitializePlugin(DeltaSpikePlugin.class) +
PluginManagerInvoker.buildCallPluginMethod(DeltaSpikePlugin.class, "registerRepoProxy", "$_", "java.lang.Object", "this.targetClass", "java.lang.Class")+
"}" +
"return $_;"
);
LOGGER.debug("org.apache.deltaspike.proxy.api.DeltaSpikeProxyContextualLifecycle - registration hook added.");
| 233 | 189 | 422 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/plugin/hotswap-agent-deltaspike-plugin/src/main/java/org/hotswap/agent/plugin/deltaspike/transformer/DeltaSpikeProxyTransformer.java
|
DeltaSpikeProxyTransformer
|
edit
|
class DeltaSpikeProxyTransformer {
private static AgentLogger LOGGER = AgentLogger.getLogger(DeltaSpikeProxyTransformer.class);
/**
* Delegates ClassUtils.tryToLoadClassForName to org.hotswap.agent.plugin.deltaspike.command.ProxyClassLoadingDelegate::tryToLoadClassForName
*
* @param classPool the class pool
* @param ctClass the ct class
* @throws NotFoundException the not found exception
* @throws CannotCompileException the cannot compile exception
*/
@OnClassLoadEvent(classNameRegexp = "org.apache.deltaspike.proxy.api.DeltaSpikeProxyFactory")
public static void patchDeltaSpikeProxyFactory(ClassPool classPool, CtClass ctClass) throws NotFoundException, CannotCompileException {
if (HaCdiCommons.isJakarta(classPool)) {
return;
}
// Deltaspike 1.5
instrumentTryToLoadClassForName(ctClass, "getProxyClass");
instrumentTryToLoadClassForName(ctClass, "createProxyClass");
// Deltaspike 1.7, 1.8, 1.9
instrumentTryToLoadClassForName(ctClass, "resolveAlreadyDefinedProxyClass");
}
private static void instrumentTryToLoadClassForName(CtClass ctClass, String methodName) throws CannotCompileException {
try {
CtMethod getProxyClassMethod = ctClass.getDeclaredMethod(methodName);
getProxyClassMethod.instrument(
new ExprEditor() {
public void edit(MethodCall m) throws CannotCompileException {
if (m.getClassName().equals("org.apache.deltaspike.core.util.ClassUtils") && m.getMethodName().equals("tryToLoadClassForName"))
m.replace("{ $_ = org.hotswap.agent.plugin.deltaspike.command.ProxyClassLoadingDelegate.tryToLoadClassForName($$); }");
}
});
} catch (NotFoundException e) {
LOGGER.debug("Method '{}' not found in '{}'.", methodName, ctClass.getName());
}
}
/**
* Delegates loadClass to org.hotswap.agent.plugin.deltaspike.command.ProxyClassLoadingDelegate::loadClass
*
* @param classPool the class pool
* @param ctClass the ct class
* @throws NotFoundException the not found exception
* @throws CannotCompileException the cannot compile exception
*/
@OnClassLoadEvent(classNameRegexp = "org.apache.deltaspike.proxy.impl.AsmProxyClassGenerator")
public static void patchAsmProxyClassGenerator(ClassPool classPool, CtClass ctClass) throws NotFoundException, CannotCompileException {
if (HaCdiCommons.isJakarta(classPool)) {
return;
}
CtMethod generateProxyClassMethod = ctClass.getDeclaredMethod("generateProxyClass");
generateProxyClassMethod.instrument(
new ExprEditor() {
public void edit(MethodCall m) throws CannotCompileException {
if (m.getClassName().equals("org.apache.deltaspike.proxy.impl.AsmProxyClassGenerator") && m.getMethodName().equals("loadClass"))
m.replace("{ $_ = org.hotswap.agent.plugin.deltaspike.command.ProxyClassLoadingDelegate.loadClass($$); }");
}
});
LOGGER.debug("org.apache.deltaspike.proxy.impl.AsmProxyClassGenerator patched.");
}
/**
* Patch asm delta spike proxy class generator.
*
* @param classPool the class pool
* @param ctClass the ct class
* @throws NotFoundException the not found exception
* @throws CannotCompileException the cannot compile exception
*/
@OnClassLoadEvent(classNameRegexp = "org.apache.deltaspike.proxy.impl.AsmDeltaSpikeProxyClassGenerator")
public static void patchAsmDeltaSpikeProxyClassGenerator(ClassPool classPool, CtClass ctClass) throws NotFoundException, CannotCompileException {
if (HaCdiCommons.isJakarta(classPool)) {
return;
}
CtMethod generateProxyClassMethod = ctClass.getDeclaredMethod("generateProxyClass");
generateProxyClassMethod.instrument(
new ExprEditor() {
public void edit(MethodCall m) throws CannotCompileException {<FILL_FUNCTION_BODY>}
});
LOGGER.debug("org.apache.deltaspike.proxy.impl.AsmDeltaSpikeProxyClassGenerator patched.");
}
}
|
if (m.getClassName().equals("org.apache.deltaspike.proxy.impl.AsmDeltaSpikeProxyClassGenerator") && m.getMethodName().equals("loadClass")) {
m.replace("{ $_ = org.hotswap.agent.plugin.deltaspike.command.ProxyClassLoadingDelegate.loadClass($$); }");
} else if (m.getClassName().equals("org.apache.deltaspike.proxy.impl.ClassDefiner") && m.getMethodName().equals("defineClass")) {
m.replace("{ $_ = org.hotswap.agent.plugin.deltaspike.command.ProxyClassLoadingDelegate.defineClass($$); }");
}
| 1,221 | 182 | 1,403 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/plugin/hotswap-agent-deltaspike-plugin/src/main/java/org/hotswap/agent/plugin/deltaspike/transformer/HaAfteBeanDiscovery.java
|
HaAfteBeanDiscovery
|
$$ha$afterBeanDiscovery
|
class HaAfteBeanDiscovery {
public void $$ha$afterBeanDiscovery(@Observes AfterBeanDiscovery before) {<FILL_FUNCTION_BODY>}
}
|
PluginManagerInvoker.callPluginMethod(DeltaSpikePlugin.class, getClass().getClassLoader(),
"registerRepositoryClasses", new Class[] { List.class }, new Object[] { ReflectionHelper.get(this, "repositoryClasses") });
| 46 | 62 | 108 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/plugin/hotswap-agent-deltaspike-plugin/src/main/java/org/hotswap/agent/plugin/deltaspike/transformer/PartialBeanTransformer.java
|
PartialBeanTransformer
|
patchPartialBeanBindingExtension
|
class PartialBeanTransformer {
private static AgentLogger LOGGER = AgentLogger.getLogger(PartialBeanTransformer.class);
/**
* Patch partial bean binding extension.
*
* @param classPool the class pool
* @param ctClass the ct class
* @throws NotFoundException the not found exception
* @throws CannotCompileException the cannot compile exception
*/
@OnClassLoadEvent(classNameRegexp = "org.apache.deltaspike.partialbean.impl.PartialBeanBindingExtension")
public static void patchPartialBeanBindingExtension(ClassPool classPool, CtClass ctClass) throws NotFoundException, CannotCompileException {<FILL_FUNCTION_BODY>}
}
|
if (HaCdiCommons.isJakarta(classPool)) {
return;
}
CtMethod init = ctClass.getDeclaredMethod("init");
init.insertAfter(PluginManagerInvoker.buildInitializePlugin(DeltaSpikePlugin.class));
LOGGER.debug("org.apache.deltaspike.partialbean.impl.PartialBeanBindingExtension enhanced with plugin initialization.");
CtMethod createPartialBeanMethod = ctClass.getDeclaredMethod("createPartialBean");
createPartialBeanMethod.insertAfter(
"if (" + PluginManager.class.getName() + ".getInstance().isPluginInitialized(\"" + DeltaSpikePlugin.class.getName() + "\", beanClass.getClassLoader())) {" +
PluginManagerInvoker.buildCallPluginMethod(DeltaSpikePlugin.class, "registerPartialBean",
"$_", "java.lang.Object",
"beanClass", "java.lang.Class"
) +
"}" +
"return $_;"
);
LOGGER.debug("org.apache.deltaspike.partialbean.impl.PartialBeanBindingExtension patched.");
| 186 | 292 | 478 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/plugin/hotswap-agent-deltaspike-plugin/src/main/java/org/hotswap/agent/plugin/deltaspike/transformer/RepositoryTransformer.java
|
RepositoryTransformer
|
patchRepositoryMetadataHandler
|
class RepositoryTransformer {
private static AgentLogger LOGGER = AgentLogger.getLogger(RepositoryTransformer.class);
public static final String REINITIALIZE_METHOD = "$$ha$reinitialize";
/**
* Register DeltaspikePlugin and add reinitialization method to RepositoryComponent (ds<1.9)
*
* @param classPool the class pool
* @param ctClass the ct class
* @throws CannotCompileException the cannot compile exception
*/
@OnClassLoadEvent(classNameRegexp = "org.apache.deltaspike.data.impl.meta.RepositoryComponent")
public static void patchRepositoryComponent(ClassPool classPool, CtClass ctClass) throws CannotCompileException {
if (HaCdiCommons.isJakarta(classPool)) {
return;
}
StringBuilder src = new StringBuilder("{");
src.append(PluginManagerInvoker.buildInitializePlugin(DeltaSpikePlugin.class));
src.append(PluginManagerInvoker.buildCallPluginMethod(DeltaSpikePlugin.class, "registerRepoComponent",
"this", "java.lang.Object",
"this.repoClass", "java.lang.Class"));
src.append("}");
for (CtConstructor constructor : ctClass.getDeclaredConstructors()) {
constructor.insertAfter(src.toString());
}
ctClass.addMethod(CtNewMethod.make("public void " + REINITIALIZE_METHOD + "() {" +
" this.methods.clear(); " +
" initialize();" +
"}", ctClass));
LOGGER.debug("org.apache.deltaspike.data.impl.meta.RepositoryComponent - registration hook and reinitialization method added.");
}
/**
* Register DeltaspikePlugin and add reinitialization method to RepositoryMetadataHandler. (ds>=1.9)
*
* @param classPool the class pool
* @param ctClass the ctclass
* @throws CannotCompileException the cannot compile exception
* @throws NotFoundException the not found exception
*/
@OnClassLoadEvent(classNameRegexp = "org.apache.deltaspike.data.impl.meta.RepositoryMetadataHandler")
public static void patchRepositoryMetadataHandler(ClassPool classPool, CtClass ctClass) throws CannotCompileException, NotFoundException {<FILL_FUNCTION_BODY>}
/**
* Register DeltaspikePlugin and register repository classes.
*
* @param ctClass the ctclass
* @throws CannotCompileException the cannot compile exception
* @throws NotFoundException
* @throws org.hotswap.agent.javassist.CannotCompileException
*/
@OnClassLoadEvent(classNameRegexp = "org.apache.deltaspike.data.impl.RepositoryExtension")
public static void patchRepositoryExtension(ClassPool classPool, CtClass ctClass) throws CannotCompileException, NotFoundException, org.hotswap.agent.javassist.CannotCompileException {
if (HaCdiCommons.isJakarta(classPool)) {
return;
}
if (ctClass.getSuperclassName().equals(Object.class.getName())) {
ctClass.setSuperclass(classPool.get(HaAfteBeanDiscovery.class.getName()));
} else {
LOGGER.error("org.apache.deltaspike.data.impl.RepositoryExtension patch failed. Expected superclass java.lang.Object, found:" + ctClass.getSuperclassName());
}
LOGGER.debug("org.apache.deltaspike.data.impl.RepositoryExtension - registration hook and registration repository classes added.");
}
}
|
if (HaCdiCommons.isJakarta(classPool)) {
return;
}
ctClass.addMethod(CtNewMethod.make("public void " + REINITIALIZE_METHOD + "(java.lang.Class repositoryClass) {" +
"org.apache.deltaspike.data.impl.meta.RepositoryMetadata metadata = metadataInitializer.init(repositoryClass, this.beanManager);" +
"this.repositoriesMetadata.put(repositoryClass, metadata);" +
"}", ctClass));
LOGGER.debug("org.apache.deltaspike.data.impl.meta.RepositoryMetadataHandler - registration hook and reinitialization method added.");
| 945 | 175 | 1,120 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/plugin/hotswap-agent-deltaspike-plugin/src/main/java/org/hotswap/agent/plugin/deltaspike/transformer/ViewConfigTransformer.java
|
ViewConfigTransformer
|
edit
|
class ViewConfigTransformer {
private static AgentLogger LOGGER = AgentLogger.getLogger(ViewConfigTransformer.class);
private static final String VIEW_CONFIG_RESOLVER_PROXY_FIELD = "$$ha$viewConfigResolverProxy";
/**
* Register DeltaspikePlugin and add reinitialization method to RepositoryComponent
*
* @param classPool the class pool
* @param ctClass the ct class
* @throws CannotCompileException the cannot compile exception
* @throws NotFoundException the not found exception
*/
@OnClassLoadEvent(classNameRegexp = "org.apache.deltaspike.jsf.impl.config.view.ViewConfigExtension")
public static void patchViewConfigExtension(ClassPool classPool, CtClass ctClass) throws CannotCompileException, NotFoundException {
if (HaCdiCommons.isJakarta(classPool)) {
return;
}
CtMethod init = ctClass.getDeclaredMethod("init");
init.insertAfter(
"{" +
"if (this.isActivated) {" +
PluginManagerInvoker.buildInitializePlugin(DeltaSpikePlugin.class)+
"}" +
"}"
);
LOGGER.debug("org.apache.deltaspike.jsf.impl.config.view.ViewConfigExtension enhanced with plugin initialization.");
CtClass viewConfigResProxyClass = classPool.get("org.hotswap.agent.plugin.deltaspike.jsf.ViewConfigResolverProxy");
CtField viewConfigResProxyField = new CtField(viewConfigResProxyClass, VIEW_CONFIG_RESOLVER_PROXY_FIELD, ctClass);
ctClass.addField(viewConfigResProxyField);
CtMethod generateProxyClassMethod = ctClass.getDeclaredMethod("transformMetaDataTree");
generateProxyClassMethod.instrument(
new ExprEditor() {
public void edit(NewExpr e) throws CannotCompileException {<FILL_FUNCTION_BODY>}
}
);
}
}
|
if (e.getClassName().equals("org.apache.deltaspike.jsf.impl.config.view.DefaultViewConfigResolver"))
e.replace(
"{ " +
"java.lang.Object _resolver = new org.apache.deltaspike.jsf.impl.config.view.DefaultViewConfigResolver($$); " +
"if (this." + VIEW_CONFIG_RESOLVER_PROXY_FIELD + "==null) {" +
"this." + VIEW_CONFIG_RESOLVER_PROXY_FIELD + "=new org.hotswap.agent.plugin.deltaspike.jsf.ViewConfigResolverProxy();" +
"}" +
"this." + VIEW_CONFIG_RESOLVER_PROXY_FIELD + ".setViewConfigResolver(_resolver);" +
"java.util.List _list = org.hotswap.agent.plugin.deltaspike.jsf.ViewConfigResolverUtils.findViewConfigRootClasses(this.rootViewConfigNode);" +
PluginManagerInvoker.buildCallPluginMethod(DeltaSpikePlugin.class, "registerViewConfigRootClasses",
"this", "java.lang.Object", "_list", "java.util.List") +
" $_ = this." + VIEW_CONFIG_RESOLVER_PROXY_FIELD + ";" +
"}"
);
| 527 | 341 | 868 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/plugin/hotswap-agent-el-resolver-plugin/src/main/java/org/hotswap/agent/plugin/elresolver/PurgeBeanELResolverCacheCommand.java
|
PurgeBeanELResolverCacheCommand
|
equals
|
class PurgeBeanELResolverCacheCommand extends MergeableCommand {
private static AgentLogger LOGGER = AgentLogger.getLogger(PurgeBeanELResolverCacheCommand.class);
private ClassLoader appClassLoader;
private Set<Object> registeredBeanELResolvers;
public PurgeBeanELResolverCacheCommand(ClassLoader appClassLoader, Set<Object> registeredBeanELResolvers)
{
this.appClassLoader = appClassLoader;
this.registeredBeanELResolvers = registeredBeanELResolvers;
}
@Override
public void executeCommand() {
LOGGER.debug("Purging BeanELResolver cache.");
try {
Class<?> beanElResolverClass = Class.forName("javax.el.BeanELResolver", true, appClassLoader);
Method beanElResolverMethod = beanElResolverClass.getDeclaredMethod(ELResolverPlugin.PURGE_CLASS_CACHE_METHOD_NAME, ClassLoader.class);
for (Object registeredBeanELResolver : registeredBeanELResolvers) {
beanElResolverMethod.invoke(registeredBeanELResolver, appClassLoader);
}
} catch (ClassNotFoundException e) {
LOGGER.debug("BeanELResolver class not found in class loader {}.", appClassLoader);
} catch (Exception e) {
LOGGER.error("Error purging BeanELResolver cache.", e);
}
}
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
int result = appClassLoader.hashCode();
return result;
}
@Override
public String toString() {
return "PurgeBeanELResolverCacheCommand{appClassLoader=" + appClassLoader + '}';
}
}
|
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PurgeBeanELResolverCacheCommand that = (PurgeBeanELResolverCacheCommand) o;
if (!appClassLoader.equals(that.appClassLoader)) return false;
return true;
| 443 | 85 | 528 |
<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-el-resolver-plugin/src/main/java/org/hotswap/agent/plugin/elresolver/PurgeJbossReflectionUtil.java
|
PurgeJbossReflectionUtil
|
executeCommand
|
class PurgeJbossReflectionUtil extends MergeableCommand {
private static AgentLogger LOGGER = AgentLogger.getLogger(PurgeBeanELResolverCacheCommand.class);
private ClassLoader appClassLoader;
public PurgeJbossReflectionUtil(ClassLoader appClassLoader) {
this.appClassLoader = appClassLoader;
}
@Override
public void executeCommand() {<FILL_FUNCTION_BODY>}
}
|
try {
LOGGER.debug("Flushing Jboss ReflectionUtil");
Class<?> reflectionUtilClass = appClassLoader.loadClass("org.jboss.el.util.ReflectionUtil");
Object cache = ReflectionHelper.get(null, reflectionUtilClass, "methodCache");
ReflectionHelper.invoke(cache, cache.getClass(), "clear", null);
} catch (Exception e) {
LOGGER.error("executeCommand() exception {}.", e.getMessage());
}
| 115 | 122 | 237 |
<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-freemarker-plugin/src/main/java/org/hotswap/agent/plugin/freemarker/FreeMarkerPlugin.java
|
FreeMarkerPlugin
|
executeCommand
|
class FreeMarkerPlugin {
private static final AgentLogger LOGGER = AgentLogger.getLogger(FreeMarkerPlugin.class);
@Init
private Scheduler scheduler;
private final Command clearIntrospectionCache = new Command() {
@Override
public void executeCommand() {<FILL_FUNCTION_BODY>}
};
private Object freeMarkerServlet;
@OnClassLoadEvent(classNameRegexp = "freemarker.ext.servlet.FreemarkerServlet")
public static void init(ClassPool classPool, final CtClass ctClass) throws NotFoundException, CannotCompileException {
String src = PluginManagerInvoker.buildInitializePlugin(FreeMarkerPlugin.class);
src += PluginManagerInvoker.buildCallPluginMethod(FreeMarkerPlugin.class,
"registerServlet", "this", "java.lang.Object");
CtMethod init = ctClass.getDeclaredMethod("init");
init.insertAfter(src);
LOGGER.debug("Patched freemarker.ext.servlet.FreemarkerServlet");
}
public void registerServlet(final Object freeMarkerServlet) {
this.freeMarkerServlet = freeMarkerServlet;
LOGGER.info("Plugin {} initialized for servlet {}", getClass(), this.freeMarkerServlet);
}
@OnClassLoadEvent(classNameRegexp = ".*", events = {LoadEvent.REDEFINE})
public void cacheReloader(CtClass ctClass) {
scheduler.scheduleCommand(clearIntrospectionCache, 500);
}
@OnClassLoadEvent(classNameRegexp = "org.springframework.ui.freemarker.FreeMarkerConfigurationFactory")
public static void patchCreateConfiguration(ClassPool classPool, final CtClass ctClass) {
try {
CtMethod method = ctClass.getDeclaredMethod("createConfiguration", new CtClass[]{});
method.insertBefore("this.preferFileSystemAccess = false;");
method.insertBefore("String[] $ha$newArray = new String[this.templateLoaderPaths.length + 1]; " +
"$ha$newArray[0] = \"classpath:/$ha$freemarker\";" +
"for (int i = 0; i < this.templateLoaderPaths.length; i++) {" +
" $ha$newArray[i + 1] = this.templateLoaderPaths[i];" +
"}" + "this.templateLoaderPaths = $ha$newArray;");
} catch (NotFoundException | CannotCompileException e) {
LOGGER.debug("Cannot patch patchCreateConfiguration method for {}", ctClass.getName(), e);
}
}
@OnClassLoadEvent(classNameRegexp = "freemarker.template.Configuration")
public static void patchCreateTemplateCache(ClassPool classPool, final CtClass ctClass) {
try {
CtMethod method = ctClass.getDeclaredMethod("createTemplateCache", new CtClass[]{});
method.insertAfter("cache.setDelay(0L);");
} catch (NotFoundException | CannotCompileException e) {
LOGGER.debug("Cannot patch patchCreateTemplateCache method for {}", ctClass.getName(), e);
}
}
}
|
LOGGER.debug("Clearing FreeMarker BeanWrapper class introspection class.");
try {
Object config = ReflectionHelper.get(freeMarkerServlet, "config");
Object objectWrapper = ReflectionHelper.get(config, "objectWrapper");
ReflectionHelper.invoke(objectWrapper, objectWrapper.getClass(), "clearClassIntrospecitonCache", new Class[]{});
LOGGER.info("Cleared FreeMarker introspection cache");
} catch (Exception e) {
LOGGER.error("Error clearing FreeMarker introspection cache", e);
}
| 811 | 140 | 951 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/plugin/hotswap-agent-glassfish-plugin/src/main/java/org/hotswap/agent/plugin/glassfish/GlassFishPlugin.java
|
GlassFishPlugin
|
transformFelix
|
class GlassFishPlugin {
protected static AgentLogger LOGGER = AgentLogger.getLogger(GlassFishPlugin.class);
private static String FRAMEWORK_BOOTDELEGATION = "org.osgi.framework.bootdelegation";
private static final String BOOTDELEGATION_PACKAGES =
"org.hotswap.agent, " +
"org.hotswap.agent.*";
@OnClassLoadEvent(classNameRegexp = "org.apache.felix.framework.Felix")
public static void transformFelix(ClassPool classPool, CtClass ctClass) throws NotFoundException, CannotCompileException {<FILL_FUNCTION_BODY>}
@OnClassLoadEvent(classNameRegexp = "org.apache.felix.framework.BundleWiringImpl")
public static void transformBundleClassLoader(ClassPool classPool, CtClass ctClass) throws NotFoundException, CannotCompileException {
// String initializePlugin = PluginManagerInvoker.buildInitializePlugin(GlassFishPlugin.class);
//
// for (CtConstructor constructor : ctClass.getDeclaredConstructors()) {
// constructor.insertAfter(initializePlugin);
// }
//
/*
CtMethod getClassLoaderInternalCopy = CtMethod.make("public ClassLoader __getClassLoaderInternal(){return null;}", ctClass);
getClassLoaderInternalCopy.setBody(ctClass.getDeclaredMethod("getClassLoaderInternal"), null);
ctClass.addMethod(getClassLoaderInternalCopy);
CtMethod getClassLoaderInternal = ctClass.getDeclaredMethod("getClassLoaderInternal");
getClassLoaderInternal.setBody(
"{ " +
"boolean wasClassLoader = (m_classLoader == null); " +
"ClassLoader ret = __getClassLoaderInternal();" +
"if (!wasClassLoader && ret != null) {" +
PluginManagerInvoker.buildInitializePlugin(GlassFishPlugin.class, "ret") +
"}" +
"return ret;" +
"}"
);
LOGGER.debug("org.apache.felix.framework.BundleWiringImpl resource bundles registration.");
*/
}
}
|
CtClass[] constructorParams = new CtClass[] {
classPool.get("java.util.Map")
};
CtConstructor declaredConstructor = ctClass.getDeclaredConstructor(constructorParams);
declaredConstructor.insertBefore(
"{" +
"if ($1 == null) { " +
"$1 = new java.util.HashMap();" +
"}" +
"String $$ha$bootDeleg = (String) $1.get(\"" + FRAMEWORK_BOOTDELEGATION + "\");" +
"if ($$ha$bootDeleg == null) {" +
"$$ha$bootDeleg = \"\";" +
"}" +
"if ($$ha$bootDeleg.indexOf(\"org.hotswap.agent\") == -1) {" +
"$$ha$bootDeleg = $$ha$bootDeleg.trim();" +
"if (!$$ha$bootDeleg.isEmpty()) {" +
"$$ha$bootDeleg = $$ha$bootDeleg + \", \";" +
"}" +
"$$ha$bootDeleg = $$ha$bootDeleg + \"" + BOOTDELEGATION_PACKAGES + "\";" +
"$1.put(\"" + FRAMEWORK_BOOTDELEGATION + "\", $$ha$bootDeleg);" +
"}" +
"}"
);
// declaredConstructor.insertAfter(PluginManagerInvoker.buildInitializePlugin(GlassFishPlugin.class));
LOGGER.debug("Class 'org.apache.felix.framework.Felix' patched in classLoader {}.");
| 560 | 410 | 970 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/plugin/hotswap-agent-glassfish-plugin/src/main/java/org/hotswap/agent/plugin/glassfish/WebappClassLoaderTransformer.java
|
WebappClassLoaderTransformer
|
patchWebappClassLoader
|
class WebappClassLoaderTransformer {
protected static AgentLogger LOGGER = AgentLogger.getLogger(WebappClassLoaderTransformer.class);
private static boolean webappClassLoaderPatched = false;
@OnClassLoadEvent(classNameRegexp = "org.glassfish.web.loader.WebappClassLoader")
public static void patchWebappClassLoader(ClassPool classPool,CtClass ctClass) throws CannotCompileException, NotFoundException {<FILL_FUNCTION_BODY>}
}
|
if (!webappClassLoaderPatched) {
try {
// clear classloader cache
ctClass.getDeclaredMethod("getResource", new CtClass[]{classPool.get("java.lang.String")}).insertBefore(
"resourceEntries.clear();"
);
ctClass.getDeclaredMethod("getResourceAsStream", new CtClass[]{classPool.get("java.lang.String")}).insertBefore(
"resourceEntries.clear();"
);
webappClassLoaderPatched = true;
} catch (NotFoundException e) {
LOGGER.trace("WebappClassLoader does not contain getResource(), getResourceAsStream method.");
}
}
| 126 | 174 | 300 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/plugin/hotswap-agent-hibernate-jakarta-plugin/src/main/java/org/hotswap/agent/plugin/hibernate_jakarta/HibernateJakartaPlugin.java
|
HibernateJakartaPlugin
|
refresh
|
class HibernateJakartaPlugin
{
private static final String ENTITY_ANNOTATION = "jakarta.persistence.Entity";
private static AgentLogger LOGGER = AgentLogger.getLogger(HibernateJakartaPlugin.class);
@Init
Scheduler scheduler;
@Init
ClassLoader appClassLoader;
Set<Object> regAnnotatedMetaDataProviders = Collections.newSetFromMap(new WeakHashMap<Object, Boolean>());
Map<Object, String> regBeanMetaDataManagersMap = new WeakHashMap<Object, String>();
// refresh commands
Command reloadEntityManagerFactoryCommand =
new ReflectionCommand(this, HibernateRefreshCommands.class.getName(), "reloadEntityManagerFactory");
Command reloadSessionFactoryCommand =
new ReflectionCommand(this, HibernateRefreshCommands.class.getName(), "reloadSessionFactory");
private Command invalidateHibernateValidatorCaches = new Command() {
@Override
public void executeCommand() {
LOGGER.debug("Refreshing BeanMetaDataManagerCache/AnnotatedMetaDataProvider cache.");
try {
Method resetCacheMethod1 = resolveClass("org.hibernate.validator.internal.metadata.provider.AnnotationMetaDataProvider").getDeclaredMethod("$$ha$resetCache");
for (Object regAnnotatedDataManager : regAnnotatedMetaDataProviders) {
LOGGER.debug("Invoking org.hibernate.validator.internal.metadata.provider.AnnotationMetaDataProvider.$$ha$resetCache on {}", regAnnotatedDataManager);
resetCacheMethod1.invoke(regAnnotatedDataManager);
}
for (Map.Entry<Object, String> entry : regBeanMetaDataManagersMap.entrySet()) {
LOGGER.debug("Invoking " + entry.getValue() + " .$$ha$resetCache on {}", entry.getKey());
Method resetCacheMethod2 = resolveClass(entry.getValue()).getDeclaredMethod("$$ha$resetCache");
resetCacheMethod2.invoke(entry.getKey());
}
} catch (Exception e) {
LOGGER.error("Error refreshing BeanMetaDataManagerCache/AnnotatedMetaDataProvider cache.", e);
}
}
};
// is EJB3 or plain hibernate
boolean hibernateEjb;
/**
* Plugin initialization properties (from HibernatePersistenceHelper or SessionFactoryProxy)
*/
public void init(String version, Boolean hibernateEjb) {
LOGGER.info("Hibernate plugin initialized - Hibernate Core version '{}'", version);
this.hibernateEjb = hibernateEjb;
}
/**
* Reload after entity class change. It covers also @Entity annotation removal.
*/
@OnClassLoadEvent(classNameRegexp = ".*", events = LoadEvent.REDEFINE)
public void entityReload(CtClass clazz, Class original) {
// TODO list of entity/resource files is known to hibernate, better to check this list
if (AnnotationHelper.hasAnnotation(original, ENTITY_ANNOTATION)
|| AnnotationHelper.hasAnnotation(clazz, ENTITY_ANNOTATION)
) {
LOGGER.debug("Entity reload class {}, original classloader {}", clazz.getName(), original.getClassLoader());
refresh(100);
}
}
/**
* New entity class - not covered by reloading mechanism.
* <p/>
* Increase the reload timeout to avoid duplicate reloading in case of recompile with IDE
* and delete/create event sequence - than create is cached by this event and hotswap for
* the same class by entityReload.
*/
@OnClassFileEvent(classNameRegexp = ".*", events = {FileEvent.CREATE})
public void newEntity(CtClass clazz) throws Exception {
if (AnnotationHelper.hasAnnotation(clazz, ENTITY_ANNOTATION)) {
refresh(500);
}
}
@OnClassLoadEvent(classNameRegexp = ".*", events = LoadEvent.REDEFINE)
public void invalidateClassCache() throws Exception {
if (!regBeanMetaDataManagersMap.isEmpty() || !regAnnotatedMetaDataProviders.isEmpty()) {
scheduler.scheduleCommand(invalidateHibernateValidatorCaches);
}
}
// reload the configuration - schedule a command to run in the application classloader and merge
// duplicate commands.
private void refresh(int timeout) {<FILL_FUNCTION_BODY>}
public void registerAnnotationMetaDataProvider(Object annotatedMetaDataProvider) {
regAnnotatedMetaDataProviders.add(annotatedMetaDataProvider);
}
public void registerBeanMetaDataManager(Object beanMetaDataManager, String beanMetaDataManagerClassName) {
regBeanMetaDataManagersMap.put(beanMetaDataManager, beanMetaDataManagerClassName);
}
private Class<?> resolveClass(String name) throws ClassNotFoundException {
return Class.forName(name, true, appClassLoader);
}
}
|
if (hibernateEjb) {
scheduler.scheduleCommand(reloadEntityManagerFactoryCommand, timeout);
} else {
scheduler.scheduleCommand(reloadSessionFactoryCommand, timeout);
}
| 1,286 | 57 | 1,343 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/plugin/hotswap-agent-hibernate-jakarta-plugin/src/main/java/org/hotswap/agent/plugin/hibernate_jakarta/HibernatePersistenceHelper.java
|
HibernatePersistenceHelper
|
createEntityManagerFactoryProxy
|
class HibernatePersistenceHelper {
private static AgentLogger LOGGER = AgentLogger.getLogger(HibernatePersistenceHelper.class);
// each persistence unit should be wrapped only once
static Set<String> wrappedPersistenceUnitNames = new HashSet<>();
/**
* @param info persistent unit definition
* @param properties properties to create entity manager factory
* @param original entity manager factory
* @return proxy of entity manager
*/
public static EntityManagerFactory createContainerEntityManagerFactoryProxy(Object builder, PersistenceUnitInfo info, Map properties,
EntityManagerFactory original) {
// ensure only once
if (wrappedPersistenceUnitNames.contains(info.getPersistenceUnitName())) {
return original;
}
wrappedPersistenceUnitNames.add(info.getPersistenceUnitName());
EntityManagerFactoryProxy wrapper = EntityManagerFactoryProxy.getWrapper(info.getPersistenceUnitName());
EntityManagerFactory proxy = wrapper.proxy(builder, original, info.getPersistenceUnitName(), info, properties);
initPlugin(original);
LOGGER.debug("Returning container EntityManager proxy {} instead of EntityManager {}", proxy.getClass(), original);
return proxy;
}
/**
* @param persistenceUnitName persistent unit name
* @param properties properties to create entity manager factory
* @param original entity manager factory
* @return proxy of entity manager
*/
public static EntityManagerFactory createEntityManagerFactoryProxy(Object builder, String persistenceUnitName, Map properties,
EntityManagerFactory original) {<FILL_FUNCTION_BODY>}
// call initializePlugin and setup version and EJB flag
private static void initPlugin(EntityManagerFactory original) {
ClassLoader appClassLoader = original.getClass().getClassLoader();
String version = Version.getVersionString();
PluginManagerInvoker.callInitializePlugin(HibernateJakartaPlugin.class, appClassLoader);
PluginManagerInvoker.callPluginMethod(HibernateJakartaPlugin.class, appClassLoader,
"init",
new Class[]{String.class, Boolean.class},
new Object[]{version, true});
}
}
|
// ensure only once
if (wrappedPersistenceUnitNames.contains(persistenceUnitName)) {
return original;
}
wrappedPersistenceUnitNames.add(persistenceUnitName);
EntityManagerFactoryProxy wrapper = EntityManagerFactoryProxy.getWrapper(persistenceUnitName);
EntityManagerFactory proxy = wrapper.proxy(builder, original, persistenceUnitName, null, properties);
initPlugin(original);
LOGGER.debug("Returning EntityManager proxy {} instead of EntityManager {}", proxy.getClass(), original);
return proxy;
| 550 | 142 | 692 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/plugin/hotswap-agent-hibernate-jakarta-plugin/src/main/java/org/hotswap/agent/plugin/hibernate_jakarta/HibernateRefreshCommands.java
|
HibernateRefreshCommands
|
reloadEntityManagerFactory
|
class HibernateRefreshCommands {
private static AgentLogger LOGGER = AgentLogger.getLogger(HibernateRefreshCommands.class);
/**
* 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;
public static void reloadEntityManagerFactory() {<FILL_FUNCTION_BODY>}
public static void reloadSessionFactory() {
LOGGER.debug("Refreshing SessionFactory configuration.");
SessionFactoryProxy.refreshProxiedFactories();
LOGGER.reload("Hibernate SessionFactory configuration refreshed.");
reloadFlag = false;
}
}
|
LOGGER.debug("Refreshing hibernate configuration.");
EntityManagerFactoryProxy.refreshProxiedFactories();
LOGGER.reload("Hibernate EntityMangerFactory configuration refreshed.");
reloadFlag = false;
| 200 | 62 | 262 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/plugin/hotswap-agent-hibernate-jakarta-plugin/src/main/java/org/hotswap/agent/plugin/hibernate_jakarta/proxy/EntityManagerFactoryProxy.java
|
EntityManagerFactoryProxy
|
refreshProxiedFactory
|
class EntityManagerFactoryProxy {
private static AgentLogger LOGGER = AgentLogger.getLogger(EntityManagerFactoryProxy.class);
// Map persistenceUnitName -> Wrapper instance
private static Map<String, EntityManagerFactoryProxy> proxiedFactories = new HashMap<>();
// hold lock during refresh. The lock is checked on each factory method call.
final Object reloadLock = new Object();
// current entity manager factory instance - this is the target this proxy delegates to
EntityManagerFactory currentInstance;
// info and properties to use to build fresh instance of factory
String persistenceUnitName;
PersistenceUnitInfo info;
Map properties;
// builder object to create properties
Object builder;
/**
* Create new wrapper for persistenceUnitName and hold it's instance for future use.
*
* @param persistenceUnitName key to the wrapper
* @return existing wrapper or new instance (never null)
*/
public static EntityManagerFactoryProxy getWrapper(String persistenceUnitName) {
if (!proxiedFactories.containsKey(persistenceUnitName)) {
proxiedFactories.put(persistenceUnitName, new EntityManagerFactoryProxy());
}
return proxiedFactories.get(persistenceUnitName);
}
/**
* Refresh all known wrapped factories.
*/
public static void refreshProxiedFactories() {
String[] version = Version.getVersionString().split("\\.");
boolean version43OrGreater = false;
try {
version43OrGreater = Integer.valueOf(version[0]) >= 5 || (Integer.valueOf(version[0]) == 4 && Integer.valueOf(version[1]) >= 3);
} catch (Exception e) {
LOGGER.warning("Unable to resolve hibernate version '{}'", version);
}
for (EntityManagerFactoryProxy wrapper : proxiedFactories.values()) {
String persistenceClassName = wrapper.properties == null ? null :
(String) wrapper.properties.get("PERSISTENCE_CLASS_NAME");
try {
// lock proxy execution during reload
synchronized (wrapper.reloadLock) {
if ("org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider".equals(persistenceClassName)) {
wrapper.refreshProxiedFactorySpring();
} else if (version43OrGreater) {
wrapper.refreshProxiedFactoryVersion43OrGreater();
} else {
wrapper.refreshProxiedFactory();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void refreshProxiedFactorySpring() {
try {
currentInstance = (EntityManagerFactory) ReflectionHelper.invoke(builder, builder.getClass(),
"createContainerEntityManagerFactory",
new Class[]{PersistenceUnitInfo.class, Map.class}, info, properties);
} catch (Exception e) {
e.printStackTrace();
LOGGER.error("Unable to reload persistence unit {}", info, e);
}
}
public void refreshProxiedFactoryVersion43OrGreater() {
if (info == null) {
currentInstance = Persistence.createEntityManagerFactory(persistenceUnitName, properties);
} else {
try {
Class bootstrapClazz = loadClass("org.hibernate.jpa.boot.spi.Bootstrap");
Class builderClazz = loadClass("org.hibernate.jpa.boot.spi.EntityManagerFactoryBuilder");
Object builder = ReflectionHelper.invoke(null, bootstrapClazz, "getEntityManagerFactoryBuilder",
new Class[]{PersistenceUnitInfo.class, Map.class}, info, properties);
currentInstance = (EntityManagerFactory) ReflectionHelper.invoke(builder, builderClazz, "build",
new Class[]{});
} catch (Exception e) {
e.printStackTrace();
LOGGER.error("Unable to reload persistence unit {}", info, e);
}
}
}
/**
* Refresh a single persistence unit - replace the wrapped EntityManagerFactory with fresh instance.
*/
public void refreshProxiedFactory() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, NoSuchFieldException {<FILL_FUNCTION_BODY>}
// create factory from cached configuration
// from HibernatePersistence.createContainerEntityManagerFactory()
private void buildFreshEntityManagerFactory() {
try {
Class ejb3ConfigurationClazz = loadClass("org.hibernate.ejb.Ejb3Configuration");
LOGGER.trace("new Ejb3Configuration()");
Object cfg = ejb3ConfigurationClazz.newInstance();
LOGGER.trace("cfg.configure( info, properties );");
if (info != null) {
ReflectionHelper.invoke(cfg, ejb3ConfigurationClazz, "configure",
new Class[]{PersistenceUnitInfo.class, Map.class}, info, properties);
}
else {
ReflectionHelper.invoke(cfg, ejb3ConfigurationClazz, "configure",
new Class[]{String.class, Map.class}, persistenceUnitName, properties);
}
LOGGER.trace("configured.buildEntityManagerFactory()");
currentInstance = (EntityManagerFactory) ReflectionHelper.invoke(cfg, ejb3ConfigurationClazz, "buildEntityManagerFactory",
new Class[]{});
} catch (Exception e) {
LOGGER.error("Unable to build fresh entity manager factory for persistence unit {}", persistenceUnitName);
}
}
/**
* Create a proxy for EntityManagerFactory.
*
* @param factory initial factory to delegate method calls to.
* @param info definition to cache for factory reload
* @param properties properties to cache for factory reload
* @return the proxy
*/
public EntityManagerFactory proxy(Object builder, EntityManagerFactory factory, String persistenceUnitName,
PersistenceUnitInfo info, Map properties) {
this.builder = builder;
this.currentInstance = factory;
this.persistenceUnitName = persistenceUnitName;
this.info = info;
this.properties = properties;
return (EntityManagerFactory) Proxy.newProxyInstance(
currentInstance.getClass().getClassLoader(), currentInstance.getClass().getInterfaces(),
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// if reload in progress, wait for it
synchronized (reloadLock) {}
return method.invoke(currentInstance, args);
}
});
}
private Class loadClass(String name) throws ClassNotFoundException {
return getClass().getClassLoader().loadClass(name);
}
}
|
// refresh registry
try {
Class entityManagerFactoryRegistryClazz = loadClass("org.hibernate.ejb.internal.EntityManagerFactoryRegistry");
Object instance = ReflectionHelper.get(null, entityManagerFactoryRegistryClazz, "INSTANCE");
ReflectionHelper.invoke(instance, entityManagerFactoryRegistryClazz, "removeEntityManagerFactory",
new Class[] {String.class, EntityManagerFactory.class}, persistenceUnitName, currentInstance);
} catch (Exception e) {
LOGGER.error("Unable to clear previous instance of entity manager factory");
}
buildFreshEntityManagerFactory();
| 1,704 | 153 | 1,857 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/plugin/hotswap-agent-hibernate-jakarta-plugin/src/main/java/org/hotswap/agent/plugin/hibernate_jakarta/proxy/SessionFactoryProxy.java
|
SessionFactoryProxy
|
proxy
|
class SessionFactoryProxy {
private static Map<Configuration, SessionFactoryProxy> proxiedFactories = new HashMap<>();
private SessionFactoryProxy(Configuration configuration) {
this.configuration = configuration;
}
public static SessionFactoryProxy getWrapper(Configuration configuration) {
if (!proxiedFactories.containsKey(configuration)) {
proxiedFactories.put(configuration, new SessionFactoryProxy(configuration));
}
return proxiedFactories.get(configuration);
}
public static void refreshProxiedFactories() {
for (SessionFactoryProxy wrapper : proxiedFactories.values())
try {
wrapper.refreshProxiedFactory();
} catch (Exception e) {
e.printStackTrace();
}
}
public void refreshProxiedFactory() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
Method m = Configuration.class.getDeclaredMethod("_buildSessionFactory", ServiceRegistry.class);
currentInstance = (SessionFactory) m.invoke(configuration, serviceRegistry);
}
private Configuration configuration;
private SessionFactory currentInstance;
private ServiceRegistry serviceRegistry;
public SessionFactory proxy(SessionFactory sessionFactory, ServiceRegistry serviceRegistry) {<FILL_FUNCTION_BODY>}
}
|
this.currentInstance = sessionFactory;
this.serviceRegistry = serviceRegistry;
ProxyFactory factory = new ProxyFactory();
factory.setSuperclass(SessionFactoryImpl.class);
factory.setInterfaces(new Class[]{SessionFactory.class});
MethodHandler handler = new MethodHandler() {
@Override
public Object invoke(Object self, Method overridden, Method forwarder,
Object[] args) throws Throwable {
try {
return overridden.invoke(currentInstance, args);
} catch(InvocationTargetException e) {
//rethrow original exception to prevent proxying from changing external behaviour of SessionFactory
throw e.getTargetException();
}
}
};
Object instance;
try {
Constructor constructor = ReflectionFactory.getReflectionFactory().newConstructorForSerialization(factory.createClass(), Object.class.getDeclaredConstructor(new Class[0]));
instance = constructor.newInstance();
((Proxy) instance).setHandler(handler);
} catch (Exception e) {
throw new Error("Unable instantiate SessionFactory proxy", e);
}
return (SessionFactory) instance;
| 318 | 289 | 607 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/plugin/hotswap-agent-hibernate-plugin/src/main/java/org/hotswap/agent/plugin/hibernate/HibernatePersistenceHelper.java
|
HibernatePersistenceHelper
|
createContainerEntityManagerFactoryProxy
|
class HibernatePersistenceHelper {
private static AgentLogger LOGGER = AgentLogger.getLogger(HibernatePersistenceHelper.class);
// each persistence unit should be wrapped only once
static Set<String> wrappedPersistenceUnitNames = new HashSet<>();
/**
* @param info persistent unit definition
* @param properties properties to create entity manager factory
* @param original entity manager factory
* @return proxy of entity manager
*/
public static EntityManagerFactory createContainerEntityManagerFactoryProxy(Object builder, PersistenceUnitInfo info, Map properties,
EntityManagerFactory original) {<FILL_FUNCTION_BODY>}
/**
* @param persistenceUnitName persistent unit name
* @param properties properties to create entity manager factory
* @param original entity manager factory
* @return proxy of entity manager
*/
public static EntityManagerFactory createEntityManagerFactoryProxy(Object builder, String persistenceUnitName, Map properties,
EntityManagerFactory original) {
// ensure only once
if (wrappedPersistenceUnitNames.contains(persistenceUnitName)) {
return original;
}
wrappedPersistenceUnitNames.add(persistenceUnitName);
EntityManagerFactoryProxy wrapper = EntityManagerFactoryProxy.getWrapper(persistenceUnitName);
EntityManagerFactory proxy = wrapper.proxy(builder, original, persistenceUnitName, null, properties);
initPlugin(original);
LOGGER.debug("Returning EntityManager proxy {} instead of EntityManager {}", proxy.getClass(), original);
return proxy;
}
// call initializePlugin and setup version and EJB flag
private static void initPlugin(EntityManagerFactory original) {
ClassLoader appClassLoader = original.getClass().getClassLoader();
String version = Version.getVersionString();
PluginManagerInvoker.callInitializePlugin(HibernatePlugin.class, appClassLoader);
PluginManagerInvoker.callPluginMethod(HibernatePlugin.class, appClassLoader,
"init",
new Class[]{String.class, Boolean.class},
new Object[]{version, true});
}
}
|
// ensure only once
if (wrappedPersistenceUnitNames.contains(info.getPersistenceUnitName())) {
return original;
}
wrappedPersistenceUnitNames.add(info.getPersistenceUnitName());
EntityManagerFactoryProxy wrapper = EntityManagerFactoryProxy.getWrapper(info.getPersistenceUnitName());
EntityManagerFactory proxy = wrapper.proxy(builder, original, info.getPersistenceUnitName(), info, properties);
initPlugin(original);
LOGGER.debug("Returning container EntityManager proxy {} instead of EntityManager {}", proxy.getClass(), original);
return proxy;
| 529 | 155 | 684 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/plugin/hotswap-agent-hibernate-plugin/src/main/java/org/hotswap/agent/plugin/hibernate/HibernatePlugin.java
|
HibernatePlugin
|
executeCommand
|
class HibernatePlugin {
private static final String ENTITY_ANNOTATION = "javax.persistence.Entity";
private static AgentLogger LOGGER = AgentLogger.getLogger(HibernatePlugin.class);
@Init
Scheduler scheduler;
@Init
ClassLoader appClassLoader;
Set<Object> regAnnotatedMetaDataProviders = Collections.newSetFromMap(new WeakHashMap<Object, Boolean>());
Map<Object, String> regBeanMetaDataManagersMap = new WeakHashMap<Object, String>();
// refresh commands
Command reloadEntityManagerFactoryCommand =
new ReflectionCommand(this, HibernateRefreshCommands.class.getName(), "reloadEntityManagerFactory");
Command reloadSessionFactoryCommand =
new ReflectionCommand(this, HibernateRefreshCommands.class.getName(), "reloadSessionFactory");
private Command invalidateHibernateValidatorCaches = new Command() {
@Override
public void executeCommand() {<FILL_FUNCTION_BODY>}
};
// is EJB3 or plain hibernate
boolean hibernateEjb;
/**
* Plugin initialization properties (from HibernatePersistenceHelper or SessionFactoryProxy)
*/
public void init(String version, Boolean hibernateEjb) {
LOGGER.info("Hibernate plugin initialized - Hibernate Core version '{}'", version);
this.hibernateEjb = hibernateEjb;
}
/**
* Reload after entity class change. It covers also @Entity annotation removal.
*/
@OnClassLoadEvent(classNameRegexp = ".*", events = LoadEvent.REDEFINE)
public void entityReload(CtClass clazz, Class original) {
// TODO list of entity/resource files is known to hibernate, better to check this list
if (AnnotationHelper.hasAnnotation(original, ENTITY_ANNOTATION)
|| AnnotationHelper.hasAnnotation(clazz, ENTITY_ANNOTATION)
) {
LOGGER.debug("Entity reload class {}, original classloader {}", clazz.getName(), original.getClassLoader());
refresh(100);
}
}
/**
* New entity class - not covered by reloading mechanism.
* <p/>
* Increase the reload timeout to avoid duplicate reloading in case of recompile with IDE
* and delete/create event sequence - than create is cached by this event and hotswap for
* the same class by entityReload.
*/
@OnClassFileEvent(classNameRegexp = ".*", events = {FileEvent.CREATE})
public void newEntity(CtClass clazz) throws Exception {
if (AnnotationHelper.hasAnnotation(clazz, ENTITY_ANNOTATION)) {
refresh(500);
}
}
@OnClassLoadEvent(classNameRegexp = ".*", events = LoadEvent.REDEFINE)
public void invalidateClassCache() throws Exception {
if (!regBeanMetaDataManagersMap.isEmpty() || !regAnnotatedMetaDataProviders.isEmpty()) {
scheduler.scheduleCommand(invalidateHibernateValidatorCaches);
}
}
// reload the configuration - schedule a command to run in the application classloader and merge
// duplicate commands.
private void refresh(int timeout) {
if (hibernateEjb) {
scheduler.scheduleCommand(reloadEntityManagerFactoryCommand, timeout);
} else {
scheduler.scheduleCommand(reloadSessionFactoryCommand, timeout);
}
}
public void registerAnnotationMetaDataProvider(Object annotatedMetaDataProvider) {
regAnnotatedMetaDataProviders.add(annotatedMetaDataProvider);
}
public void registerBeanMetaDataManager(Object beanMetaDataManager, String beanMetaDataManagerClassName) {
regBeanMetaDataManagersMap.put(beanMetaDataManager, beanMetaDataManagerClassName);
}
private Class<?> resolveClass(String name) throws ClassNotFoundException {
return Class.forName(name, true, appClassLoader);
}
}
|
LOGGER.debug("Refreshing BeanMetaDataManagerCache/AnnotatedMetaDataProvider cache.");
try {
Method resetCacheMethod1 = resolveClass("org.hibernate.validator.internal.metadata.provider.AnnotationMetaDataProvider").getDeclaredMethod("$$ha$resetCache");
for (Object regAnnotatedDataManager : regAnnotatedMetaDataProviders) {
LOGGER.debug("Invoking org.hibernate.validator.internal.metadata.provider.AnnotationMetaDataProvider.$$ha$resetCache on {}", regAnnotatedDataManager);
resetCacheMethod1.invoke(regAnnotatedDataManager);
}
for (Map.Entry<Object, String> entry : regBeanMetaDataManagersMap.entrySet()) {
LOGGER.debug("Invoking " + entry.getValue() + " .$$ha$resetCache on {}", entry.getKey());
Method resetCacheMethod2 = resolveClass(entry.getValue()).getDeclaredMethod("$$ha$resetCache");
resetCacheMethod2.invoke(entry.getKey());
}
} catch (Exception e) {
LOGGER.error("Error refreshing BeanMetaDataManagerCache/AnnotatedMetaDataProvider cache.", e);
}
| 1,036 | 296 | 1,332 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/plugin/hotswap-agent-hibernate-plugin/src/main/java/org/hotswap/agent/plugin/hibernate/HibernateRefreshCommands.java
|
HibernateRefreshCommands
|
reloadSessionFactory
|
class HibernateRefreshCommands {
private static AgentLogger LOGGER = AgentLogger.getLogger(HibernateRefreshCommands.class);
/**
* 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;
public static void reloadEntityManagerFactory() {
LOGGER.debug("Refreshing hibernate configuration.");
EntityManagerFactoryProxy.refreshProxiedFactories();
LOGGER.reload("Hibernate EntityMangerFactory configuration refreshed.");
reloadFlag = false;
}
public static void reloadSessionFactory() {<FILL_FUNCTION_BODY>}
}
|
LOGGER.debug("Refreshing SessionFactory configuration.");
SessionFactoryProxy.refreshProxiedFactories();
LOGGER.reload("Hibernate SessionFactory configuration refreshed.");
reloadFlag = false;
| 205 | 56 | 261 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/plugin/hotswap-agent-hibernate-plugin/src/main/java/org/hotswap/agent/plugin/hibernate/proxy/EntityManagerFactoryProxy.java
|
EntityManagerFactoryProxy
|
refreshProxiedFactories
|
class EntityManagerFactoryProxy {
private static AgentLogger LOGGER = AgentLogger.getLogger(EntityManagerFactoryProxy.class);
// Map persistenceUnitName -> Wrapper instance
private static Map<String, EntityManagerFactoryProxy> proxiedFactories = new HashMap<>();
// hold lock during refresh. The lock is checked on each factory method call.
final Object reloadLock = new Object();
// current entity manager factory instance - this is the target this proxy delegates to
EntityManagerFactory currentInstance;
// info and properties to use to build fresh instance of factory
String persistenceUnitName;
PersistenceUnitInfo info;
Map properties;
// builder object to create properties
Object builder;
/**
* Create new wrapper for persistenceUnitName and hold it's instance for future use.
*
* @param persistenceUnitName key to the wrapper
* @return existing wrapper or new instance (never null)
*/
public static EntityManagerFactoryProxy getWrapper(String persistenceUnitName) {
if (!proxiedFactories.containsKey(persistenceUnitName)) {
proxiedFactories.put(persistenceUnitName, new EntityManagerFactoryProxy());
}
return proxiedFactories.get(persistenceUnitName);
}
/**
* Refresh all known wrapped factories.
*/
public static void refreshProxiedFactories() {<FILL_FUNCTION_BODY>}
private void refreshProxiedFactorySpring() {
try {
currentInstance = (EntityManagerFactory) ReflectionHelper.invoke(builder, builder.getClass(),
"createContainerEntityManagerFactory",
new Class[]{PersistenceUnitInfo.class, Map.class}, info, properties);
} catch (Exception e) {
e.printStackTrace();
LOGGER.error("Unable to reload persistence unit {}", info, e);
}
}
public void refreshProxiedFactoryVersion43OrGreater() {
if (info == null) {
currentInstance = Persistence.createEntityManagerFactory(persistenceUnitName, properties);
} else {
try {
Class bootstrapClazz = loadClass("org.hibernate.jpa.boot.spi.Bootstrap");
Class builderClazz = loadClass("org.hibernate.jpa.boot.spi.EntityManagerFactoryBuilder");
Object builder = ReflectionHelper.invoke(null, bootstrapClazz, "getEntityManagerFactoryBuilder",
new Class[]{PersistenceUnitInfo.class, Map.class}, info, properties);
currentInstance = (EntityManagerFactory) ReflectionHelper.invoke(builder, builderClazz, "build",
new Class[]{});
} catch (Exception e) {
e.printStackTrace();
LOGGER.error("Unable to reload persistence unit {}", info, e);
}
}
}
/**
* Refresh a single persistence unit - replace the wrapped EntityManagerFactory with fresh instance.
*/
public void refreshProxiedFactory() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, NoSuchFieldException {
// refresh registry
try {
Class entityManagerFactoryRegistryClazz = loadClass("org.hibernate.ejb.internal.EntityManagerFactoryRegistry");
Object instance = ReflectionHelper.get(null, entityManagerFactoryRegistryClazz, "INSTANCE");
ReflectionHelper.invoke(instance, entityManagerFactoryRegistryClazz, "removeEntityManagerFactory",
new Class[] {String.class, EntityManagerFactory.class}, persistenceUnitName, currentInstance);
} catch (Exception e) {
LOGGER.error("Unable to clear previous instance of entity manager factory");
}
buildFreshEntityManagerFactory();
}
// create factory from cached configuration
// from HibernatePersistence.createContainerEntityManagerFactory()
private void buildFreshEntityManagerFactory() {
try {
Class ejb3ConfigurationClazz = loadClass("org.hibernate.ejb.Ejb3Configuration");
LOGGER.trace("new Ejb3Configuration()");
Object cfg = ejb3ConfigurationClazz.newInstance();
LOGGER.trace("cfg.configure( info, properties );");
if (info != null) {
ReflectionHelper.invoke(cfg, ejb3ConfigurationClazz, "configure",
new Class[]{PersistenceUnitInfo.class, Map.class}, info, properties);
}
else {
ReflectionHelper.invoke(cfg, ejb3ConfigurationClazz, "configure",
new Class[]{String.class, Map.class}, persistenceUnitName, properties);
}
LOGGER.trace("configured.buildEntityManagerFactory()");
currentInstance = (EntityManagerFactory) ReflectionHelper.invoke(cfg, ejb3ConfigurationClazz, "buildEntityManagerFactory",
new Class[]{});
} catch (Exception e) {
LOGGER.error("Unable to build fresh entity manager factory for persistence unit {}", persistenceUnitName);
}
}
/**
* Create a proxy for EntityManagerFactory.
*
* @param factory initial factory to delegate method calls to.
* @param info definition to cache for factory reload
* @param properties properties to cache for factory reload
* @return the proxy
*/
public EntityManagerFactory proxy(Object builder, EntityManagerFactory factory, String persistenceUnitName,
PersistenceUnitInfo info, Map properties) {
this.builder = builder;
this.currentInstance = factory;
this.persistenceUnitName = persistenceUnitName;
this.info = info;
this.properties = properties;
return (EntityManagerFactory) Proxy.newProxyInstance(
currentInstance.getClass().getClassLoader(), currentInstance.getClass().getInterfaces(),
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// if reload in progress, wait for it
synchronized (reloadLock) {}
return method.invoke(currentInstance, args);
}
});
}
private Class loadClass(String name) throws ClassNotFoundException {
return getClass().getClassLoader().loadClass(name);
}
}
|
String[] version = Version.getVersionString().split("\\.");
boolean version43OrGreater = false;
try {
version43OrGreater = Integer.valueOf(version[0]) >= 5 || (Integer.valueOf(version[0]) == 4 && Integer.valueOf(version[1]) >= 3);
} catch (Exception e) {
LOGGER.warning("Unable to resolve hibernate version '{}'", version);
}
for (EntityManagerFactoryProxy wrapper : proxiedFactories.values()) {
String persistenceClassName = wrapper.properties == null ? null :
(String) wrapper.properties.get("PERSISTENCE_CLASS_NAME");
try {
// lock proxy execution during reload
synchronized (wrapper.reloadLock) {
if ("org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider".equals(persistenceClassName)) {
wrapper.refreshProxiedFactorySpring();
} else if (version43OrGreater) {
wrapper.refreshProxiedFactoryVersion43OrGreater();
} else {
wrapper.refreshProxiedFactory();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
| 1,538 | 319 | 1,857 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/plugin/hotswap-agent-hibernate-plugin/src/main/java/org/hotswap/agent/plugin/hibernate/proxy/SessionFactoryProxy.java
|
SessionFactoryProxy
|
refreshProxiedFactories
|
class SessionFactoryProxy {
private static Map<Configuration, SessionFactoryProxy> proxiedFactories = new HashMap<>();
private SessionFactoryProxy(Configuration configuration) {
this.configuration = configuration;
}
public static SessionFactoryProxy getWrapper(Configuration configuration) {
if (!proxiedFactories.containsKey(configuration)) {
proxiedFactories.put(configuration, new SessionFactoryProxy(configuration));
}
return proxiedFactories.get(configuration);
}
public static void refreshProxiedFactories() {<FILL_FUNCTION_BODY>}
public void refreshProxiedFactory() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
Method m = Configuration.class.getDeclaredMethod("_buildSessionFactory", ServiceRegistry.class);
currentInstance = (SessionFactory) m.invoke(configuration, serviceRegistry);
}
private Configuration configuration;
private SessionFactory currentInstance;
private ServiceRegistry serviceRegistry;
public SessionFactory proxy(SessionFactory sessionFactory, ServiceRegistry serviceRegistry) {
this.currentInstance = sessionFactory;
this.serviceRegistry = serviceRegistry;
ProxyFactory factory = new ProxyFactory();
factory.setSuperclass(SessionFactoryImpl.class);
factory.setInterfaces(new Class[]{SessionFactory.class});
MethodHandler handler = new MethodHandler() {
@Override
public Object invoke(Object self, Method overridden, Method forwarder,
Object[] args) throws Throwable {
try {
return overridden.invoke(currentInstance, args);
} catch(InvocationTargetException e) {
//rethrow original exception to prevent proxying from changing external behaviour of SessionFactory
throw e.getTargetException();
}
}
};
Object instance;
try {
Constructor constructor = ReflectionFactory.getReflectionFactory().newConstructorForSerialization(factory.createClass(), Object.class.getDeclaredConstructor(new Class[0]));
instance = constructor.newInstance();
((Proxy) instance).setHandler(handler);
} catch (Exception e) {
throw new Error("Unable instantiate SessionFactory proxy", e);
}
return (SessionFactory) instance;
}
}
|
for (SessionFactoryProxy wrapper : proxiedFactories.values())
try {
wrapper.refreshProxiedFactory();
} catch (Exception e) {
e.printStackTrace();
}
| 552 | 55 | 607 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/plugin/hotswap-agent-hibernate3-plugin/src/main/java/org/hotswap/agent/plugin/hibernate3/jpa/Hibernate3JPAHelper.java
|
Hibernate3JPAHelper
|
createEntityManagerFactoryProxy
|
class Hibernate3JPAHelper {
/** The logger. */
private static AgentLogger LOGGER = AgentLogger.getLogger(Hibernate3JPAHelper.class);
/** The wrapped persistence unit names. */
// each persistence unit should be wrapped only once
static Set<String> wrappedPersistenceUnitNames = new HashSet<>();
/**
* Creates the container entity manager factory proxy.
*
* @param info persistent unit definition
* @param properties properties to create entity manager factory
* @param original entity manager factory
* @return proxy of entity manager
*/
public static EntityManagerFactory createContainerEntityManagerFactoryProxy(PersistenceUnitInfo info,
Map<?,?> properties, EntityManagerFactory original) {
// ensure only once
if (wrappedPersistenceUnitNames.contains(info.getPersistenceUnitName())){
return original;
}
wrappedPersistenceUnitNames.add(info.getPersistenceUnitName());
EntityManagerFactoryProxy wrapper = EntityManagerFactoryProxy.getWrapper(info.getPersistenceUnitName());
EntityManagerFactory proxy = wrapper.proxy(original, info.getPersistenceUnitName(), info, properties);
initPlugin(original);
LOGGER.debug("Returning container EntityManager proxy {} instead of EntityManager {}", proxy.getClass(),
original);
return proxy;
}
/**
* Creates the entity manager factory proxy.
*
* @param persistenceUnitName persistent unit name
* @param properties properties to create entity manager factory
* @param original entity manager factory
* @return proxy of entity manager
*/
public static EntityManagerFactory createEntityManagerFactoryProxy(String persistenceUnitName, Map<?,?> properties,
EntityManagerFactory original) {<FILL_FUNCTION_BODY>}
/**
* Inits the plugin.
*
* @param original the original
*/
// call initializePlugin and setup version and EJB flag
private static void initPlugin(EntityManagerFactory original) {
ClassLoader appClassLoader = original.getClass().getClassLoader();
String version = Version.getVersionString();
PluginManagerInvoker.callInitializePlugin(Hibernate3JPAPlugin.class, appClassLoader);
PluginManagerInvoker.callPluginMethod(Hibernate3JPAPlugin.class, appClassLoader, "init", new Class[] { String.class, Boolean.class }, new Object[] { version, true });
}
}
|
// ensure only once
if (wrappedPersistenceUnitNames.contains(persistenceUnitName)){
return original;
}
wrappedPersistenceUnitNames.add(persistenceUnitName);
EntityManagerFactoryProxy wrapper = EntityManagerFactoryProxy.getWrapper(persistenceUnitName);
EntityManagerFactory proxy = wrapper.proxy(original, persistenceUnitName, null, properties);
initPlugin(original);
LOGGER.debug("Returning EntityManager proxy {} instead of EntityManager {}", proxy.getClass(), original);
return proxy;
| 625 | 139 | 764 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/plugin/hotswap-agent-hibernate3-plugin/src/main/java/org/hotswap/agent/plugin/hibernate3/jpa/Hibernate3JPAPlugin.java
|
Hibernate3JPAPlugin
|
executeCommand
|
class Hibernate3JPAPlugin {
/** The Constant ENTITY_ANNOTATION. */
private static final String ENTITY_ANNOTATION = "javax.persistence.Entity";
/** The logger. */
private static AgentLogger LOGGER = AgentLogger.getLogger(Hibernate3JPAPlugin.class);
/** The scheduler. */
@Init
Scheduler scheduler;
/** The app class loader. */
@Init
ClassLoader appClassLoader;
/** The reg annotated meta data providers. */
Set<Object> regAnnotatedMetaDataProviders = Collections.newSetFromMap(new WeakHashMap<Object, Boolean>());
/** The reg bean meta data managers. */
Set<Object> regBeanMetaDataManagers = Collections.newSetFromMap(new WeakHashMap<Object, Boolean>());
/** The reload entity manager factory command. */
// refresh commands
Command reloadEntityManagerFactoryCommand = new ReflectionCommand(this, Hibernate3JPARefreshCommands.class.getName(),
"reloadEntityManagerFactory");
/** The invalidate hibernate validator caches. */
private Command invalidateHibernateValidatorCaches = new Command() {
@Override
public void executeCommand() {<FILL_FUNCTION_BODY>}
};
/** The hibernate ejb. */
// is EJB3 or plain hibernate
boolean hibernateEjb;
/**
* Plugin initialization properties (from Hibernate3JPAHelper or
* SessionFactoryProxy).
*
* @param version the version
* @param hibernateEjb the hibernate ejb
*/
public void init(String version, Boolean hibernateEjb) {
LOGGER.info("Hibernate3 JPA plugin initialized - Hibernate Core version '{}'", version);
this.hibernateEjb = hibernateEjb;
}
/**
* Reload after entity class change. It covers also @Entity annotation
* removal.
*
* @param clazz the clazz
* @param original the original
*/
@OnClassLoadEvent(classNameRegexp = ".*", events = LoadEvent.REDEFINE)
public void entityReload(CtClass clazz, Class<?> original) {
// TODO list of entity/resource files is known to hibernate, better to
// check this list
if (AnnotationHelper.hasAnnotation(original, ENTITY_ANNOTATION)
|| AnnotationHelper.hasAnnotation(clazz, ENTITY_ANNOTATION)) {
LOGGER.debug("Entity reload class {}, original classloader {}", clazz.getName(), original.getClassLoader());
refresh(100);
}
}
/**
* New entity class - not covered by reloading mechanism.
* <p/>
* Increase the reload timeout to avoid duplicate reloading in case of
* recompile with IDE and delete/create event sequence - than create is
* cached by this event and hotswap for the same class by entityReload.
*
* @param clazz the clazz
* @throws Exception the exception
*/
@OnClassFileEvent(classNameRegexp = ".*", events = { FileEvent.CREATE })
public void newEntity(CtClass clazz) throws Exception {
if (AnnotationHelper.hasAnnotation(clazz, ENTITY_ANNOTATION)) {
refresh(500);
}
}
/**
* Reload on hbm file modifications.
*/
@OnResourceFileEvent(path = "/", filter = ".*.hbm.xml")
public void refreshOnHbm(){
refresh(500);
}
/**
* Reload on hibernate.cfg.xml file modifications
*/
@OnResourceFileEvent(path = "/", filter = ".*.cfg.xml")
public void refreshOnCfg(){
refresh(500);
}
/**
* Reload on persistence.xml file modifications
*/
@OnResourceFileEvent(path = "/", filter = "persistence.xml")
public void refreshOnPersistenceXml(){
refresh(500);
}
/**
* Invalidate class cache.
*
* @throws Exception the exception
*/
@OnClassLoadEvent(classNameRegexp = ".*", events = LoadEvent.REDEFINE)
public void invalidateClassCache() throws Exception {
if (!regBeanMetaDataManagers.isEmpty() || !regAnnotatedMetaDataProviders.isEmpty()) {
scheduler.scheduleCommand(invalidateHibernateValidatorCaches);
}
}
// reload the configuration - schedule a command to run in the application
// classloader and merge
/**
* Refresh.
*
* @param timeout the timeout
*/
// duplicate commands.
private void refresh(int timeout) {
scheduler.scheduleCommand(reloadEntityManagerFactoryCommand, timeout);
}
/**
* Register annotation meta data provider.
*
* @param annotatedMetaDataProvider the annotated meta data provider
*/
public void registerAnnotationMetaDataProvider(Object annotatedMetaDataProvider) {
regAnnotatedMetaDataProviders.add(annotatedMetaDataProvider);
}
/**
* Register bean meta data manager.
*
* @param beanMetaDataManager the bean meta data manager
*/
public void registerBeanMetaDataManager(Object beanMetaDataManager) {
regBeanMetaDataManagers.add(beanMetaDataManager);
}
/**
* 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);
}
}
|
LOGGER.debug("Refreshing BeanMetaDataManagerCache/AnnotatedMetaDataProvider cache.");
try {
Method resetCacheMethod1 = resolveClass(
"org.hibernate.validator.internal.metadata.provider.AnnotationMetaDataProvider")
.getDeclaredMethod("__resetCache");
for (Object regAnnotatedDataManager : regAnnotatedMetaDataProviders) {
LOGGER.debug(
"Invoking org.hibernate.validator.internal.metadata.provider.AnnotationMetaDataProvider.__resetCache on {}",
regAnnotatedDataManager);
resetCacheMethod1.invoke(regAnnotatedDataManager);
}
Method resetCacheMethod2 = resolveClass("org.hibernate.validator.internal.metadata.BeanMetaDataManager")
.getDeclaredMethod("__resetCache");
for (Object regBeanMetaDataManager : regBeanMetaDataManagers) {
LOGGER.debug(
"Invoking org.hibernate.validator.internal.metadata.BeanMetaDataManager.__resetCache on {}",
regBeanMetaDataManager);
resetCacheMethod2.invoke(regBeanMetaDataManager);
}
} catch (Exception e) {
LOGGER.error("Error refreshing BeanMetaDataManagerCache/AnnotatedMetaDataProvider cache.", e);
}
| 1,496 | 321 | 1,817 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/plugin/hotswap-agent-hibernate3-plugin/src/main/java/org/hotswap/agent/plugin/hibernate3/jpa/Hibernate3JPARefreshCommands.java
|
Hibernate3JPARefreshCommands
|
reloadEntityManagerFactory
|
class Hibernate3JPARefreshCommands {
/** The logger. */
private static AgentLogger LOGGER = AgentLogger.getLogger(Hibernate3JPARefreshCommands.class);
/**
* 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;
/**
* Reload entity manager factory.
*/
public static void reloadEntityManagerFactory() {<FILL_FUNCTION_BODY>}
}
|
LOGGER.debug("Refreshing hibernate configuration.");
EntityManagerFactoryProxy.refreshProxiedFactories();
LOGGER.reload("Hibernate EntityMangerFactory configuration refreshed.");
reloadFlag = false;
| 160 | 62 | 222 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/plugin/hotswap-agent-hibernate3-plugin/src/main/java/org/hotswap/agent/plugin/hibernate3/jpa/Hibernate3JPATransformers.java
|
Hibernate3JPATransformers
|
beanMetaDataManagerRegisterVariable
|
class Hibernate3JPATransformers {
/** The logger. */
private static AgentLogger LOGGER = AgentLogger.getLogger(Hibernate3JPATransformers.class);
/**
* Override HibernatePersistence.createContainerEntityManagerFactory() to return EntityManagerFactory proxy object.
* {@link org.hotswap.agent.plugin.hibernate3.jpa.proxy.EntityManagerFactoryProxy} holds reference to all proxied factories
* and on refresh command replaces internal factory with fresh instance.
* <p/>
* Two variants covered - createContainerEntityManagerFactory and createEntityManagerFactory.
* <p/>
* After the entity manager factory and it's proxy are instantiated, plugin init method is invoked.
*
* @param clazz the clazz
* @throws Exception the exception
*/
@OnClassLoadEvent(classNameRegexp = "org.hibernate.ejb.HibernatePersistence")
public static void proxyHibernatePersistence(CtClass clazz) throws Exception {
LOGGER.debug("Override org.hibernate.ejb.HibernatePersistence#createContainerEntityManagerFactory and createEntityManagerFactory to create a EntityManagerFactoryProxy proxy.");
CtMethod oldMethod = clazz.getDeclaredMethod("createContainerEntityManagerFactory");
oldMethod.setName("_createContainerEntityManagerFactory" + clazz.getSimpleName());
CtMethod newMethod = CtNewMethod.make(
"public javax.persistence.EntityManagerFactory createContainerEntityManagerFactory(javax.persistence.spi.PersistenceUnitInfo info, java.util.Map properties) {" +
" return " + Hibernate3JPAHelper.class.getName() + ".createContainerEntityManagerFactoryProxy(" +
" info, properties, _createContainerEntityManagerFactory" + clazz.getSimpleName() + "(info, properties)); " +
"}", clazz);
clazz.addMethod(newMethod);
oldMethod = clazz.getDeclaredMethod("createEntityManagerFactory");
oldMethod.setName("_createEntityManagerFactory" + clazz.getSimpleName());
newMethod = CtNewMethod.make(
"public javax.persistence.EntityManagerFactory createEntityManagerFactory(String persistenceUnitName, java.util.Map properties) {" +
" return " + Hibernate3JPAHelper.class.getName() + ".createEntityManagerFactoryProxy(" +
" persistenceUnitName, properties, _createEntityManagerFactory" + clazz.getSimpleName() + "(persistenceUnitName, properties)); " +
"}", clazz);
clazz.addMethod(newMethod);
}
/**
* Bean meta data manager register variable.
*
* @param ctClass the ct class
* @throws CannotCompileException the cannot compile exception
*/
@OnClassLoadEvent(classNameRegexp = "org.hibernate.validator.internal.metadata.BeanMetaDataManager")
public static void beanMetaDataManagerRegisterVariable(CtClass ctClass) throws CannotCompileException {<FILL_FUNCTION_BODY>}
/**
* Annotation meta data provider register variable.
*
* @param ctClass the ct class
* @throws CannotCompileException the cannot compile exception
*/
@OnClassLoadEvent(classNameRegexp = "org.hibernate.validator.internal.metadata.provider.AnnotationMetaDataProvider")
public static void annotationMetaDataProviderRegisterVariable(CtClass ctClass) throws CannotCompileException {
StringBuilder src = new StringBuilder("{");
src.append(PluginManagerInvoker.buildInitializePlugin(Hibernate3JPAPlugin.class));
src.append(PluginManagerInvoker.buildCallPluginMethod(Hibernate3JPAPlugin.class, "registerAnnotationMetaDataProvider",
"this", "java.lang.Object"));
src.append("}");
for (CtConstructor constructor : ctClass.getDeclaredConstructors()) {
constructor.insertAfter(src.toString());
}
ctClass.addMethod(CtNewMethod.make("public void __resetCache() {" +
" this.configuredBeans.clear(); " +
"}", ctClass));
LOGGER.debug("org.hibernate.validator.internal.metadata.provider.AnnotationMetaDataProvider - added method __resetCache().");
}
}
|
StringBuilder src = new StringBuilder("{");
src.append(PluginManagerInvoker.buildInitializePlugin(Hibernate3JPAPlugin.class));
src.append(PluginManagerInvoker.buildCallPluginMethod(Hibernate3JPAPlugin.class, "registerBeanMetaDataManager",
"this", "java.lang.Object"));
src.append("}");
for (CtConstructor constructor : ctClass.getDeclaredConstructors()) {
constructor.insertAfter(src.toString());
}
ctClass.addMethod(CtNewMethod.make("public void __resetCache() {" +
" this.beanMetaDataCache.clear(); " +
"}", ctClass));
LOGGER.debug("org.hibernate.validator.internal.metadata.BeanMetaDataManager - added method __resetCache().");
| 1,098 | 213 | 1,311 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/plugin/hotswap-agent-hibernate3-plugin/src/main/java/org/hotswap/agent/plugin/hibernate3/jpa/proxy/EntityManagerFactoryProxy.java
|
EntityManagerFactoryProxy
|
getWrapper
|
class EntityManagerFactoryProxy {
/** The logger. */
private static AgentLogger LOGGER = AgentLogger.getLogger(EntityManagerFactoryProxy.class);
/** The proxied factories. */
// Map persistenceUnitName -> Wrapper instance
private static Map<String, EntityManagerFactoryProxy> proxiedFactories = new HashMap<>();
/** The reload lock. */
// hold lock during refresh. The lock is checked on each factory method call.
final Object reloadLock = new Object();
/** The current instance. */
// current entity manager factory instance - this is the target this proxy delegates to
EntityManagerFactory currentInstance;
/** The persistence unit name. */
// info and properties to use to build fresh instance of factory
String persistenceUnitName;
/** The info. */
PersistenceUnitInfo info;
/** The properties. */
Map<?,?> properties;
/**
* Create new wrapper for persistenceUnitName and hold it's instance for future use.
*
* @param persistenceUnitName key to the wrapper
* @return existing wrapper or new instance (never null)
*/
public static EntityManagerFactoryProxy getWrapper(String persistenceUnitName) {<FILL_FUNCTION_BODY>}
/**
* Refresh all known wrapped factories.
*/
public static void refreshProxiedFactories() {
String[] version = Version.getVersionString().split("\\.");
boolean version43OrGreater = false;
try {
version43OrGreater = Integer.valueOf(version[0]) >= 4 && Integer.valueOf(version[1]) >= 3;
} catch (Exception e) {
LOGGER.warning("Unable to resolve hibernate version '{}'", Arrays.toString(version));
}
for (EntityManagerFactoryProxy wrapper : proxiedFactories.values())
try {
// lock proxy execution during reload
synchronized (wrapper.reloadLock) {
if (version43OrGreater) {
wrapper.refreshProxiedFactoryVersion43OrGreater();
} else {
wrapper.refreshProxiedFactory();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Refresh proxied factory version43 or greater.
*/
public void refreshProxiedFactoryVersion43OrGreater() {
if (info == null) {
currentInstance = Persistence.createEntityManagerFactory(persistenceUnitName, properties);
} else {
try {
Class<?> bootstrapClazz = loadClass("org.hibernate.jpa.boot.spi.Bootstrap");
Class<?> builderClazz = loadClass("org.hibernate.jpa.boot.spi.EntityManagerFactoryBuilder");
Object builder = ReflectionHelper.invoke(null, bootstrapClazz, "getEntityManagerFactoryBuilder",
new Class[]{PersistenceUnitInfo.class, Map.class}, info, properties);
currentInstance = (EntityManagerFactory) ReflectionHelper.invoke(builder, builderClazz, "build",
new Class[]{});
} catch (Exception e) {
e.printStackTrace();
LOGGER.error("Unable to reload persistence unit {}", info, e);
}
}
}
/**
* Refresh a single persistence unit - replace the wrapped EntityManagerFactory with fresh instance.
*
* @throws NoSuchMethodException the no such method exception
* @throws InvocationTargetException the invocation target exception
* @throws IllegalAccessException the illegal access exception
* @throws NoSuchFieldException the no such field exception
*/
public void refreshProxiedFactory() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, NoSuchFieldException {
// refresh registry
try {
Class<?> entityManagerFactoryRegistryClazz = loadClass("org.hibernate.ejb.internal.EntityManagerFactoryRegistry");
Object instance = ReflectionHelper.get(null, entityManagerFactoryRegistryClazz, "INSTANCE");
ReflectionHelper.invoke(instance, entityManagerFactoryRegistryClazz, "removeEntityManagerFactory",
new Class[] {String.class, EntityManagerFactory.class}, persistenceUnitName, currentInstance);
} catch (Exception e) {
LOGGER.error("Unable to clear previous instance of entity manager factory");
}
buildFreshEntityManagerFactory();
}
// create factory from cached configuration
/**
* Builds the fresh entity manager factory.
*/
// from HibernatePersistence.createContainerEntityManagerFactory()
private void buildFreshEntityManagerFactory() {
try {
Class<?> ejb3ConfigurationClazz = loadClass("org.hibernate.ejb.Ejb3Configuration");
LOGGER.trace("new Ejb3Configuration()");
Object cfg = ejb3ConfigurationClazz.newInstance();
LOGGER.trace("cfg.configure( info, properties );");
if (info != null) {
ReflectionHelper.invoke(cfg, ejb3ConfigurationClazz, "configure",
new Class[]{PersistenceUnitInfo.class, Map.class}, info, properties);
}
else {
ReflectionHelper.invoke(cfg, ejb3ConfigurationClazz, "configure",
new Class[]{String.class, Map.class}, persistenceUnitName, properties);
}
LOGGER.trace("configured.buildEntityManagerFactory()");
currentInstance = (EntityManagerFactory) ReflectionHelper.invoke(cfg, ejb3ConfigurationClazz, "buildEntityManagerFactory",
new Class[]{});
} catch (Exception e) {
LOGGER.error("Unable to build fresh entity manager factory for persistence unit {}", persistenceUnitName);
}
}
/**
* Create a proxy for EntityManagerFactory.
*
* @param factory initial factory to delegate method calls to.
* @param persistenceUnitName the persistence unit name
* @param info definition to cache for factory reload
* @param properties properties to cache for factory reload
* @return the proxy
*/
public EntityManagerFactory proxy(EntityManagerFactory factory, String persistenceUnitName,
PersistenceUnitInfo info, Map<?,?> properties) {
this.currentInstance = factory;
this.persistenceUnitName = persistenceUnitName;
this.info = info;
this.properties = properties;
return (EntityManagerFactory) Proxy.newProxyInstance(
currentInstance.getClass().getClassLoader(), currentInstance.getClass().getInterfaces(),
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// if reload in progress, wait for it
synchronized (reloadLock) {}
return method.invoke(currentInstance, args);
}
});
}
/**
* Load class.
*
* @param name the name
* @return the class
* @throws ClassNotFoundException the class not found exception
*/
private Class<?> loadClass(String name) throws ClassNotFoundException {
return getClass().getClassLoader().loadClass(name);
}
}
|
if (!proxiedFactories.containsKey(persistenceUnitName)) {
proxiedFactories.put(persistenceUnitName, new EntityManagerFactoryProxy());
}
return proxiedFactories.get(persistenceUnitName);
| 1,797 | 63 | 1,860 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/plugin/hotswap-agent-hibernate3-plugin/src/main/java/org/hotswap/agent/plugin/hibernate3/session/Hibernate3Plugin.java
|
Hibernate3Plugin
|
entityReload
|
class Hibernate3Plugin {
/** The Constant ENTITY_ANNOTATION. */
private static final String ENTITY_ANNOTATION = "javax.persistence.Entity";
/** The logger. */
private static AgentLogger LOGGER = AgentLogger.getLogger(Hibernate3Plugin.class);
/** The scheduler. */
@Init
Scheduler scheduler;
/** The app class loader. */
@Init
ClassLoader appClassLoader;
/** The version. */
String version;
/** The reload session factory command. */
// refresh command
private final Command reloadSessionFactoryCommand = new ReflectionCommand(this, Hibernate3RefreshCommand.class.getName(), "reloadSessionFactory");
/**
* Plugin initialization properties (from Hibernate3JPAHelper or
* SessionFactoryProxy).
*/
@Init
public void init() {
LOGGER.info("Hibernate3 Session plugin initialized", version);
}
/** The enabled. */
boolean enabled = true;
/**
* Disable plugin (if environment is JPA)
*
* Need to re-think this: Maybe use OverrideConfig to hold this info?.
*/
public void disable() {
LOGGER.info("Disabling Hibernate3 Session plugin since JPA is active");
this.enabled = false;
}
/**
* Sets the version.
*
* @param v
* the new version
*/
public void setVersion(String v) {
this.version = v;
LOGGER.info("Hibernate Core version '{}'", version);
}
/**
* Reload after entity class change. It covers also @Entity annotation
* removal.
*
* @param clazz
* the clazz
* @param original
* the original
*/
@OnClassLoadEvent(classNameRegexp = ".*", events = LoadEvent.REDEFINE)
public void entityReload(CtClass clazz, Class<?> original) {<FILL_FUNCTION_BODY>}
/**
* New entity class - not covered by reloading mechanism.
* <p/>
* Increase the reload timeout to avoid duplicate reloading in case of
* recompile with IDE and delete/create event sequence - than create is
* cached by this event and hotswap for the same class by entityReload.
*
* @param clazz
* the clazz
* @throws Exception
* the exception
*/
@OnClassFileEvent(classNameRegexp = ".*", events = { FileEvent.CREATE })
public void newEntity(CtClass clazz) throws Exception {
if (AnnotationHelper.hasAnnotation(clazz, ENTITY_ANNOTATION)) {
refresh(500);
}
}
/**
* Reload on hbm file modifications.
*/
@OnResourceFileEvent(path = "/", filter = ".*.hbm.xml")
public void refreshOnHbm() {
refresh(500);
}
/**
* Reload on hibernate.cfg.xml file modifications
*/
@OnResourceFileEvent(path = "/", filter = ".*.cfg.xml")
public void refreshOnCfg() {
refresh(500);
}
// reload the configuration - schedule a command to run in the application
/**
* Refresh.
*
* @param timeout
* the timeout
*/
// classloader and merge duplicate commands.
public void refresh(int timeout) {
if (enabled) {
scheduler.scheduleCommand(reloadSessionFactoryCommand, timeout);
}
}
}
|
// TODO list of entity/resource files is known to hibernate,
// better to check this list
if (AnnotationHelper.hasAnnotation(original, ENTITY_ANNOTATION) || AnnotationHelper.hasAnnotation(clazz, ENTITY_ANNOTATION)) {
LOGGER.debug("Entity reload class {}, original classloader {}", clazz.getName(), original.getClassLoader());
refresh(500);
}
| 940 | 107 | 1,047 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/plugin/hotswap-agent-hibernate3-plugin/src/main/java/org/hotswap/agent/plugin/hibernate3/session/Hibernate3RefreshCommand.java
|
Hibernate3RefreshCommand
|
reloadSessionFactory
|
class Hibernate3RefreshCommand {
/** The logger. */
private static AgentLogger LOGGER = AgentLogger.getLogger(Hibernate3RefreshCommand.class);
/**
* 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;
/**
* Reload session factory.
*/
public static void reloadSessionFactory() {<FILL_FUNCTION_BODY>}
}
|
LOGGER.debug("Refreshing SessionFactory configuration.");
SessionFactoryProxy.refreshProxiedFactories();
LOGGER.reload("Hibernate SessionFactory configuration refreshed.");
reloadFlag = false;
| 152 | 56 | 208 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/plugin/hotswap-agent-hibernate3-plugin/src/main/java/org/hotswap/agent/plugin/hibernate3/session/Hibernate3Transformers.java
|
Hibernate3Transformers
|
proxySessionFactory
|
class Hibernate3Transformers {
/** The logger. */
private static AgentLogger LOGGER = AgentLogger.getLogger(Hibernate3Transformers.class);
/**
* Ensure org.hibernate.impl.SessionFactoryImpl is Proxyable
*
* @param clazz
* the clazz
* @param classPool
* the class pool
* @param classLoader
* the class loader
* @throws Exception
* the exception
*/
@OnClassLoadEvent(classNameRegexp = "org.hibernate.impl.SessionFactoryImpl")
public static void removeSessionFactoryImplFinalFlag(CtClass clazz, ClassPool classPool, ClassLoader classLoader) throws Exception {
ProxyUtil.ensureProxyable(clazz);
LOGGER.info("Override org.hibernate.impl.SessionFactoryImpl {}", classLoader);
}
/**
* Patch org.hibernate.cfg.Configuration with ReInitializable features. When
* java8+ is supprted, then make methods default in ReInitializable
*
* @param classLoader
* the class loader
* @param classPool
* the class pool
* @param clazz
* the clazz
* @throws Exception
* the exception
*/
@OnClassLoadEvent(classNameRegexp = "org.hibernate.cfg.Configuration")
public static void proxySessionFactory(ClassLoader classLoader, ClassPool classPool, CtClass clazz) throws Exception {<FILL_FUNCTION_BODY>}
/**
* If org.hibernate.ejb.HibernatePersistence is loaded then we live in a JPA
* environment. Disable the Hibernate3Plugin reload command
*
* @param clazz
* the clazz
* @throws Exception
* the exception
*/
@OnClassLoadEvent(classNameRegexp = "org.hibernate.ejb.HibernatePersistence")
public static void proxyHibernatePersistence(CtClass clazz) throws Exception {
CtConstructor con = clazz.getDeclaredConstructor(new CtClass[] {});
LOGGER.debug("org.hibernate.ejb.HibernatePersistence.<init>");
con.insertAfter(//
"java.lang.ClassLoader $$cl = Thread.currentThread().getContextClassLoader();"//
+ PluginManagerInvoker.buildInitializePlugin(Hibernate3Plugin.class, "$$cl")//
+ PluginManagerInvoker.buildCallPluginMethod("$$cl", Hibernate3Plugin.class, "disable")//
);
}
}
|
LOGGER.debug("Adding interface o.h.a.p.h.s.p.ReInitializable to org.hibernate.cfg.Configuration.");
clazz.addInterface(classPool.get("org.hotswap.agent.plugin.hibernate3.session.proxy.ReInitializable"));
CtField field = CtField.make("private org.hotswap.agent.plugin.hibernate3.session.proxy.OverrideConfig $$override = new org.hotswap.agent.plugin.hibernate3.session.proxy.OverrideConfig();", clazz);
clazz.addField(field);
LOGGER.debug("Patching org.hibernate.cfg.Configuration#buildSessionFactory to create a SessionFactoryProxy proxy.");
CtMethod oldMethod = clazz.getDeclaredMethod("buildSessionFactory");
oldMethod.setName("_buildSessionFactory");
CtMethod newMethod = CtNewMethod.make(//
"public org.hibernate.SessionFactory buildSessionFactory() throws org.hibernate.HibernateException {" + //
" return " + SessionFactoryProxy.class.getName() + //
" .getWrapper(this)" + //
" .proxy(_buildSessionFactory()); " + //
"}",
clazz);
clazz.addMethod(newMethod);
LOGGER.debug("Adding org.hibernate.cfg.Configuration.reInitialize() method");
CtMethod reInitMethod = CtNewMethod.make(//
"public void reInitialize(){" + //
" this.settingsFactory = new org.hibernate.cfg.SettingsFactory();" + //
" this.reset();" + //
"}",
clazz);
clazz.addMethod(reInitMethod);
LOGGER.debug("Adding org.hibernate.cfg.Configuration.getOverrideConfig() method");
CtMethod internalPropsMethod = CtNewMethod.make(//
"public org.hotswap.agent.plugin.hibernate3.session.proxy.OverrideConfig getOverrideConfig(){" + //
" return $$override;" + //
"}",
clazz);
clazz.addMethod(internalPropsMethod);
CtConstructor con = clazz.getDeclaredConstructor(new CtClass[] {});
LOGGER.debug("Patching org.hibernate.cfg.Configuration.<init>");
con.insertAfter(//
"java.lang.ClassLoader $$cl = Thread.currentThread().getContextClassLoader();"//
+ PluginManagerInvoker.buildInitializePlugin(Hibernate3Plugin.class, "$$cl")//
+ "java.lang.String $$version = org.hibernate.Version.getVersionString();" //
+ PluginManagerInvoker.buildCallPluginMethod("$$cl", Hibernate3Plugin.class, "setVersion", "$$version", "java.lang.String")//
);
ProxyUtil.addMethod(classLoader, classPool, clazz, "void", "hotSwap", null);
ProxyUtil.addMethod(classLoader, classPool, clazz, "org.hibernate.cfg.Configuration", "setProperty", new String[] { "java.lang.String", "java.lang.String" });
ProxyUtil.addMethod(classLoader, classPool, clazz, "org.hibernate.cfg.Configuration", "configure", new String[] { "java.lang.String" });
ProxyUtil.addMethod(classLoader, classPool, clazz, "org.hibernate.cfg.Configuration", "configure", new String[] { "java.net.URL" });
ProxyUtil.addMethod(classLoader, classPool, clazz, "org.hibernate.cfg.Configuration", "configure", new String[] { "java.io.File" });
ProxyUtil.addMethod(classLoader, classPool, clazz, "org.hibernate.cfg.Configuration", "configure", new String[] { "org.w3c.dom.Document" });
ProxyUtil.addMethod(classLoader, classPool, clazz, "org.hibernate.cfg.Configuration", "configure", null);
LOGGER.info("Hibernate3Plugin, patched org.hibernate.cfg.Configuration");
| 656 | 1,039 | 1,695 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/plugin/hotswap-agent-hibernate3-plugin/src/main/java/org/hotswap/agent/plugin/hibernate3/session/proxy/ReInitializableHelper.java
|
ReInitializableHelper
|
configure
|
class ReInitializableHelper {
/** The logger. */
private static AgentLogger LOGGER = AgentLogger.getLogger(ReInitializableHelper.class);
/**
* Hot swap.
*
* @param r
* the r
*/
public static void hotSwap(ReInitializable r) {
OverrideConfig o = r.getOverrideConfig();
r.reInitialize();
switch (o.configuredBy) {
case FILE:
r.configure(File.class.cast(o.config));
break;
case NONE:
r.configure();
break;
case STRING:
r.configure(String.class.cast(o.config));
break;
case URL:
r.configure(URL.class.cast(o.config));
break;
case W3C:
r.configure(org.w3c.dom.Document.class.cast(o.config));
break;
default:
throw new RuntimeException("Don't know how to reconficure...");
}
for (Map.Entry<String, String> e : o.properties.entrySet()) {
r.setProperty(e.getKey(), e.getValue());
}
}
/**
* Sets the property.
*
* @param r
* the r
* @param propertyName
* the property name
* @param value
* the value
* @return the configuration
*/
public static Configuration setProperty(ReInitializable r, String propertyName, String value) {
LOGGER.debug("setProperty..................... key:" + propertyName + ", value:" + value);
r._setProperty(propertyName, value);
r.getOverrideConfig().properties.put(propertyName, value);
return (Configuration) r;
}
/**
* Configure.
*
* @param r
* the r
* @param resource
* the resource
* @return the configuration
* @throws HibernateException
* the hibernate exception
*/
public static Configuration configure(ReInitializable r, String resource) throws HibernateException {
LOGGER.debug("Configuring....................." + resource);
r._configure(resource);
r.getOverrideConfig().config = resource;
r.getOverrideConfig().configuredBy = ConfiguredBy.STRING;
r.getOverrideConfig().properties.clear();
return (Configuration) r;
}
/**
* Configure.
*
* @param r
* the r
* @param url
* the url
* @return the configuration
* @throws HibernateException
* the hibernate exception
*/
public static Configuration configure(ReInitializable r, java.net.URL url) throws HibernateException {
LOGGER.debug("Configuring....................." + url);
r._configure(url);
r.getOverrideConfig().config = url;
r.getOverrideConfig().configuredBy = ConfiguredBy.URL;
r.getOverrideConfig().properties.clear();
return (Configuration) r;
}
/**
* Configure.
*
* @param r
* the r
* @param configFile
* the config file
* @return the configuration
* @throws HibernateException
* the hibernate exception
*/
public static Configuration configure(ReInitializable r, java.io.File configFile) throws HibernateException {
System.err.println("Configuring....................." + configFile);
r._configure(configFile);
r.getOverrideConfig().properties.clear();
return (Configuration) r;
}
/**
* Configure.
*
* @param r
* the r
* @param document
* the document
* @return the configuration
* @throws HibernateException
* the hibernate exception
*/
public static Configuration configure(ReInitializable r, org.w3c.dom.Document document) throws HibernateException {<FILL_FUNCTION_BODY>}
/**
* Configure.
*
* @param r
* the r
* @return the configuration
* @throws HibernateException
* the hibernate exception
*/
public static Configuration configure(ReInitializable r) throws HibernateException {
LOGGER.debug("Configuring..................... EMPTY..");
r._configure();
r.getOverrideConfig().config = null;
r.getOverrideConfig().configuredBy = ConfiguredBy.NONE;
r.getOverrideConfig().properties.clear();
return (Configuration) r;
}
}
|
LOGGER.debug("Configuring....................." + document);
r._configure(document);
r.getOverrideConfig().config = document;
r.getOverrideConfig().configuredBy = ConfiguredBy.W3C;
r.getOverrideConfig().properties.clear();
return (Configuration) r;
| 1,185 | 79 | 1,264 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/plugin/hotswap-agent-hibernate3-plugin/src/main/java/org/hotswap/agent/plugin/hibernate3/session/proxy/SessionFactoryProxy.java
|
SessionFactoryProxy
|
getWrapper
|
class SessionFactoryProxy {
/** The proxied factories. */
private static Map<Configuration, SessionFactoryProxy> proxiedFactories = new HashMap<>();
/**
* Gets the wrapper.
*
* @param configuration
* the configuration
* @return the wrapper
*/
public static SessionFactoryProxy getWrapper(Configuration configuration) {<FILL_FUNCTION_BODY>}
/**
* Refresh proxied factories.
*/
public static void refreshProxiedFactories() {
synchronized (proxiedFactories) {
for (SessionFactoryProxy wrapper : proxiedFactories.values()) {
try {
wrapper.refreshProxiedFactory();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
/** The configuration. */
private Configuration configuration;
/** The current instance. */
private volatile SessionFactory currentInstance;
/**
* Instantiates a new session factory proxy.
*
* @param configuration
* the configuration
*/
private SessionFactoryProxy(Configuration configuration) {
this.configuration = configuration;
}
/**
* Refresh proxied factory.
*
* @throws NoSuchMethodException
* the no such method exception
* @throws InvocationTargetException
* the invocation target exception
* @throws IllegalAccessException
* the illegal access exception
*/
public void refreshProxiedFactory() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
ReInitializable r = ReInitializable.class.cast(configuration);
r.hotSwap();
currentInstance = r._buildSessionFactory();
}
/**
* Proxy.
*
* @param sessionFactory
* the session factory
* @return the session factory
*/
public SessionFactory proxy(SessionFactory sessionFactory) {
try {
this.currentInstance = sessionFactory;
ProxyFactory factory = new ProxyFactory();
factory.setSuperclass(SessionFactoryImpl.class);
factory.setInterfaces(new Class[] { SessionFactory.class, SessionFactoryImplementor.class });
MethodHandler handler = new MethodHandler() {
@Override
public Object invoke(Object self, Method overridden, Method forwarder, Object[] args) throws Throwable {
return overridden.invoke(currentInstance, args);
}
};
Object instance;
try {
Constructor<?> constructor = sun.reflect.ReflectionFactory.getReflectionFactory()//
.newConstructorForSerialization(factory.createClass(), Object.class.getDeclaredConstructor(new Class[0]));
instance = constructor.newInstance();
((Proxy) instance).setHandler(handler);
} catch (Exception e) {
e.printStackTrace();
throw new Error("Unable instantiate SessionFactory proxy", e);
}
return (SessionFactory) instance;
} catch (Exception e) {
e.printStackTrace();
throw new Error("Unable instantiate SessionFactory proxy", e);
}
}
}
|
synchronized (proxiedFactories) {
if (!proxiedFactories.containsKey(configuration)) {
proxiedFactories.put(configuration, new SessionFactoryProxy(configuration));
}
return proxiedFactories.get(configuration);
}
| 782 | 69 | 851 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/plugin/hotswap-agent-ibatis-plugin/src/main/java/org/hotswap/agent/plugin/ibatis/IBatisConfigurationHandler.java
|
IBatisConfigurationHandler
|
refresh
|
class IBatisConfigurationHandler {
private static AgentLogger LOGGER = AgentLogger.getLogger(IBatisConfigurationHandler.class);
private static Resource[] configLocations;
private static Resource[] mappingLocations;
private static Properties properties;
private static SqlMapConfigParser sqlMapConfigParser;
private static XmlParserState parserState;
/**
* Set the SqlMapConfigParser instance
* @param parser
*/
public static void setSqlMapConfigParser(SqlMapConfigParser parser) {
if(sqlMapConfigParser==null) {
sqlMapConfigParser=parser;
LOGGER.info("Set ibatis sql map config parser -> "+parser);
}
}
/**
* Set the iBATIS configLocation files
* @param configLocationsArg
* @param mappingLocationsArg
*/
public static void setMapFiles(Resource[] configLocationsArg,Resource[] mappingLocationsArg,Properties propertiesArg) {
configLocations=configLocationsArg;
mappingLocations=mappingLocationsArg;
properties=propertiesArg;
LOGGER.info("Set ibatis config files -> "+configLocations+","+mappingLocations+","+properties);
}
/**
* Set the XmlParserState instance
* @param parser
*/
public static void setParserState(XmlParserState state) {
if(parserState==null) {
parserState=state;
LOGGER.info("Set ibatis parser state -> "+state);
}
}
/**
* Convert Resource[] to String
* @param res
* @return
* @throws IOException
*/
public static String toPath(Resource[]res) throws IOException {
StringBuilder phs=new StringBuilder();
for(int i=0;i<res.length;i++) {
if(i!=0) phs.append("\n");
phs.append(res[i].getURL().getPath());
}
return phs.toString();
}
/**
* Refresh the iBATIS configuration
*/
public static void refresh() {<FILL_FUNCTION_BODY>}
}
|
LOGGER.info("Ibatis sql map refresh ...");
parserState.getSqlIncludes().clear();
ReflectionHelper.invoke(parserState.getConfig().getDelegate(), IBatisTransformers.REFRESH_METHOD);
for (Resource configLocation : configLocations) {
try {
InputStream is = configLocation.getInputStream();
sqlMapConfigParser.parse(is, properties);
}catch (Exception ex) {
LOGGER.error("Failed to parse config resource: " + configLocation, ex.getCause());
}
}
SqlMapParser parser=new SqlMapParser(parserState);
for (Resource mappingLocation : mappingLocations) {
try {
parser.parse(mappingLocation.getInputStream());
}catch (Exception ex) {
LOGGER.error("Failed to parse sql map resource: " + mappingLocation, ex.getCause());
}
}
LOGGER.info("Ibatis sql map refresh successful!!!");
| 605 | 263 | 868 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/plugin/hotswap-agent-ibatis-plugin/src/main/java/org/hotswap/agent/plugin/ibatis/IBatisPlugin.java
|
IBatisPlugin
|
registConfigFile
|
class IBatisPlugin {
private static AgentLogger LOGGER = AgentLogger.getLogger(IBatisPlugin.class);
@Init
private Scheduler scheduler;
@Init
private ClassLoader appClassLoader;
private Set<String> configFileSet = new HashSet<>();
private Command reloadIbatisConfigurationCommand =
new ReflectionCommand(this, IBatisConfigurationHandler.class.getName(), "refresh");
@Init
public void init(PluginConfiguration pluginConfiguration) {
LOGGER.info("IBatis plugin initialized.");
}
public void registConfigFile(String configFiles){<FILL_FUNCTION_BODY>}
@OnResourceFileEvent(path="/", filter = ".*.xml", events = {FileEvent.MODIFY})
public void registerResourceListenersModify(URL url) {
if(configFileSet.contains(url.getPath())) {
LOGGER.info("IBatis config file changed : {}", url.getPath());
scheduler.scheduleCommand(reloadIbatisConfigurationCommand, 500);
}
}
}
|
String[]paths=configFiles.split("\n");
for(String ph:paths) {
configFileSet.add(ph);
LOGGER.debug("IBatis config file registered : {}", ph);
}
| 310 | 63 | 373 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/plugin/hotswap-agent-ibatis-plugin/src/main/java/org/hotswap/agent/plugin/ibatis/IBatisTransformers.java
|
IBatisTransformers
|
patchSqlMapParser
|
class IBatisTransformers {
private static AgentLogger LOGGER = AgentLogger.getLogger(IBatisTransformers.class);
public static final String REFRESH_METHOD = "$$ha$refresh";
/**
* Set the SqlMapConfigParser instance
* @param ctClass
* @param classPool
* @throws CannotCompileException
* @throws NotFoundException
*/
@OnClassLoadEvent(classNameRegexp = "com.ibatis.sqlmap.engine.builder.xml.SqlMapConfigParser")
public static void patchSqlMapConfigParser(CtClass ctClass, ClassPool classPool) throws CannotCompileException, NotFoundException {
StringBuilder src = new StringBuilder("{");
src.append(IBatisConfigurationHandler.class.getName() + ".setSqlMapConfigParser(this);");
src.append("}");
CtClass[] constructorParams = new CtClass[] {};
ctClass.getDeclaredConstructor(constructorParams).insertAfter(src.toString());
LOGGER.debug("com.ibatis.sqlmap.engine.builder.xml.SqlMapConfigParser patched.");
}
/**
* Set ibatis sqlMap configLocation files
* @param ctClass
* @param classPool
* @throws CannotCompileException
* @throws NotFoundException
*/
@OnClassLoadEvent(classNameRegexp = "org.springframework.orm.ibatis.SqlMapClientFactoryBean")
public static void patchSqlMapClientFactoryBean(CtClass ctClass, ClassPool classPool) throws CannotCompileException, NotFoundException {
StringBuilder src = new StringBuilder("{");
src.append(PluginManagerInvoker.buildInitializePlugin(IBatisPlugin.class));
src.append(PluginManagerInvoker.buildCallPluginMethod(IBatisPlugin.class, "registConfigFile",IBatisConfigurationHandler.class.getName() + ".toPath(this.configLocations)", "java.lang.String"));
src.append(PluginManagerInvoker.buildCallPluginMethod(IBatisPlugin.class, "registConfigFile",IBatisConfigurationHandler.class.getName() + ".toPath(this.mappingLocations)", "java.lang.String"));
src.append(IBatisConfigurationHandler.class.getName() + ".setMapFiles(this.configLocations,this.mappingLocations,this.sqlMapClientProperties);");
src.append("}");
CtMethod method = ctClass.getDeclaredMethod("afterPropertiesSet");
method.insertAfter(src.toString());
LOGGER.debug("org.springframework.orm.ibatis.SqlMapClientFactoryBean patched.");
}
/**
* Set the XmlParserState instance
* @param ctClass
* @param classPool
* @throws CannotCompileException
* @throws NotFoundException
*/
@OnClassLoadEvent(classNameRegexp = "com.ibatis.sqlmap.engine.builder.xml.SqlMapParser")
public static void patchSqlMapParser(CtClass ctClass, ClassPool classPool) throws CannotCompileException, NotFoundException {<FILL_FUNCTION_BODY>}
/**
* Clear the SqlMapExecutorDelegate state
* @param ctClass
* @param classPool
* @throws CannotCompileException
*/
@OnClassLoadEvent(classNameRegexp = "com.ibatis.sqlmap.engine.impl.SqlMapExecutorDelegate")
public static void patchSqlMapExecutorDelegate(CtClass ctClass, ClassPool classPool) throws CannotCompileException {
CtMethod newMethod = CtNewMethod.make(
"public void " + REFRESH_METHOD + "() {" +
"this.mappedStatements.clear();" +
"}", ctClass);
ctClass.addMethod(newMethod);
LOGGER.debug("com.ibatis.sqlmap.engine.impl.SqlMapExecutorDelegate patched.");
}
}
|
StringBuilder src = new StringBuilder("{");
src.append(IBatisConfigurationHandler.class.getName() + ".setParserState(this.state);");
src.append("}");
CtClass[] constructorParams = new CtClass[] {
classPool.get("com.ibatis.sqlmap.engine.builder.xml.XmlParserState")
};
ctClass.getDeclaredConstructor(constructorParams).insertAfter(src.toString());
LOGGER.debug("com.ibatis.sqlmap.engine.builder.xml.SqlMapParser patched.");
| 1,054 | 152 | 1,206 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/plugin/hotswap-agent-idea-plugin/src/main/java/org/hotswap/agent/plugin/idea/IdeaPlugin.java
|
IdeaPlugin
|
patchUrlClassLoader
|
class IdeaPlugin {
private static AgentLogger LOGGER = AgentLogger.getLogger(IdeaPlugin.class);
private static boolean initialized = false;
public void init() {
if (!initialized) {
initialized = true;
LOGGER.info("Idea plugin plugin initialized.");
}
}
@OnClassLoadEvent(classNameRegexp = "com.intellij.util.lang.UrlClassLoader")
public static void patchUrlClassLoader(CtClass ctClass) throws CannotCompileException {<FILL_FUNCTION_BODY>}
}
|
if (!initialized) {
String initializePlugin = PluginManagerInvoker.buildInitializePlugin(IdeaPlugin.class, "appClassLoader");
String initializeThis = PluginManagerInvoker.buildCallPluginMethod("appClassLoader", IdeaPlugin.class, "init");
for (CtConstructor constructor : ctClass.getDeclaredConstructors()) {
constructor.insertAfter(initializePlugin);
constructor.insertAfter(initializeThis);
}
}
try {
ctClass.getDeclaredMethod("findClass").insertBefore(
"if ($1.startsWith(\"org.hotswap.agent\")) { " +
"return appClassLoader.loadClass($1);" +
"}"
);
} catch (NotFoundException e) {
LOGGER.warning("Unable to find method \"findClass()\" in com.intellij.util.lang.UrlClassLoader.", e);
}
try {
ctClass.getDeclaredMethod("getResourceAsStream").insertBefore(
"if ($1.startsWith(\"org/hotswap/agent\")) { " +
"return appClassLoader.getResourceAsStream($1);" +
"}"
);
} catch (NotFoundException e) {
LOGGER.warning("Unable to find method \"getResourceAsStream()\" in com.intellij.util.lang.UrlClassLoader.", e);
}
ctClass.addMethod(CtNewMethod.make(
"public java.net.URL getResource(String name) {" +
"if (name.startsWith(\"org/hotswap/agent/\")) { " +
"return appClassLoader.getResource(name);" +
"}" +
"return super.getResource(name);" +
"}", ctClass)
);
| 145 | 461 | 606 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/plugin/hotswap-agent-jackson-plugin/src/main/java/org/hotswap/agent/plugin/jackson/JacksonPlugin.java
|
JacksonPlugin
|
insertRegisterCacheObjectInConstructor
|
class JacksonPlugin {
private static final AgentLogger LOGGER = AgentLogger.getLogger(JacksonPlugin.class);
private static final String CLEAR_CACHE_METHOD = "ha$$clearCache";
public static boolean reloadFlag = false;
private final Set<Object> needToClearCacheObjects = Collections.synchronizedSet(Collections.newSetFromMap(new WeakHashMap<>()));
private final Command reloadJacksonCommand = new Command() {
public void executeCommand() {
reloadFlag = true;
try {
Set<Object> copy = Collections.newSetFromMap(new WeakHashMap<>());
synchronized (needToClearCacheObjects) {
copy.addAll(needToClearCacheObjects);
}
for (Object obj : copy) {
invokeClearCacheMethod(obj);
}
LOGGER.info("Reloaded Jackson.");
} catch (Exception e) {
LOGGER.error("Error reloading Jackson.", e);
} finally {
reloadFlag = false;
}
}
};
@Init
private Scheduler scheduler;
@OnClassLoadEvent(classNameRegexp = ".*", events = LoadEvent.REDEFINE)
public void reload() {
scheduler.scheduleCommand(reloadJacksonCommand, 500);
}
private static void insertRegisterCacheObjectInConstructor(CtClass ctClass) throws CannotCompileException{<FILL_FUNCTION_BODY>}
@OnClassLoadEvent(classNameRegexp = "com.fasterxml.jackson.databind.ObjectMapper", events = LoadEvent.DEFINE, skipSynthetic = false)
public static void patchObjectMapper(CtClass ctClass) throws CannotCompileException {
LOGGER.debug("Patch {}", ctClass);
insertRegisterCacheObjectInConstructor(ctClass);
CtMethod clearCacheMethod = CtNewMethod.make("public void " + CLEAR_CACHE_METHOD + "() {_rootDeserializers.clear();}", ctClass);
ctClass.addMethod(clearCacheMethod);
}
@OnClassLoadEvent(classNameRegexp = "com.fasterxml.jackson.databind.ser.SerializerCache", events = LoadEvent.DEFINE, skipSynthetic = false)
public static void patchSerializerCache(CtClass ctClass) throws CannotCompileException {
LOGGER.debug("Patch {}", ctClass);
insertRegisterCacheObjectInConstructor(ctClass);
CtMethod clearCacheMethod = CtNewMethod.make("public void " + CLEAR_CACHE_METHOD + "() {flush();}", ctClass);
ctClass.addMethod(clearCacheMethod);
}
@OnClassLoadEvent(classNameRegexp = "com.fasterxml.jackson.databind.deser.DeserializerCache", events = LoadEvent.DEFINE, skipSynthetic = false)
public static void patchDeserializerCache(CtClass ctClass) throws CannotCompileException {
LOGGER.debug("Patch {}", ctClass);
insertRegisterCacheObjectInConstructor(ctClass);
CtMethod clearCacheMethod = CtNewMethod.make("public void " + CLEAR_CACHE_METHOD + "() {flushCachedDeserializers();}", ctClass);
ctClass.addMethod(clearCacheMethod);
}
@OnClassLoadEvent(classNameRegexp = "com.fasterxml.jackson.databind.ser.impl.ReadOnlyClassToSerializerMap", events = LoadEvent.DEFINE, skipSynthetic = false)
public static void patchReadOnlyClassToSerializerMap(CtClass ctClass) throws CannotCompileException {
LOGGER.debug("Patch {}", ctClass);
insertRegisterCacheObjectInConstructor(ctClass);
CtMethod clearCacheMethod = CtNewMethod.make("public void " + CLEAR_CACHE_METHOD + "() {_buckets = new com.fasterxml.jackson.databind.ser.impl.ReadOnlyClassToSerializerMap.Bucket[_size];}", ctClass);
ctClass.addMethod(clearCacheMethod);
}
@OnClassLoadEvent(classNameRegexp = "com.fasterxml.jackson.databind.type.TypeFactory", events = LoadEvent.DEFINE, skipSynthetic = false)
public static void patchTypeFactory(CtClass ctClass) throws CannotCompileException {
LOGGER.debug("Patch {}", ctClass);
insertRegisterCacheObjectInConstructor(ctClass);
CtMethod clearCacheMethod = CtNewMethod.make("public void " + CLEAR_CACHE_METHOD + "() { _typeCache.clear();}", ctClass);
ctClass.addMethod(clearCacheMethod);
}
@OnClassLoadEvent(classNameRegexp = "com.fasterxml.jackson.databind.util.LRUMap", events = LoadEvent.DEFINE, skipSynthetic = false)
public static void patch(CtClass ctClass) throws CannotCompileException {
LOGGER.debug("Patch {}", ctClass);
insertRegisterCacheObjectInConstructor(ctClass);
CtMethod clearCacheMethod = CtNewMethod.make("public void " + CLEAR_CACHE_METHOD + "() { clear();}", ctClass);
ctClass.addMethod(clearCacheMethod);
}
public void registerNeedToClearCacheObjects(Object objectMapper) {
needToClearCacheObjects.add(objectMapper);
LOGGER.debug("register {}", objectMapper);
}
private static void invokeClearCacheMethod(Object obj) {
try {
LOGGER.debug("Reload {}", obj);
ReflectionHelper.invoke(obj, CLEAR_CACHE_METHOD);
} catch (Exception e) {
LOGGER.error("Reload failed {}", obj.getClass(), e);
}
}
}
|
for (CtConstructor constructor : ctClass.getDeclaredConstructors()) {
StringBuilder src = new StringBuilder("{");
src.append(PluginManagerInvoker.buildInitializePlugin(JacksonPlugin.class));
src.append(PluginManagerInvoker.buildCallPluginMethod(JacksonPlugin.class, "registerNeedToClearCacheObjects",
"this", "java.lang.Object"));
src.append("}");
constructor.insertAfter(src.toString());
}
| 1,497 | 121 | 1,618 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/plugin/hotswap-agent-jbossmodules-plugin/src/main/java/org/hotswap/agent/plugin/jbossmodules/JBossModulesPlugin.java
|
JBossModulesPlugin
|
transformModule
|
class JBossModulesPlugin {
protected static AgentLogger LOGGER = AgentLogger.getLogger(JBossModulesPlugin.class);
// TODO : Skip system packages, it should be in config file
private static final String SKIP_MODULES_REGEXP = "sun\\.jdk.*|ibm\\.jdk.*|javax\\..*|org\\.jboss\\..*";
private static final String USE_MODULES_REGEXP = "deployment\\..*";
@Init
ClassLoader moduleClassLoader;
@Init
public void init(PluginConfiguration pluginConfiguration) {
LOGGER.info("JBossModules plugin plugin initialized.");
}
@OnClassLoadEvent(classNameRegexp = "org.jboss.modules.ModuleLoader")
public static void transformModule(ClassPool classPool, CtClass ctClass) throws NotFoundException, CannotCompileException {<FILL_FUNCTION_BODY>}
}
|
try {
ctClass.getDeclaredMethod("loadModule", new CtClass[]{classPool.get(String.class.getName())}).insertAfter(
"if ($1.matches(\"" + USE_MODULES_REGEXP + "\")) {" +
PluginManagerInvoker.buildInitializePlugin(JBossModulesPlugin.class, "$_.getClassLoaderPrivate()") +
"}" +
"return $_;"
);
ctClass.getDeclaredMethod("unloadModuleLocal", new CtClass[]{classPool.get(String.class.getName()), classPool.get("org.jboss.modules.Module")}).insertBefore(
"if(!$1.matches(\"" + SKIP_MODULES_REGEXP + "\")) {" +
PluginManagerInvoker.buildCallCloseClassLoader("$2.getClassLoaderPrivate()") +
"}"
);
} catch (NotFoundException e) {
ctClass.getDeclaredMethod("loadModule", new CtClass[]{classPool.get("org.jboss.modules.ModuleIdentifier")}).insertAfter(
"if ($1.getName().matches(\"" + USE_MODULES_REGEXP + "\")) {" +
PluginManagerInvoker.buildInitializePlugin(JBossModulesPlugin.class, "$_.getClassLoaderPrivate()") +
"}" +
"return $_;"
);
ctClass.getDeclaredMethod("unloadModuleLocal", new CtClass[]{classPool.get("org.jboss.modules.Module")}).insertBefore(
"if(!$1.getIdentifier().getName().matches(\"" + SKIP_MODULES_REGEXP + "\")) {" +
PluginManagerInvoker.buildCallCloseClassLoader("$1.getClassLoaderPrivate()") +
"}"
);
}
LOGGER.debug("Class 'org.jboss.modules.Module' patched.");
| 238 | 485 | 723 |
<no_super_class>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.