id
int32
0
165k
repo
stringlengths
7
58
path
stringlengths
12
218
func_name
stringlengths
3
140
original_string
stringlengths
73
34.1k
language
stringclasses
1 value
code
stringlengths
73
34.1k
code_tokens
list
docstring
stringlengths
3
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
105
339
26,400
spring-projects/spring-loaded
springloaded/src/main/java/org/springsource/loaded/TypeRegistry.java
TypeRegistry.getTypeRegistryFor
public static TypeRegistry getTypeRegistryFor(ClassLoader classloader) { if (classloader == null) { return null; } //WeakReference<TypeRegistry> existingRegistryRef = loaderToRegistryMap.get(classloader); TypeRegistry existingRegistry = loaderToRegistryMap.get(classloader);//existingRegistryRef==null?null:existingRegistryRef.get(); if (existingRegistry != null) { return existingRegistry; } if (GlobalConfiguration.isRuntimeLogging && log.isLoggable(Level.INFO)) { if (excludedLoaderInstances.contains(classloader.toString())) { return null; } } String classloaderName = classloader.getClass().getName(); if (classloaderName.equals("sun.reflect.DelegatingClassLoader")) { return null; } for (String excluded : excludedLoaders) { if (classloaderName.startsWith(excluded)) { if (GlobalConfiguration.isRuntimeLogging && log.isLoggable(Level.FINEST)) { log.info("Classloader " + classloaderName + " has been deliberately excluded"); } excludedLoaderInstances.add(classloader.toString()); return null; } } // if (GlobalConfiguration.limit) { // // only allow for certain loaders! // boolean isOK = false; // if (classloaderName.equals("org.apache.catalina.loader.StandardClassLoader")) { // isOK = true; // } else if (classloaderName.equals("com.springsource.insight.collection.tcserver.ltw.TomcatWeavingInsightClassLoader")) { // isOK = true; // } else if (classloaderName.equals("org.springframework.instrument.classloading.tomcat.TomcatInstrumentableClassLoader")) { // isOK = true; // } else if (classloaderName.equals("org.apache.catalina.loader.WebappClassLoader")) { // isOK = true; // } // if (!isOK) { // return null; // } // } try { Class.forName("org.springsource.loaded.ri.ReflectiveInterceptor", false, classloader); } catch (ClassNotFoundException ex) { if (GlobalConfiguration.isRuntimeLogging && log.isLoggable(Level.INFO)) { log.info("No TypeRegistry (can't load ReflectiveInterceptor) for loader " + classloader); } return null; } if (GlobalConfiguration.isRuntimeLogging && log.isLoggable(Level.INFO)) { log.info("TypeRegistry.getRegistryFor(): creating new TypeRegistry for loader " + classloader); } TypeRegistry tr = new TypeRegistry(classloader); // if (GlobalConfiguration.isRuntimeLogging) { // Utils.log(100, "TypeRegistry.getTypeRegistryFor(classloader=" + classloader + ") returning " + tr); // } return tr; }
java
public static TypeRegistry getTypeRegistryFor(ClassLoader classloader) { if (classloader == null) { return null; } //WeakReference<TypeRegistry> existingRegistryRef = loaderToRegistryMap.get(classloader); TypeRegistry existingRegistry = loaderToRegistryMap.get(classloader);//existingRegistryRef==null?null:existingRegistryRef.get(); if (existingRegistry != null) { return existingRegistry; } if (GlobalConfiguration.isRuntimeLogging && log.isLoggable(Level.INFO)) { if (excludedLoaderInstances.contains(classloader.toString())) { return null; } } String classloaderName = classloader.getClass().getName(); if (classloaderName.equals("sun.reflect.DelegatingClassLoader")) { return null; } for (String excluded : excludedLoaders) { if (classloaderName.startsWith(excluded)) { if (GlobalConfiguration.isRuntimeLogging && log.isLoggable(Level.FINEST)) { log.info("Classloader " + classloaderName + " has been deliberately excluded"); } excludedLoaderInstances.add(classloader.toString()); return null; } } // if (GlobalConfiguration.limit) { // // only allow for certain loaders! // boolean isOK = false; // if (classloaderName.equals("org.apache.catalina.loader.StandardClassLoader")) { // isOK = true; // } else if (classloaderName.equals("com.springsource.insight.collection.tcserver.ltw.TomcatWeavingInsightClassLoader")) { // isOK = true; // } else if (classloaderName.equals("org.springframework.instrument.classloading.tomcat.TomcatInstrumentableClassLoader")) { // isOK = true; // } else if (classloaderName.equals("org.apache.catalina.loader.WebappClassLoader")) { // isOK = true; // } // if (!isOK) { // return null; // } // } try { Class.forName("org.springsource.loaded.ri.ReflectiveInterceptor", false, classloader); } catch (ClassNotFoundException ex) { if (GlobalConfiguration.isRuntimeLogging && log.isLoggable(Level.INFO)) { log.info("No TypeRegistry (can't load ReflectiveInterceptor) for loader " + classloader); } return null; } if (GlobalConfiguration.isRuntimeLogging && log.isLoggable(Level.INFO)) { log.info("TypeRegistry.getRegistryFor(): creating new TypeRegistry for loader " + classloader); } TypeRegistry tr = new TypeRegistry(classloader); // if (GlobalConfiguration.isRuntimeLogging) { // Utils.log(100, "TypeRegistry.getTypeRegistryFor(classloader=" + classloader + ") returning " + tr); // } return tr; }
[ "public", "static", "TypeRegistry", "getTypeRegistryFor", "(", "ClassLoader", "classloader", ")", "{", "if", "(", "classloader", "==", "null", ")", "{", "return", "null", ";", "}", "//WeakReference<TypeRegistry> existingRegistryRef = loaderToRegistryMap.get(classloader);", "TypeRegistry", "existingRegistry", "=", "loaderToRegistryMap", ".", "get", "(", "classloader", ")", ";", "//existingRegistryRef==null?null:existingRegistryRef.get();", "if", "(", "existingRegistry", "!=", "null", ")", "{", "return", "existingRegistry", ";", "}", "if", "(", "GlobalConfiguration", ".", "isRuntimeLogging", "&&", "log", ".", "isLoggable", "(", "Level", ".", "INFO", ")", ")", "{", "if", "(", "excludedLoaderInstances", ".", "contains", "(", "classloader", ".", "toString", "(", ")", ")", ")", "{", "return", "null", ";", "}", "}", "String", "classloaderName", "=", "classloader", ".", "getClass", "(", ")", ".", "getName", "(", ")", ";", "if", "(", "classloaderName", ".", "equals", "(", "\"sun.reflect.DelegatingClassLoader\"", ")", ")", "{", "return", "null", ";", "}", "for", "(", "String", "excluded", ":", "excludedLoaders", ")", "{", "if", "(", "classloaderName", ".", "startsWith", "(", "excluded", ")", ")", "{", "if", "(", "GlobalConfiguration", ".", "isRuntimeLogging", "&&", "log", ".", "isLoggable", "(", "Level", ".", "FINEST", ")", ")", "{", "log", ".", "info", "(", "\"Classloader \"", "+", "classloaderName", "+", "\" has been deliberately excluded\"", ")", ";", "}", "excludedLoaderInstances", ".", "add", "(", "classloader", ".", "toString", "(", ")", ")", ";", "return", "null", ";", "}", "}", "//\t\tif (GlobalConfiguration.limit) {", "//\t\t\t// only allow for certain loaders!", "//\t\t\tboolean isOK = false;", "//\t\t\tif (classloaderName.equals(\"org.apache.catalina.loader.StandardClassLoader\")) {", "//\t\t\t\tisOK = true;", "//\t\t\t} else if (classloaderName.equals(\"com.springsource.insight.collection.tcserver.ltw.TomcatWeavingInsightClassLoader\")) {", "//\t\t\t\tisOK = true;", "//\t\t\t} else if (classloaderName.equals(\"org.springframework.instrument.classloading.tomcat.TomcatInstrumentableClassLoader\")) {", "//\t\t\t\tisOK = true;", "//\t\t\t} else if (classloaderName.equals(\"org.apache.catalina.loader.WebappClassLoader\")) {", "//\t\t\t\tisOK = true;", "//\t\t\t}", "//\t\t\tif (!isOK) {", "//\t\t\t\treturn null;", "//\t\t\t}", "//\t\t}", "try", "{", "Class", ".", "forName", "(", "\"org.springsource.loaded.ri.ReflectiveInterceptor\"", ",", "false", ",", "classloader", ")", ";", "}", "catch", "(", "ClassNotFoundException", "ex", ")", "{", "if", "(", "GlobalConfiguration", ".", "isRuntimeLogging", "&&", "log", ".", "isLoggable", "(", "Level", ".", "INFO", ")", ")", "{", "log", ".", "info", "(", "\"No TypeRegistry (can't load ReflectiveInterceptor) for loader \"", "+", "classloader", ")", ";", "}", "return", "null", ";", "}", "if", "(", "GlobalConfiguration", ".", "isRuntimeLogging", "&&", "log", ".", "isLoggable", "(", "Level", ".", "INFO", ")", ")", "{", "log", ".", "info", "(", "\"TypeRegistry.getRegistryFor(): creating new TypeRegistry for loader \"", "+", "classloader", ")", ";", "}", "TypeRegistry", "tr", "=", "new", "TypeRegistry", "(", "classloader", ")", ";", "//\t\tif (GlobalConfiguration.isRuntimeLogging) {", "//\t\t\tUtils.log(100, \"TypeRegistry.getTypeRegistryFor(classloader=\" + classloader + \") returning \" + tr);", "//\t\t}", "return", "tr", ";", "}" ]
Factory access method for obtaining TypeRegistry instances. Returns a TypeRegistry for the specified classloader. @param classloader The classloader to create/retrieve the type registry for @return the TypeRegistry for the classloader
[ "Factory", "access", "method", "for", "obtaining", "TypeRegistry", "instances", ".", "Returns", "a", "TypeRegistry", "for", "the", "specified", "classloader", "." ]
59b32f957a05c6d9f149148158053605e2a6205a
https://github.com/spring-projects/spring-loaded/blob/59b32f957a05c6d9f149148158053605e2a6205a/springloaded/src/main/java/org/springsource/loaded/TypeRegistry.java#L254-L317
26,401
spring-projects/spring-loaded
springloaded/src/main/java/org/springsource/loaded/TypeRegistry.java
TypeRegistry.loadPlugins
private void loadPlugins() { // Read the plugin class names from well known resources try { Enumeration<URL> pluginResources = classLoader.get().getResources( "META-INF/services/org.springsource.reloading.agent.Plugins"); while (pluginResources.hasMoreElements()) { URL pluginResource = pluginResources.nextElement(); if (GlobalConfiguration.isRuntimeLogging && log.isLoggable(Level.FINEST)) { log.finest("loadPlugins: TypeRegistry=" + this.toString() + ": loading plugin list file " + pluginResource); } InputStream is = pluginResource.openStream(); BufferedReader pluginClassNamesReader = new BufferedReader(new InputStreamReader(is)); try { while (true) { String pluginName = pluginClassNamesReader.readLine(); if (pluginName == null) { break; } if (!pluginName.startsWith("#")) { pluginClassNames.add(pluginName); } } } catch (IOException ioe) { // eof } is.close(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // Now load those plugins for (String pluginClassName : pluginClassNames) { if (GlobalConfiguration.isRuntimeLogging && log.isLoggable(Level.FINEST)) { log.finest("loadPlugins: TypeRegistry=" + this.toString() + ": loading plugin " + pluginClassName); } try { Class<?> pluginClass = Class.forName(pluginClassName, false, this.classLoader.get()); Plugin pluginInstance = (Plugin) pluginClass.newInstance(); localPlugins.add(pluginInstance); } catch (Exception e) { log.log(Level.WARNING, "Unable to find and instantiate plugin " + pluginClassName, e); } } }
java
private void loadPlugins() { // Read the plugin class names from well known resources try { Enumeration<URL> pluginResources = classLoader.get().getResources( "META-INF/services/org.springsource.reloading.agent.Plugins"); while (pluginResources.hasMoreElements()) { URL pluginResource = pluginResources.nextElement(); if (GlobalConfiguration.isRuntimeLogging && log.isLoggable(Level.FINEST)) { log.finest("loadPlugins: TypeRegistry=" + this.toString() + ": loading plugin list file " + pluginResource); } InputStream is = pluginResource.openStream(); BufferedReader pluginClassNamesReader = new BufferedReader(new InputStreamReader(is)); try { while (true) { String pluginName = pluginClassNamesReader.readLine(); if (pluginName == null) { break; } if (!pluginName.startsWith("#")) { pluginClassNames.add(pluginName); } } } catch (IOException ioe) { // eof } is.close(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // Now load those plugins for (String pluginClassName : pluginClassNames) { if (GlobalConfiguration.isRuntimeLogging && log.isLoggable(Level.FINEST)) { log.finest("loadPlugins: TypeRegistry=" + this.toString() + ": loading plugin " + pluginClassName); } try { Class<?> pluginClass = Class.forName(pluginClassName, false, this.classLoader.get()); Plugin pluginInstance = (Plugin) pluginClass.newInstance(); localPlugins.add(pluginInstance); } catch (Exception e) { log.log(Level.WARNING, "Unable to find and instantiate plugin " + pluginClassName, e); } } }
[ "private", "void", "loadPlugins", "(", ")", "{", "// Read the plugin class names from well known resources", "try", "{", "Enumeration", "<", "URL", ">", "pluginResources", "=", "classLoader", ".", "get", "(", ")", ".", "getResources", "(", "\"META-INF/services/org.springsource.reloading.agent.Plugins\"", ")", ";", "while", "(", "pluginResources", ".", "hasMoreElements", "(", ")", ")", "{", "URL", "pluginResource", "=", "pluginResources", ".", "nextElement", "(", ")", ";", "if", "(", "GlobalConfiguration", ".", "isRuntimeLogging", "&&", "log", ".", "isLoggable", "(", "Level", ".", "FINEST", ")", ")", "{", "log", ".", "finest", "(", "\"loadPlugins: TypeRegistry=\"", "+", "this", ".", "toString", "(", ")", "+", "\": loading plugin list file \"", "+", "pluginResource", ")", ";", "}", "InputStream", "is", "=", "pluginResource", ".", "openStream", "(", ")", ";", "BufferedReader", "pluginClassNamesReader", "=", "new", "BufferedReader", "(", "new", "InputStreamReader", "(", "is", ")", ")", ";", "try", "{", "while", "(", "true", ")", "{", "String", "pluginName", "=", "pluginClassNamesReader", ".", "readLine", "(", ")", ";", "if", "(", "pluginName", "==", "null", ")", "{", "break", ";", "}", "if", "(", "!", "pluginName", ".", "startsWith", "(", "\"#\"", ")", ")", "{", "pluginClassNames", ".", "add", "(", "pluginName", ")", ";", "}", "}", "}", "catch", "(", "IOException", "ioe", ")", "{", "// eof", "}", "is", ".", "close", "(", ")", ";", "}", "}", "catch", "(", "IOException", "e", ")", "{", "// TODO Auto-generated catch block", "e", ".", "printStackTrace", "(", ")", ";", "}", "// Now load those plugins", "for", "(", "String", "pluginClassName", ":", "pluginClassNames", ")", "{", "if", "(", "GlobalConfiguration", ".", "isRuntimeLogging", "&&", "log", ".", "isLoggable", "(", "Level", ".", "FINEST", ")", ")", "{", "log", ".", "finest", "(", "\"loadPlugins: TypeRegistry=\"", "+", "this", ".", "toString", "(", ")", "+", "\": loading plugin \"", "+", "pluginClassName", ")", ";", "}", "try", "{", "Class", "<", "?", ">", "pluginClass", "=", "Class", ".", "forName", "(", "pluginClassName", ",", "false", ",", "this", ".", "classLoader", ".", "get", "(", ")", ")", ";", "Plugin", "pluginInstance", "=", "(", "Plugin", ")", "pluginClass", ".", "newInstance", "(", ")", ";", "localPlugins", ".", "add", "(", "pluginInstance", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "log", ".", "log", "(", "Level", ".", "WARNING", ",", "\"Unable to find and instantiate plugin \"", "+", "pluginClassName", ",", "e", ")", ";", "}", "}", "}" ]
Determine if any plugins are visible from the attached classloader
[ "Determine", "if", "any", "plugins", "are", "visible", "from", "the", "attached", "classloader" ]
59b32f957a05c6d9f149148158053605e2a6205a
https://github.com/spring-projects/spring-loaded/blob/59b32f957a05c6d9f149148158053605e2a6205a/springloaded/src/main/java/org/springsource/loaded/TypeRegistry.java#L392-L440
26,402
spring-projects/spring-loaded
springloaded/src/main/java/org/springsource/loaded/TypeRegistry.java
TypeRegistry.parseRebasePaths
private void parseRebasePaths(String rebaseDefinitions) { StringTokenizer tokenizer = new StringTokenizer(rebaseDefinitions, ","); while (tokenizer.hasMoreTokens()) { String rebasePair = tokenizer.nextToken(); int equals = rebasePair.indexOf('='); String fromPrefix = rebasePair.substring(0, equals); String toPrefix = rebasePair.substring(equals + 1); if (GlobalConfiguration.isRuntimeLogging && log.isLoggable(Level.INFO)) { log.info("processPropertiesConfiguration: adding rebase rule from '" + fromPrefix + "' to '" + toPrefix + "'"); } rebasePaths.put(fromPrefix, toPrefix); } }
java
private void parseRebasePaths(String rebaseDefinitions) { StringTokenizer tokenizer = new StringTokenizer(rebaseDefinitions, ","); while (tokenizer.hasMoreTokens()) { String rebasePair = tokenizer.nextToken(); int equals = rebasePair.indexOf('='); String fromPrefix = rebasePair.substring(0, equals); String toPrefix = rebasePair.substring(equals + 1); if (GlobalConfiguration.isRuntimeLogging && log.isLoggable(Level.INFO)) { log.info("processPropertiesConfiguration: adding rebase rule from '" + fromPrefix + "' to '" + toPrefix + "'"); } rebasePaths.put(fromPrefix, toPrefix); } }
[ "private", "void", "parseRebasePaths", "(", "String", "rebaseDefinitions", ")", "{", "StringTokenizer", "tokenizer", "=", "new", "StringTokenizer", "(", "rebaseDefinitions", ",", "\",\"", ")", ";", "while", "(", "tokenizer", ".", "hasMoreTokens", "(", ")", ")", "{", "String", "rebasePair", "=", "tokenizer", ".", "nextToken", "(", ")", ";", "int", "equals", "=", "rebasePair", ".", "indexOf", "(", "'", "'", ")", ";", "String", "fromPrefix", "=", "rebasePair", ".", "substring", "(", "0", ",", "equals", ")", ";", "String", "toPrefix", "=", "rebasePair", ".", "substring", "(", "equals", "+", "1", ")", ";", "if", "(", "GlobalConfiguration", ".", "isRuntimeLogging", "&&", "log", ".", "isLoggable", "(", "Level", ".", "INFO", ")", ")", "{", "log", ".", "info", "(", "\"processPropertiesConfiguration: adding rebase rule from '\"", "+", "fromPrefix", "+", "\"' to '\"", "+", "toPrefix", "+", "\"'\"", ")", ";", "}", "rebasePaths", ".", "put", "(", "fromPrefix", ",", "toPrefix", ")", ";", "}", "}" ]
Process a set of rebase definitions of the form 'a=b,c=d,e=f'.
[ "Process", "a", "set", "of", "rebase", "definitions", "of", "the", "form", "a", "=", "b", "c", "=", "d", "e", "=", "f", "." ]
59b32f957a05c6d9f149148158053605e2a6205a
https://github.com/spring-projects/spring-loaded/blob/59b32f957a05c6d9f149148158053605e2a6205a/springloaded/src/main/java/org/springsource/loaded/TypeRegistry.java#L518-L531
26,403
spring-projects/spring-loaded
springloaded/src/main/java/org/springsource/loaded/TypeRegistry.java
TypeRegistry.getTypeIdFor
public int getTypeIdFor(String slashname, boolean allocateIfNotFound) { if (allocateIfNotFound) { return NameRegistry.getIdOrAllocateFor(slashname); } else { return NameRegistry.getIdFor(slashname); } }
java
public int getTypeIdFor(String slashname, boolean allocateIfNotFound) { if (allocateIfNotFound) { return NameRegistry.getIdOrAllocateFor(slashname); } else { return NameRegistry.getIdFor(slashname); } }
[ "public", "int", "getTypeIdFor", "(", "String", "slashname", ",", "boolean", "allocateIfNotFound", ")", "{", "if", "(", "allocateIfNotFound", ")", "{", "return", "NameRegistry", ".", "getIdOrAllocateFor", "(", "slashname", ")", ";", "}", "else", "{", "return", "NameRegistry", ".", "getIdFor", "(", "slashname", ")", ";", "}", "}" ]
Lookup the type ID for a string. First checks those allocated but not yet registered, then those that are already registered. If not found then a new one is allocated and recorded. @param slashname the slashed type name, eg. a/b/c/D @param allocateIfNotFound determines whether an id should be allocated for the type if it cannot be found @return the unique ID number
[ "Lookup", "the", "type", "ID", "for", "a", "string", ".", "First", "checks", "those", "allocated", "but", "not", "yet", "registered", "then", "those", "that", "are", "already", "registered", ".", "If", "not", "found", "then", "a", "new", "one", "is", "allocated", "and", "recorded", "." ]
59b32f957a05c6d9f149148158053605e2a6205a
https://github.com/spring-projects/spring-loaded/blob/59b32f957a05c6d9f149148158053605e2a6205a/springloaded/src/main/java/org/springsource/loaded/TypeRegistry.java#L986-L993
26,404
spring-projects/spring-loaded
springloaded/src/main/java/org/springsource/loaded/TypeRegistry.java
TypeRegistry.rememberReloadableType
public void rememberReloadableType(int typeId, ReloadableType rtype) { if (typeId >= reloadableTypes.length) { resizeReloadableTypeArray(typeId); } reloadableTypes[typeId] = rtype; if ((typeId + 1) > reloadableTypesSize) { reloadableTypesSize = typeId + 1; } }
java
public void rememberReloadableType(int typeId, ReloadableType rtype) { if (typeId >= reloadableTypes.length) { resizeReloadableTypeArray(typeId); } reloadableTypes[typeId] = rtype; if ((typeId + 1) > reloadableTypesSize) { reloadableTypesSize = typeId + 1; } }
[ "public", "void", "rememberReloadableType", "(", "int", "typeId", ",", "ReloadableType", "rtype", ")", "{", "if", "(", "typeId", ">=", "reloadableTypes", ".", "length", ")", "{", "resizeReloadableTypeArray", "(", "typeId", ")", ";", "}", "reloadableTypes", "[", "typeId", "]", "=", "rtype", ";", "if", "(", "(", "typeId", "+", "1", ")", ">", "reloadableTypesSize", ")", "{", "reloadableTypesSize", "=", "typeId", "+", "1", ";", "}", "}" ]
Sometimes we discover the reloadabletype during program execution, for example A calls B and we haven't yet seen B. We find B has been loaded by a parent classloader, let's remember B here so we can do fast lookups for it. @param typeId the id for the type @param rtype the ReloadableType to associate with the id
[ "Sometimes", "we", "discover", "the", "reloadabletype", "during", "program", "execution", "for", "example", "A", "calls", "B", "and", "we", "haven", "t", "yet", "seen", "B", ".", "We", "find", "B", "has", "been", "loaded", "by", "a", "parent", "classloader", "let", "s", "remember", "B", "here", "so", "we", "can", "do", "fast", "lookups", "for", "it", "." ]
59b32f957a05c6d9f149148158053605e2a6205a
https://github.com/spring-projects/spring-loaded/blob/59b32f957a05c6d9f149148158053605e2a6205a/springloaded/src/main/java/org/springsource/loaded/TypeRegistry.java#L1195-L1203
26,405
spring-projects/spring-loaded
springloaded/src/main/java/org/springsource/loaded/TypeRegistry.java
TypeRegistry.getReloadableType
public ReloadableType getReloadableType(String slashedClassName) { int id = getTypeIdFor(slashedClassName, true); if (id >= reloadableTypesSize) { return null; } return getReloadableType(id); }
java
public ReloadableType getReloadableType(String slashedClassName) { int id = getTypeIdFor(slashedClassName, true); if (id >= reloadableTypesSize) { return null; } return getReloadableType(id); }
[ "public", "ReloadableType", "getReloadableType", "(", "String", "slashedClassName", ")", "{", "int", "id", "=", "getTypeIdFor", "(", "slashedClassName", ",", "true", ")", ";", "if", "(", "id", ">=", "reloadableTypesSize", ")", "{", "return", "null", ";", "}", "return", "getReloadableType", "(", "id", ")", ";", "}" ]
Determine the reloadabletype object representation for a specified class. If the caller already knows the ID for the type, that would be a quicker way to locate the reloadable type object. @param slashedClassName the slashed (e.g. java/lang/String) class name @return the ReloadableType
[ "Determine", "the", "reloadabletype", "object", "representation", "for", "a", "specified", "class", ".", "If", "the", "caller", "already", "knows", "the", "ID", "for", "the", "type", "that", "would", "be", "a", "quicker", "way", "to", "locate", "the", "reloadable", "type", "object", "." ]
59b32f957a05c6d9f149148158053605e2a6205a
https://github.com/spring-projects/spring-loaded/blob/59b32f957a05c6d9f149148158053605e2a6205a/springloaded/src/main/java/org/springsource/loaded/TypeRegistry.java#L1212-L1218
26,406
spring-projects/spring-loaded
springloaded/src/main/java/org/springsource/loaded/TypeRegistry.java
TypeRegistry.getReloadableType
public ReloadableType getReloadableType(String slashedClassname, boolean allocateIdIfNotYetLoaded) { if (allocateIdIfNotYetLoaded) { return getReloadableType(getTypeIdFor(slashedClassname, allocateIdIfNotYetLoaded)); } else { for (int i = 0; i < reloadableTypesSize; i++) { ReloadableType rtype = reloadableTypes[i]; if (rtype != null && rtype.getSlashedName().equals(slashedClassname)) { return rtype; } } return null; } }
java
public ReloadableType getReloadableType(String slashedClassname, boolean allocateIdIfNotYetLoaded) { if (allocateIdIfNotYetLoaded) { return getReloadableType(getTypeIdFor(slashedClassname, allocateIdIfNotYetLoaded)); } else { for (int i = 0; i < reloadableTypesSize; i++) { ReloadableType rtype = reloadableTypes[i]; if (rtype != null && rtype.getSlashedName().equals(slashedClassname)) { return rtype; } } return null; } }
[ "public", "ReloadableType", "getReloadableType", "(", "String", "slashedClassname", ",", "boolean", "allocateIdIfNotYetLoaded", ")", "{", "if", "(", "allocateIdIfNotYetLoaded", ")", "{", "return", "getReloadableType", "(", "getTypeIdFor", "(", "slashedClassname", ",", "allocateIdIfNotYetLoaded", ")", ")", ";", "}", "else", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "reloadableTypesSize", ";", "i", "++", ")", "{", "ReloadableType", "rtype", "=", "reloadableTypes", "[", "i", "]", ";", "if", "(", "rtype", "!=", "null", "&&", "rtype", ".", "getSlashedName", "(", ")", ".", "equals", "(", "slashedClassname", ")", ")", "{", "return", "rtype", ";", "}", "}", "return", "null", ";", "}", "}" ]
Find the ReloadableType object for a given classname. If the allocateIdIfNotYetLoaded option is set then a new id will be allocated for this classname if it hasn't previously been seen before. This method does not create new ReloadableType objects, they are expected to come into existence when defined by the classloader. @param slashedClassname the slashed class name (e.g. java/lang/String) @param allocateIdIfNotYetLoaded if true an id will be allocated because sometime later the type will be loaded (and made reloadable) @return the ReloadableType discovered or allocated, or null if not found and !allocateIdIfNotYetLoaded
[ "Find", "the", "ReloadableType", "object", "for", "a", "given", "classname", ".", "If", "the", "allocateIdIfNotYetLoaded", "option", "is", "set", "then", "a", "new", "id", "will", "be", "allocated", "for", "this", "classname", "if", "it", "hasn", "t", "previously", "been", "seen", "before", ".", "This", "method", "does", "not", "create", "new", "ReloadableType", "objects", "they", "are", "expected", "to", "come", "into", "existence", "when", "defined", "by", "the", "classloader", "." ]
59b32f957a05c6d9f149148158053605e2a6205a
https://github.com/spring-projects/spring-loaded/blob/59b32f957a05c6d9f149148158053605e2a6205a/springloaded/src/main/java/org/springsource/loaded/TypeRegistry.java#L1269-L1282
26,407
spring-projects/spring-loaded
springloaded/src/main/java/org/springsource/loaded/TypeRegistry.java
TypeRegistry.istcheck
@UsedByGeneratedCode public static Object istcheck(int ids, String nameAndDescriptor) { if (TypeRegistry.nothingReloaded) { return null; } int registryId = ids >>> 16; int typeId = ids & 0xffff; TypeRegistry typeRegistry = registryInstances[registryId].get(); ReloadableType reloadableType = typeRegistry.getReloadableType(typeId); if (reloadableType == null) { reloadableType = searchForReloadableType(typeId, typeRegistry); } // Check 2: Info computed earlier if (reloadableType != null && !reloadableType.isAffectedByReload()) { return null; } if (reloadableType != null && reloadableType.hasBeenReloaded()) { MethodMember method = reloadableType.getLiveVersion().incrementalTypeDescriptor.getFromLatestByDescriptor( nameAndDescriptor); boolean dispatchThroughDescriptor = false; if (method == null) { // method has been deleted or is on a supertype. Look for it: // TODO this block is based on something below in invokespecial handling but this has some // fixes in - should they be migrated down below or a common util method constructed? Object dispatcherToUse = null; String supertypename = reloadableType.getTypeDescriptor().getSupertypeName(); TypeRegistry reg = reloadableType.getTypeRegistry(); boolean found = false; while (supertypename != null) { ReloadableType nextInHierarchy = reg.getReloadableType(supertypename); if (nextInHierarchy == null) { TypeDescriptor td = reg.getDescriptorFor(supertypename); if (td != null) { method = td.getByNameAndDescriptor(nameAndDescriptor); supertypename = td.getSupertypeName(); } else { break; } } else if (nextInHierarchy.hasBeenReloaded()) { method = nextInHierarchy.getLiveVersion().incrementalTypeDescriptor.getFromLatestByDescriptor( nameAndDescriptor); if (method != null && IncrementalTypeDescriptor.wasDeleted(method)) { method = null; } // ignore catchers because the dynamic __execute method wont have an implementation of them, we should // just keep looking for the real thing if (method != null && (MethodMember.isCatcher(method) || MethodMember.isSuperDispatcher(method))) { method = null; } } else { // it is reloadable but has not been reloaded method = nextInHierarchy.getMethod(nameAndDescriptor); } if (method != null) { found = true; break; } // the nextInHierarchy==null case will have already set the supertypename if (nextInHierarchy != null) { supertypename = nextInHierarchy.getSlashedSupertypeName(); } } if (found) { return dispatcherToUse; } throw new NoSuchMethodError(reloadableType.getBaseName() + "." + nameAndDescriptor); } else if (IncrementalTypeDescriptor.isBrandNewMethod(method)) { // definetly need to use the dispatcher dispatchThroughDescriptor = true; } else if (IncrementalTypeDescriptor.hasChanged(method)) { if (IncrementalTypeDescriptor.isNowNonStatic(method)) { throw new IncompatibleClassChangeError( "SpringLoaded: Target of static call is no longer static '" + reloadableType.getBaseName() + "." + nameAndDescriptor + "'"); } // TODO need a check in here for a visibility change? Something like this: // if (IncrementalTypeDescriptor.hasVisibilityChanged(method)) { // dispatchThroughDescriptor = true; // } } if (dispatchThroughDescriptor) { if (GlobalConfiguration.isRuntimeLogging && log.isLoggable(Level.FINER)) { log.info("istcheck(): reloadabletype=" + reloadableType + " versionstamp " + reloadableType.getLiveVersion().versionstamp); } return reloadableType.getLatestDispatcherInstance(); } } return null; }
java
@UsedByGeneratedCode public static Object istcheck(int ids, String nameAndDescriptor) { if (TypeRegistry.nothingReloaded) { return null; } int registryId = ids >>> 16; int typeId = ids & 0xffff; TypeRegistry typeRegistry = registryInstances[registryId].get(); ReloadableType reloadableType = typeRegistry.getReloadableType(typeId); if (reloadableType == null) { reloadableType = searchForReloadableType(typeId, typeRegistry); } // Check 2: Info computed earlier if (reloadableType != null && !reloadableType.isAffectedByReload()) { return null; } if (reloadableType != null && reloadableType.hasBeenReloaded()) { MethodMember method = reloadableType.getLiveVersion().incrementalTypeDescriptor.getFromLatestByDescriptor( nameAndDescriptor); boolean dispatchThroughDescriptor = false; if (method == null) { // method has been deleted or is on a supertype. Look for it: // TODO this block is based on something below in invokespecial handling but this has some // fixes in - should they be migrated down below or a common util method constructed? Object dispatcherToUse = null; String supertypename = reloadableType.getTypeDescriptor().getSupertypeName(); TypeRegistry reg = reloadableType.getTypeRegistry(); boolean found = false; while (supertypename != null) { ReloadableType nextInHierarchy = reg.getReloadableType(supertypename); if (nextInHierarchy == null) { TypeDescriptor td = reg.getDescriptorFor(supertypename); if (td != null) { method = td.getByNameAndDescriptor(nameAndDescriptor); supertypename = td.getSupertypeName(); } else { break; } } else if (nextInHierarchy.hasBeenReloaded()) { method = nextInHierarchy.getLiveVersion().incrementalTypeDescriptor.getFromLatestByDescriptor( nameAndDescriptor); if (method != null && IncrementalTypeDescriptor.wasDeleted(method)) { method = null; } // ignore catchers because the dynamic __execute method wont have an implementation of them, we should // just keep looking for the real thing if (method != null && (MethodMember.isCatcher(method) || MethodMember.isSuperDispatcher(method))) { method = null; } } else { // it is reloadable but has not been reloaded method = nextInHierarchy.getMethod(nameAndDescriptor); } if (method != null) { found = true; break; } // the nextInHierarchy==null case will have already set the supertypename if (nextInHierarchy != null) { supertypename = nextInHierarchy.getSlashedSupertypeName(); } } if (found) { return dispatcherToUse; } throw new NoSuchMethodError(reloadableType.getBaseName() + "." + nameAndDescriptor); } else if (IncrementalTypeDescriptor.isBrandNewMethod(method)) { // definetly need to use the dispatcher dispatchThroughDescriptor = true; } else if (IncrementalTypeDescriptor.hasChanged(method)) { if (IncrementalTypeDescriptor.isNowNonStatic(method)) { throw new IncompatibleClassChangeError( "SpringLoaded: Target of static call is no longer static '" + reloadableType.getBaseName() + "." + nameAndDescriptor + "'"); } // TODO need a check in here for a visibility change? Something like this: // if (IncrementalTypeDescriptor.hasVisibilityChanged(method)) { // dispatchThroughDescriptor = true; // } } if (dispatchThroughDescriptor) { if (GlobalConfiguration.isRuntimeLogging && log.isLoggable(Level.FINER)) { log.info("istcheck(): reloadabletype=" + reloadableType + " versionstamp " + reloadableType.getLiveVersion().versionstamp); } return reloadableType.getLatestDispatcherInstance(); } } return null; }
[ "@", "UsedByGeneratedCode", "public", "static", "Object", "istcheck", "(", "int", "ids", ",", "String", "nameAndDescriptor", ")", "{", "if", "(", "TypeRegistry", ".", "nothingReloaded", ")", "{", "return", "null", ";", "}", "int", "registryId", "=", "ids", ">>>", "16", ";", "int", "typeId", "=", "ids", "&", "0xffff", ";", "TypeRegistry", "typeRegistry", "=", "registryInstances", "[", "registryId", "]", ".", "get", "(", ")", ";", "ReloadableType", "reloadableType", "=", "typeRegistry", ".", "getReloadableType", "(", "typeId", ")", ";", "if", "(", "reloadableType", "==", "null", ")", "{", "reloadableType", "=", "searchForReloadableType", "(", "typeId", ",", "typeRegistry", ")", ";", "}", "// Check 2: Info computed earlier", "if", "(", "reloadableType", "!=", "null", "&&", "!", "reloadableType", ".", "isAffectedByReload", "(", ")", ")", "{", "return", "null", ";", "}", "if", "(", "reloadableType", "!=", "null", "&&", "reloadableType", ".", "hasBeenReloaded", "(", ")", ")", "{", "MethodMember", "method", "=", "reloadableType", ".", "getLiveVersion", "(", ")", ".", "incrementalTypeDescriptor", ".", "getFromLatestByDescriptor", "(", "nameAndDescriptor", ")", ";", "boolean", "dispatchThroughDescriptor", "=", "false", ";", "if", "(", "method", "==", "null", ")", "{", "// method has been deleted or is on a supertype. Look for it:", "// TODO this block is based on something below in invokespecial handling but this has some", "// fixes in - should they be migrated down below or a common util method constructed?", "Object", "dispatcherToUse", "=", "null", ";", "String", "supertypename", "=", "reloadableType", ".", "getTypeDescriptor", "(", ")", ".", "getSupertypeName", "(", ")", ";", "TypeRegistry", "reg", "=", "reloadableType", ".", "getTypeRegistry", "(", ")", ";", "boolean", "found", "=", "false", ";", "while", "(", "supertypename", "!=", "null", ")", "{", "ReloadableType", "nextInHierarchy", "=", "reg", ".", "getReloadableType", "(", "supertypename", ")", ";", "if", "(", "nextInHierarchy", "==", "null", ")", "{", "TypeDescriptor", "td", "=", "reg", ".", "getDescriptorFor", "(", "supertypename", ")", ";", "if", "(", "td", "!=", "null", ")", "{", "method", "=", "td", ".", "getByNameAndDescriptor", "(", "nameAndDescriptor", ")", ";", "supertypename", "=", "td", ".", "getSupertypeName", "(", ")", ";", "}", "else", "{", "break", ";", "}", "}", "else", "if", "(", "nextInHierarchy", ".", "hasBeenReloaded", "(", ")", ")", "{", "method", "=", "nextInHierarchy", ".", "getLiveVersion", "(", ")", ".", "incrementalTypeDescriptor", ".", "getFromLatestByDescriptor", "(", "nameAndDescriptor", ")", ";", "if", "(", "method", "!=", "null", "&&", "IncrementalTypeDescriptor", ".", "wasDeleted", "(", "method", ")", ")", "{", "method", "=", "null", ";", "}", "// ignore catchers because the dynamic __execute method wont have an implementation of them, we should", "// just keep looking for the real thing", "if", "(", "method", "!=", "null", "&&", "(", "MethodMember", ".", "isCatcher", "(", "method", ")", "||", "MethodMember", ".", "isSuperDispatcher", "(", "method", ")", ")", ")", "{", "method", "=", "null", ";", "}", "}", "else", "{", "// it is reloadable but has not been reloaded", "method", "=", "nextInHierarchy", ".", "getMethod", "(", "nameAndDescriptor", ")", ";", "}", "if", "(", "method", "!=", "null", ")", "{", "found", "=", "true", ";", "break", ";", "}", "// the nextInHierarchy==null case will have already set the supertypename", "if", "(", "nextInHierarchy", "!=", "null", ")", "{", "supertypename", "=", "nextInHierarchy", ".", "getSlashedSupertypeName", "(", ")", ";", "}", "}", "if", "(", "found", ")", "{", "return", "dispatcherToUse", ";", "}", "throw", "new", "NoSuchMethodError", "(", "reloadableType", ".", "getBaseName", "(", ")", "+", "\".\"", "+", "nameAndDescriptor", ")", ";", "}", "else", "if", "(", "IncrementalTypeDescriptor", ".", "isBrandNewMethod", "(", "method", ")", ")", "{", "// definetly need to use the dispatcher", "dispatchThroughDescriptor", "=", "true", ";", "}", "else", "if", "(", "IncrementalTypeDescriptor", ".", "hasChanged", "(", "method", ")", ")", "{", "if", "(", "IncrementalTypeDescriptor", ".", "isNowNonStatic", "(", "method", ")", ")", "{", "throw", "new", "IncompatibleClassChangeError", "(", "\"SpringLoaded: Target of static call is no longer static '\"", "+", "reloadableType", ".", "getBaseName", "(", ")", "+", "\".\"", "+", "nameAndDescriptor", "+", "\"'\"", ")", ";", "}", "// TODO need a check in here for a visibility change? Something like this:", "//\t\t\t\tif (IncrementalTypeDescriptor.hasVisibilityChanged(method)) {", "//\t\t\t\t\tdispatchThroughDescriptor = true;", "//\t\t\t\t}", "}", "if", "(", "dispatchThroughDescriptor", ")", "{", "if", "(", "GlobalConfiguration", ".", "isRuntimeLogging", "&&", "log", ".", "isLoggable", "(", "Level", ".", "FINER", ")", ")", "{", "log", ".", "info", "(", "\"istcheck(): reloadabletype=\"", "+", "reloadableType", "+", "\" versionstamp \"", "+", "reloadableType", ".", "getLiveVersion", "(", ")", ".", "versionstamp", ")", ";", "}", "return", "reloadableType", ".", "getLatestDispatcherInstance", "(", ")", ";", "}", "}", "return", "null", ";", "}" ]
Determine if something has changed in a particular type related to a particular descriptor and so the dispatcher interface should be used. The type registry ID and class ID are merged in the 'ids' parameter. This method is for INVOKESTATIC rewrites and so performs additional checks because it assumes the target is static. @param ids packed representation of the registryId (top 16bits) and typeId (bottom 16bits) @param nameAndDescriptor the name and descriptor of the method about to be INVOKESTATIC'd @return null if the original code can run otherwise return the dispatcher to use
[ "Determine", "if", "something", "has", "changed", "in", "a", "particular", "type", "related", "to", "a", "particular", "descriptor", "and", "so", "the", "dispatcher", "interface", "should", "be", "used", ".", "The", "type", "registry", "ID", "and", "class", "ID", "are", "merged", "in", "the", "ids", "parameter", ".", "This", "method", "is", "for", "INVOKESTATIC", "rewrites", "and", "so", "performs", "additional", "checks", "because", "it", "assumes", "the", "target", "is", "static", "." ]
59b32f957a05c6d9f149148158053605e2a6205a
https://github.com/spring-projects/spring-loaded/blob/59b32f957a05c6d9f149148158053605e2a6205a/springloaded/src/main/java/org/springsource/loaded/TypeRegistry.java#L1367-L1467
26,408
spring-projects/spring-loaded
springloaded/src/main/java/org/springsource/loaded/TypeRegistry.java
TypeRegistry.instanceFieldInterceptionRequired
@UsedByGeneratedCode public static boolean instanceFieldInterceptionRequired(int ids, String name) { if (nothingReloaded) { return false; } int registryId = ids >>> 16; int typeId = ids & 0xffff; TypeRegistry typeRegistry = registryInstances[registryId].get(); ReloadableType reloadableType = typeRegistry.getReloadableType(typeId); // TODO covers all situations? if (reloadableType != null) { if (reloadableType.hasFieldChangedInHierarchy(name)) { return true; } } return false; }
java
@UsedByGeneratedCode public static boolean instanceFieldInterceptionRequired(int ids, String name) { if (nothingReloaded) { return false; } int registryId = ids >>> 16; int typeId = ids & 0xffff; TypeRegistry typeRegistry = registryInstances[registryId].get(); ReloadableType reloadableType = typeRegistry.getReloadableType(typeId); // TODO covers all situations? if (reloadableType != null) { if (reloadableType.hasFieldChangedInHierarchy(name)) { return true; } } return false; }
[ "@", "UsedByGeneratedCode", "public", "static", "boolean", "instanceFieldInterceptionRequired", "(", "int", "ids", ",", "String", "name", ")", "{", "if", "(", "nothingReloaded", ")", "{", "return", "false", ";", "}", "int", "registryId", "=", "ids", ">>>", "16", ";", "int", "typeId", "=", "ids", "&", "0xffff", ";", "TypeRegistry", "typeRegistry", "=", "registryInstances", "[", "registryId", "]", ".", "get", "(", ")", ";", "ReloadableType", "reloadableType", "=", "typeRegistry", ".", "getReloadableType", "(", "typeId", ")", ";", "// TODO covers all situations?", "if", "(", "reloadableType", "!=", "null", ")", "{", "if", "(", "reloadableType", ".", "hasFieldChangedInHierarchy", "(", "name", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Called for a field operation - trying to determine whether a particular field needs special handling. @param ids packed representation of the registryId (top 16bits) and typeId (bottom 16bits) @param name the name of the instance field about to be accessed @return true if the field operation must be intercepted
[ "Called", "for", "a", "field", "operation", "-", "trying", "to", "determine", "whether", "a", "particular", "field", "needs", "special", "handling", "." ]
59b32f957a05c6d9f149148158053605e2a6205a
https://github.com/spring-projects/spring-loaded/blob/59b32f957a05c6d9f149148158053605e2a6205a/springloaded/src/main/java/org/springsource/loaded/TypeRegistry.java#L1747-L1763
26,409
spring-projects/spring-loaded
springloaded/src/main/java/org/springsource/loaded/TypeRegistry.java
TypeRegistry.ivicheck
@UsedByGeneratedCode public static boolean ivicheck(int ids, String nameAndDescriptor) { // Check 1: FAST: Has anything at all been reloaded? if (nothingReloaded) { return false; } // if (GlobalConfiguration.isRuntimeLogging && log.isLoggable(Level.FINER)) { // log.entering("TypeRegistry", "ivicheck", new Object[] { ids, nameAndDescriptor }); // } // TODO [perf] global check (anything been reloaded?) // TODO [perf] local check (type or anything in its hierarchy reloaded) int registryId = ids >>> 16; int typeId = ids & 0xffff; TypeRegistry typeRegistry = registryInstances[registryId].get(); ReloadableType reloadableType = typeRegistry.getReloadableType(typeId); // Ok, think about what null means here. It means this registry has not loaded this type as a reloadable type. That doesn't // mean it isn't reloadable as a parent loaded may have found it. We have 3 options: // 1. assume names are unique - we can look up this type and find the registry in question // 2. assume delegating classloaders and search the parent registry for it // 3. pass something in at the call site (the class obejct), this would give us the classloader and thus the registry // 3 is ideal, but slower. 2 is nice but not always safe. 1 will work in a lot of situations. // let's try with a (2) strategy, fallback on a (1) - when we revisit this we can end up doing (3) maybe... // TODO [grails] We need a sentinel to indicate that we've had a look, so that we dont go off searching every time, but for now, lets // just do the search: if (reloadableType == null) { reloadableType = searchForReloadableType(typeId, typeRegistry); } // Check 2: Info computed earlier if (reloadableType != null && !reloadableType.isAffectedByReload()) { return false; } if (reloadableType != null && reloadableType.hasBeenReloaded()) { MethodMember method = reloadableType.getLiveVersion().incrementalTypeDescriptor.getFromLatestByDescriptor( nameAndDescriptor); boolean dispatchThroughDescriptor = false; if (method == null) { if (!reloadableType.getTypeDescriptor().isFinalInHierarchy(nameAndDescriptor)) { // Reloading has occurred and method does not exist in new version, throw NSME throw new NoSuchMethodError(reloadableType.getBaseName() + "." + nameAndDescriptor); } } else if (IncrementalTypeDescriptor.isBrandNewMethod(method)) { // Reloading has occurred and method has been added (it wasn't in the original) definetly need to use the dispatcher dispatchThroughDescriptor = true; } else if (IncrementalTypeDescriptor.hasChanged(method)) { // Reloading has occurred and the method has changed in some way // Method has been deleted - let the catcher/new generated dispatcher deal with it if (!IncrementalTypeDescriptor.isCatcher(method)) { if (!IncrementalTypeDescriptor.wasDeleted(method)) { // Don't want to call the one that was there! dispatchThroughDescriptor = true; } // } else if (IncrementalTypeDescriptor.wasDeleted(method)) { // // The method is a catcher because it used to be there, it no longer is // dispatchThroughDescriptor = true; } } if (dispatchThroughDescriptor) { if (GlobalConfiguration.isRuntimeLogging && log.isLoggable(Level.FINER)) { log.info("versionstamp " + reloadableType.getLiveVersion().versionstamp); log.exiting("TypeRegistry", "ivicheck", true); } return true; } } // if (GlobalConfiguration.isRuntimeLogging && log.isLoggable(Level.FINER)) { // log.exiting("TypeRegistry", "ivicheck", true); // } return false; }
java
@UsedByGeneratedCode public static boolean ivicheck(int ids, String nameAndDescriptor) { // Check 1: FAST: Has anything at all been reloaded? if (nothingReloaded) { return false; } // if (GlobalConfiguration.isRuntimeLogging && log.isLoggable(Level.FINER)) { // log.entering("TypeRegistry", "ivicheck", new Object[] { ids, nameAndDescriptor }); // } // TODO [perf] global check (anything been reloaded?) // TODO [perf] local check (type or anything in its hierarchy reloaded) int registryId = ids >>> 16; int typeId = ids & 0xffff; TypeRegistry typeRegistry = registryInstances[registryId].get(); ReloadableType reloadableType = typeRegistry.getReloadableType(typeId); // Ok, think about what null means here. It means this registry has not loaded this type as a reloadable type. That doesn't // mean it isn't reloadable as a parent loaded may have found it. We have 3 options: // 1. assume names are unique - we can look up this type and find the registry in question // 2. assume delegating classloaders and search the parent registry for it // 3. pass something in at the call site (the class obejct), this would give us the classloader and thus the registry // 3 is ideal, but slower. 2 is nice but not always safe. 1 will work in a lot of situations. // let's try with a (2) strategy, fallback on a (1) - when we revisit this we can end up doing (3) maybe... // TODO [grails] We need a sentinel to indicate that we've had a look, so that we dont go off searching every time, but for now, lets // just do the search: if (reloadableType == null) { reloadableType = searchForReloadableType(typeId, typeRegistry); } // Check 2: Info computed earlier if (reloadableType != null && !reloadableType.isAffectedByReload()) { return false; } if (reloadableType != null && reloadableType.hasBeenReloaded()) { MethodMember method = reloadableType.getLiveVersion().incrementalTypeDescriptor.getFromLatestByDescriptor( nameAndDescriptor); boolean dispatchThroughDescriptor = false; if (method == null) { if (!reloadableType.getTypeDescriptor().isFinalInHierarchy(nameAndDescriptor)) { // Reloading has occurred and method does not exist in new version, throw NSME throw new NoSuchMethodError(reloadableType.getBaseName() + "." + nameAndDescriptor); } } else if (IncrementalTypeDescriptor.isBrandNewMethod(method)) { // Reloading has occurred and method has been added (it wasn't in the original) definetly need to use the dispatcher dispatchThroughDescriptor = true; } else if (IncrementalTypeDescriptor.hasChanged(method)) { // Reloading has occurred and the method has changed in some way // Method has been deleted - let the catcher/new generated dispatcher deal with it if (!IncrementalTypeDescriptor.isCatcher(method)) { if (!IncrementalTypeDescriptor.wasDeleted(method)) { // Don't want to call the one that was there! dispatchThroughDescriptor = true; } // } else if (IncrementalTypeDescriptor.wasDeleted(method)) { // // The method is a catcher because it used to be there, it no longer is // dispatchThroughDescriptor = true; } } if (dispatchThroughDescriptor) { if (GlobalConfiguration.isRuntimeLogging && log.isLoggable(Level.FINER)) { log.info("versionstamp " + reloadableType.getLiveVersion().versionstamp); log.exiting("TypeRegistry", "ivicheck", true); } return true; } } // if (GlobalConfiguration.isRuntimeLogging && log.isLoggable(Level.FINER)) { // log.exiting("TypeRegistry", "ivicheck", true); // } return false; }
[ "@", "UsedByGeneratedCode", "public", "static", "boolean", "ivicheck", "(", "int", "ids", ",", "String", "nameAndDescriptor", ")", "{", "// Check 1: FAST: Has anything at all been reloaded?", "if", "(", "nothingReloaded", ")", "{", "return", "false", ";", "}", "//\t\tif (GlobalConfiguration.isRuntimeLogging && log.isLoggable(Level.FINER)) {", "//\t\t\tlog.entering(\"TypeRegistry\", \"ivicheck\", new Object[] { ids, nameAndDescriptor });", "//\t\t}", "// TODO [perf] global check (anything been reloaded?)", "// TODO [perf] local check (type or anything in its hierarchy reloaded)", "int", "registryId", "=", "ids", ">>>", "16", ";", "int", "typeId", "=", "ids", "&", "0xffff", ";", "TypeRegistry", "typeRegistry", "=", "registryInstances", "[", "registryId", "]", ".", "get", "(", ")", ";", "ReloadableType", "reloadableType", "=", "typeRegistry", ".", "getReloadableType", "(", "typeId", ")", ";", "// Ok, think about what null means here. It means this registry has not loaded this type as a reloadable type. That doesn't", "// mean it isn't reloadable as a parent loaded may have found it. We have 3 options:", "// 1. assume names are unique - we can look up this type and find the registry in question", "// 2. assume delegating classloaders and search the parent registry for it", "// 3. pass something in at the call site (the class obejct), this would give us the classloader and thus the registry", "// 3 is ideal, but slower. 2 is nice but not always safe. 1 will work in a lot of situations.", "// let's try with a (2) strategy, fallback on a (1) - when we revisit this we can end up doing (3) maybe...", "// TODO [grails] We need a sentinel to indicate that we've had a look, so that we dont go off searching every time, but for now, lets", "// just do the search:", "if", "(", "reloadableType", "==", "null", ")", "{", "reloadableType", "=", "searchForReloadableType", "(", "typeId", ",", "typeRegistry", ")", ";", "}", "// Check 2: Info computed earlier", "if", "(", "reloadableType", "!=", "null", "&&", "!", "reloadableType", ".", "isAffectedByReload", "(", ")", ")", "{", "return", "false", ";", "}", "if", "(", "reloadableType", "!=", "null", "&&", "reloadableType", ".", "hasBeenReloaded", "(", ")", ")", "{", "MethodMember", "method", "=", "reloadableType", ".", "getLiveVersion", "(", ")", ".", "incrementalTypeDescriptor", ".", "getFromLatestByDescriptor", "(", "nameAndDescriptor", ")", ";", "boolean", "dispatchThroughDescriptor", "=", "false", ";", "if", "(", "method", "==", "null", ")", "{", "if", "(", "!", "reloadableType", ".", "getTypeDescriptor", "(", ")", ".", "isFinalInHierarchy", "(", "nameAndDescriptor", ")", ")", "{", "// Reloading has occurred and method does not exist in new version, throw NSME", "throw", "new", "NoSuchMethodError", "(", "reloadableType", ".", "getBaseName", "(", ")", "+", "\".\"", "+", "nameAndDescriptor", ")", ";", "}", "}", "else", "if", "(", "IncrementalTypeDescriptor", ".", "isBrandNewMethod", "(", "method", ")", ")", "{", "// Reloading has occurred and method has been added (it wasn't in the original) definetly need to use the dispatcher", "dispatchThroughDescriptor", "=", "true", ";", "}", "else", "if", "(", "IncrementalTypeDescriptor", ".", "hasChanged", "(", "method", ")", ")", "{", "// Reloading has occurred and the method has changed in some way", "// Method has been deleted - let the catcher/new generated dispatcher deal with it", "if", "(", "!", "IncrementalTypeDescriptor", ".", "isCatcher", "(", "method", ")", ")", "{", "if", "(", "!", "IncrementalTypeDescriptor", ".", "wasDeleted", "(", "method", ")", ")", "{", "// Don't want to call the one that was there!", "dispatchThroughDescriptor", "=", "true", ";", "}", "//\t\t\t\t} else if (IncrementalTypeDescriptor.wasDeleted(method)) {", "//\t\t\t\t\t// The method is a catcher because it used to be there, it no longer is", "//\t\t\t\t\tdispatchThroughDescriptor = true;", "}", "}", "if", "(", "dispatchThroughDescriptor", ")", "{", "if", "(", "GlobalConfiguration", ".", "isRuntimeLogging", "&&", "log", ".", "isLoggable", "(", "Level", ".", "FINER", ")", ")", "{", "log", ".", "info", "(", "\"versionstamp \"", "+", "reloadableType", ".", "getLiveVersion", "(", ")", ".", "versionstamp", ")", ";", "log", ".", "exiting", "(", "\"TypeRegistry\"", ",", "\"ivicheck\"", ",", "true", ")", ";", "}", "return", "true", ";", "}", "}", "//\t\tif (GlobalConfiguration.isRuntimeLogging && log.isLoggable(Level.FINER)) {", "//\t\t\tlog.exiting(\"TypeRegistry\", \"ivicheck\", true);", "//\t\t}", "return", "false", ";", "}" ]
Used in code the generated code replaces invokevirtual calls. Determine if the code can run as it was originally compiled. This method will return FALSE if nothing has changed to interfere with the invocation and it should proceed. This method will return TRUE if something has changed and the caller needs to do something different. @param ids packed representation of the registryId (top 16bits) and typeId (bottom 16bits) @param nameAndDescriptor the name and descriptor of the method about to be INVOKEVIRTUAL'd @return true if the original method operation must be intercepted
[ "Used", "in", "code", "the", "generated", "code", "replaces", "invokevirtual", "calls", ".", "Determine", "if", "the", "code", "can", "run", "as", "it", "was", "originally", "compiled", "." ]
59b32f957a05c6d9f149148158053605e2a6205a
https://github.com/spring-projects/spring-loaded/blob/59b32f957a05c6d9f149148158053605e2a6205a/springloaded/src/main/java/org/springsource/loaded/TypeRegistry.java#L1815-L1893
26,410
spring-projects/spring-loaded
springloaded/src/main/java/org/springsource/loaded/TypeRegistry.java
TypeRegistry.getReloadableType
@UsedByGeneratedCode public static ReloadableType getReloadableType(int typeRegistryId, int typeId) { if (GlobalConfiguration.verboseMode && log.isLoggable(Level.INFO)) { log.info( ">TypeRegistry.getReloadableType(typeRegistryId=" + typeRegistryId + ",typeId=" + typeId + ")"); } TypeRegistry typeRegistry = registryInstances[typeRegistryId].get(); if (typeRegistry == null) { throw new IllegalStateException("Request to access registry id " + typeRegistryId + " but no registry with that id has been created"); } ReloadableType reloadableType = typeRegistry.getReloadableType(typeId); if (reloadableType == null) { throw new IllegalStateException("The type registry " + typeRegistry + " does not know about type id " + typeId); } reloadableType.setResolved(); if (GlobalConfiguration.verboseMode && log.isLoggable(Level.INFO)) { log.info("<TypeRegistry.getReloadableType(typeRegistryId=" + typeRegistryId + ",typeId=" + typeId + ") returning " + reloadableType); } reloadableType.createTypeAssociations(); return reloadableType; }
java
@UsedByGeneratedCode public static ReloadableType getReloadableType(int typeRegistryId, int typeId) { if (GlobalConfiguration.verboseMode && log.isLoggable(Level.INFO)) { log.info( ">TypeRegistry.getReloadableType(typeRegistryId=" + typeRegistryId + ",typeId=" + typeId + ")"); } TypeRegistry typeRegistry = registryInstances[typeRegistryId].get(); if (typeRegistry == null) { throw new IllegalStateException("Request to access registry id " + typeRegistryId + " but no registry with that id has been created"); } ReloadableType reloadableType = typeRegistry.getReloadableType(typeId); if (reloadableType == null) { throw new IllegalStateException("The type registry " + typeRegistry + " does not know about type id " + typeId); } reloadableType.setResolved(); if (GlobalConfiguration.verboseMode && log.isLoggable(Level.INFO)) { log.info("<TypeRegistry.getReloadableType(typeRegistryId=" + typeRegistryId + ",typeId=" + typeId + ") returning " + reloadableType); } reloadableType.createTypeAssociations(); return reloadableType; }
[ "@", "UsedByGeneratedCode", "public", "static", "ReloadableType", "getReloadableType", "(", "int", "typeRegistryId", ",", "int", "typeId", ")", "{", "if", "(", "GlobalConfiguration", ".", "verboseMode", "&&", "log", ".", "isLoggable", "(", "Level", ".", "INFO", ")", ")", "{", "log", ".", "info", "(", "\">TypeRegistry.getReloadableType(typeRegistryId=\"", "+", "typeRegistryId", "+", "\",typeId=\"", "+", "typeId", "+", "\")\"", ")", ";", "}", "TypeRegistry", "typeRegistry", "=", "registryInstances", "[", "typeRegistryId", "]", ".", "get", "(", ")", ";", "if", "(", "typeRegistry", "==", "null", ")", "{", "throw", "new", "IllegalStateException", "(", "\"Request to access registry id \"", "+", "typeRegistryId", "+", "\" but no registry with that id has been created\"", ")", ";", "}", "ReloadableType", "reloadableType", "=", "typeRegistry", ".", "getReloadableType", "(", "typeId", ")", ";", "if", "(", "reloadableType", "==", "null", ")", "{", "throw", "new", "IllegalStateException", "(", "\"The type registry \"", "+", "typeRegistry", "+", "\" does not know about type id \"", "+", "typeId", ")", ";", "}", "reloadableType", ".", "setResolved", "(", ")", ";", "if", "(", "GlobalConfiguration", ".", "verboseMode", "&&", "log", ".", "isLoggable", "(", "Level", ".", "INFO", ")", ")", "{", "log", ".", "info", "(", "\"<TypeRegistry.getReloadableType(typeRegistryId=\"", "+", "typeRegistryId", "+", "\",typeId=\"", "+", "typeId", "+", "\") returning \"", "+", "reloadableType", ")", ";", "}", "reloadableType", ".", "createTypeAssociations", "(", ")", ";", "return", "reloadableType", ";", "}" ]
This method discovers the reloadable type instance for the registry and type id specified. @param typeRegistryId the type registry id @param typeId the type id @return the ReloadableType (if there is no ReloadableType an exception will be thrown)
[ "This", "method", "discovers", "the", "reloadable", "type", "instance", "for", "the", "registry", "and", "type", "id", "specified", "." ]
59b32f957a05c6d9f149148158053605e2a6205a
https://github.com/spring-projects/spring-loaded/blob/59b32f957a05c6d9f149148158053605e2a6205a/springloaded/src/main/java/org/springsource/loaded/TypeRegistry.java#L1906-L1929
26,411
spring-projects/spring-loaded
springloaded/src/main/java/org/springsource/loaded/TypeRegistry.java
TypeRegistry.getPatternsFrom
private List<TypePattern> getPatternsFrom(String value) { if (value == null) { return Collections.emptyList(); } List<TypePattern> typePatterns = new ArrayList<TypePattern>(); StringTokenizer st = new StringTokenizer(value, ","); while (st.hasMoreElements()) { String typepattern = st.nextToken(); TypePattern typePattern = null; if (typepattern.endsWith("..*")) { typePattern = new PrefixTypePattern(typepattern); if (GlobalConfiguration.isRuntimeLogging && log.isLoggable(Level.INFO)) { log.info("registered package prefix '" + typepattern + "'"); } } else if (typepattern.equals("*")) { typePattern = new AnyTypePattern(); } else { typePattern = new ExactTypePattern(typepattern); } typePatterns.add(typePattern); } return typePatterns; }
java
private List<TypePattern> getPatternsFrom(String value) { if (value == null) { return Collections.emptyList(); } List<TypePattern> typePatterns = new ArrayList<TypePattern>(); StringTokenizer st = new StringTokenizer(value, ","); while (st.hasMoreElements()) { String typepattern = st.nextToken(); TypePattern typePattern = null; if (typepattern.endsWith("..*")) { typePattern = new PrefixTypePattern(typepattern); if (GlobalConfiguration.isRuntimeLogging && log.isLoggable(Level.INFO)) { log.info("registered package prefix '" + typepattern + "'"); } } else if (typepattern.equals("*")) { typePattern = new AnyTypePattern(); } else { typePattern = new ExactTypePattern(typepattern); } typePatterns.add(typePattern); } return typePatterns; }
[ "private", "List", "<", "TypePattern", ">", "getPatternsFrom", "(", "String", "value", ")", "{", "if", "(", "value", "==", "null", ")", "{", "return", "Collections", ".", "emptyList", "(", ")", ";", "}", "List", "<", "TypePattern", ">", "typePatterns", "=", "new", "ArrayList", "<", "TypePattern", ">", "(", ")", ";", "StringTokenizer", "st", "=", "new", "StringTokenizer", "(", "value", ",", "\",\"", ")", ";", "while", "(", "st", ".", "hasMoreElements", "(", ")", ")", "{", "String", "typepattern", "=", "st", ".", "nextToken", "(", ")", ";", "TypePattern", "typePattern", "=", "null", ";", "if", "(", "typepattern", ".", "endsWith", "(", "\"..*\"", ")", ")", "{", "typePattern", "=", "new", "PrefixTypePattern", "(", "typepattern", ")", ";", "if", "(", "GlobalConfiguration", ".", "isRuntimeLogging", "&&", "log", ".", "isLoggable", "(", "Level", ".", "INFO", ")", ")", "{", "log", ".", "info", "(", "\"registered package prefix '\"", "+", "typepattern", "+", "\"'\"", ")", ";", "}", "}", "else", "if", "(", "typepattern", ".", "equals", "(", "\"*\"", ")", ")", "{", "typePattern", "=", "new", "AnyTypePattern", "(", ")", ";", "}", "else", "{", "typePattern", "=", "new", "ExactTypePattern", "(", "typepattern", ")", ";", "}", "typePatterns", ".", "add", "(", "typePattern", ")", ";", "}", "return", "typePatterns", ";", "}" ]
Process some type pattern objects from the supplied value. For example the value might be 'com.foo.Bar,!com.foo.Goo' @param value string defining a comma separated list of type patterns @return list of TypePatterns
[ "Process", "some", "type", "pattern", "objects", "from", "the", "supplied", "value", ".", "For", "example", "the", "value", "might", "be", "com", ".", "foo", ".", "Bar", "!com", ".", "foo", ".", "Goo" ]
59b32f957a05c6d9f149148158053605e2a6205a
https://github.com/spring-projects/spring-loaded/blob/59b32f957a05c6d9f149148158053605e2a6205a/springloaded/src/main/java/org/springsource/loaded/TypeRegistry.java#L2070-L2094
26,412
spring-projects/spring-loaded
springloaded/src/main/java/org/springsource/loaded/TypeRegistry.java
TypeRegistry.recordBootstrapMethod
public synchronized int recordBootstrapMethod(String slashedClassName, Handle bsm, Object[] bsmArgs) { if (bsmmap == null) { bsmmap = new HashMap<String, BsmInfo[]>(); } BsmInfo[] bsminfo = bsmmap.get(slashedClassName); if (bsminfo == null) { bsminfo = new BsmInfo[1]; // TODO do we need BsmInfo or can we just use Handle directly? bsminfo[0] = new BsmInfo(bsm, bsmArgs); bsmmap.put(slashedClassName, bsminfo); return 0; } else { int len = bsminfo.length; BsmInfo[] newarray = new BsmInfo[len + 1]; System.arraycopy(bsminfo, 0, newarray, 0, len); bsminfo = newarray; bsmmap.put(slashedClassName, bsminfo); bsminfo[len] = new BsmInfo(bsm, bsmArgs); return len; } // TODO [memory] search the existing bsmInfos for a matching one! Reuse! }
java
public synchronized int recordBootstrapMethod(String slashedClassName, Handle bsm, Object[] bsmArgs) { if (bsmmap == null) { bsmmap = new HashMap<String, BsmInfo[]>(); } BsmInfo[] bsminfo = bsmmap.get(slashedClassName); if (bsminfo == null) { bsminfo = new BsmInfo[1]; // TODO do we need BsmInfo or can we just use Handle directly? bsminfo[0] = new BsmInfo(bsm, bsmArgs); bsmmap.put(slashedClassName, bsminfo); return 0; } else { int len = bsminfo.length; BsmInfo[] newarray = new BsmInfo[len + 1]; System.arraycopy(bsminfo, 0, newarray, 0, len); bsminfo = newarray; bsmmap.put(slashedClassName, bsminfo); bsminfo[len] = new BsmInfo(bsm, bsmArgs); return len; } // TODO [memory] search the existing bsmInfos for a matching one! Reuse! }
[ "public", "synchronized", "int", "recordBootstrapMethod", "(", "String", "slashedClassName", ",", "Handle", "bsm", ",", "Object", "[", "]", "bsmArgs", ")", "{", "if", "(", "bsmmap", "==", "null", ")", "{", "bsmmap", "=", "new", "HashMap", "<", "String", ",", "BsmInfo", "[", "]", ">", "(", ")", ";", "}", "BsmInfo", "[", "]", "bsminfo", "=", "bsmmap", ".", "get", "(", "slashedClassName", ")", ";", "if", "(", "bsminfo", "==", "null", ")", "{", "bsminfo", "=", "new", "BsmInfo", "[", "1", "]", ";", "// TODO do we need BsmInfo or can we just use Handle directly?", "bsminfo", "[", "0", "]", "=", "new", "BsmInfo", "(", "bsm", ",", "bsmArgs", ")", ";", "bsmmap", ".", "put", "(", "slashedClassName", ",", "bsminfo", ")", ";", "return", "0", ";", "}", "else", "{", "int", "len", "=", "bsminfo", ".", "length", ";", "BsmInfo", "[", "]", "newarray", "=", "new", "BsmInfo", "[", "len", "+", "1", "]", ";", "System", ".", "arraycopy", "(", "bsminfo", ",", "0", ",", "newarray", ",", "0", ",", "len", ")", ";", "bsminfo", "=", "newarray", ";", "bsmmap", ".", "put", "(", "slashedClassName", ",", "bsminfo", ")", ";", "bsminfo", "[", "len", "]", "=", "new", "BsmInfo", "(", "bsm", ",", "bsmArgs", ")", ";", "return", "len", ";", "}", "// TODO [memory] search the existing bsmInfos for a matching one! Reuse!", "}" ]
When an invokedynamic instruction is reached, we allocate an id that recognizes that bsm and the parameters to that bsm. The index can be used when rewriting that invokedynamic @param slashedClassName the slashed class name containing the bootstrap method @param bsm the bootstrap methods @param bsmArgs the bootstrap method arguments (asm types) @return id that represents this bootstrap method usage
[ "When", "an", "invokedynamic", "instruction", "is", "reached", "we", "allocate", "an", "id", "that", "recognizes", "that", "bsm", "and", "the", "parameters", "to", "that", "bsm", ".", "The", "index", "can", "be", "used", "when", "rewriting", "that", "invokedynamic" ]
59b32f957a05c6d9f149148158053605e2a6205a
https://github.com/spring-projects/spring-loaded/blob/59b32f957a05c6d9f149148158053605e2a6205a/springloaded/src/main/java/org/springsource/loaded/TypeRegistry.java#L2257-L2279
26,413
spring-projects/spring-loaded
springloaded/src/main/java/org/springsource/loaded/TypeRegistry.java
TypeRegistry.associateReloadableType
@UsedByGeneratedCode public static void associateReloadableType(ReloadableType child, Class<?> parent) { // TODO performance - can we make this cheaper? ClassLoader parentClassLoader = parent.getClassLoader(); if (parentClassLoader == null) { return; } TypeRegistry parentTypeRegistry = TypeRegistry.getTypeRegistryFor(parent.getClassLoader()); ReloadableType parentReloadableType = parentTypeRegistry.getReloadableType(parent); if (parentReloadableType != null) { parentReloadableType.recordSubtype(child); } }
java
@UsedByGeneratedCode public static void associateReloadableType(ReloadableType child, Class<?> parent) { // TODO performance - can we make this cheaper? ClassLoader parentClassLoader = parent.getClassLoader(); if (parentClassLoader == null) { return; } TypeRegistry parentTypeRegistry = TypeRegistry.getTypeRegistryFor(parent.getClassLoader()); ReloadableType parentReloadableType = parentTypeRegistry.getReloadableType(parent); if (parentReloadableType != null) { parentReloadableType.recordSubtype(child); } }
[ "@", "UsedByGeneratedCode", "public", "static", "void", "associateReloadableType", "(", "ReloadableType", "child", ",", "Class", "<", "?", ">", "parent", ")", "{", "// TODO performance - can we make this cheaper?", "ClassLoader", "parentClassLoader", "=", "parent", ".", "getClassLoader", "(", ")", ";", "if", "(", "parentClassLoader", "==", "null", ")", "{", "return", ";", "}", "TypeRegistry", "parentTypeRegistry", "=", "TypeRegistry", ".", "getTypeRegistryFor", "(", "parent", ".", "getClassLoader", "(", ")", ")", ";", "ReloadableType", "parentReloadableType", "=", "parentTypeRegistry", ".", "getReloadableType", "(", "parent", ")", ";", "if", "(", "parentReloadableType", "!=", "null", ")", "{", "parentReloadableType", ".", "recordSubtype", "(", "child", ")", ";", "}", "}" ]
Called from the static initializer of a reloadabletype, allowing it to connect itself to the parent type, such that when reloading occurs we can mark all relevant types in the hierarchy as being impacted by the reload. @param child the ReloadableType actively being initialized @param parent the superclass of the reloadable type (may or may not be reloadable!)
[ "Called", "from", "the", "static", "initializer", "of", "a", "reloadabletype", "allowing", "it", "to", "connect", "itself", "to", "the", "parent", "type", "such", "that", "when", "reloading", "occurs", "we", "can", "mark", "all", "relevant", "types", "in", "the", "hierarchy", "as", "being", "impacted", "by", "the", "reload", "." ]
59b32f957a05c6d9f149148158053605e2a6205a
https://github.com/spring-projects/spring-loaded/blob/59b32f957a05c6d9f149148158053605e2a6205a/springloaded/src/main/java/org/springsource/loaded/TypeRegistry.java#L2302-L2314
26,414
spring-projects/spring-loaded
springloaded/src/main/java/org/springsource/loaded/agent/SpringPlugin.java
SpringPlugin.clearLocalVariableTableParameterNameDiscovererCache
private void clearLocalVariableTableParameterNameDiscovererCache(Class<?> clazz) { if (localVariableTableParameterNameDiscovererInstances == null) { return; } if (debug) { System.out.println("SPRING_PLUGIN: ParameterNamesCache: Clearing parameter name discoverer caches"); } if (parameterNamesCacheField == null) { try { parameterNamesCacheField = localVariableTableParameterNameDiscovererInstances.get( 0).getClass().getDeclaredField("parameterNamesCache"); } catch (NoSuchFieldException nsfe) { log.log(Level.SEVERE, "Unexpectedly cannot find parameterNamesCache field on LocalVariableTableParameterNameDiscoverer class"); } } for (Object instance : localVariableTableParameterNameDiscovererInstances) { try { parameterNamesCacheField.setAccessible(true); Map<?, ?> parameterNamesCache = (Map<?, ?>) parameterNamesCacheField.get(instance); Object o = parameterNamesCache.remove(clazz); if (debug) { System.out.println( "SPRING_PLUGIN: ParameterNamesCache: Removed " + clazz.getName() + " from cache?" + (o != null)); } } catch (IllegalAccessException e) { log.log(Level.SEVERE, "Unexpected IllegalAccessException trying to access parameterNamesCache field on LocalVariableTableParameterNameDiscoverer class"); } catch (IllegalArgumentException iae) { log.log(Level.SEVERE, "Unexpected IllegalArgumentException trying to access parameterNamesCache field on LocalVariableTableParameterNameDiscoverer class"); } } }
java
private void clearLocalVariableTableParameterNameDiscovererCache(Class<?> clazz) { if (localVariableTableParameterNameDiscovererInstances == null) { return; } if (debug) { System.out.println("SPRING_PLUGIN: ParameterNamesCache: Clearing parameter name discoverer caches"); } if (parameterNamesCacheField == null) { try { parameterNamesCacheField = localVariableTableParameterNameDiscovererInstances.get( 0).getClass().getDeclaredField("parameterNamesCache"); } catch (NoSuchFieldException nsfe) { log.log(Level.SEVERE, "Unexpectedly cannot find parameterNamesCache field on LocalVariableTableParameterNameDiscoverer class"); } } for (Object instance : localVariableTableParameterNameDiscovererInstances) { try { parameterNamesCacheField.setAccessible(true); Map<?, ?> parameterNamesCache = (Map<?, ?>) parameterNamesCacheField.get(instance); Object o = parameterNamesCache.remove(clazz); if (debug) { System.out.println( "SPRING_PLUGIN: ParameterNamesCache: Removed " + clazz.getName() + " from cache?" + (o != null)); } } catch (IllegalAccessException e) { log.log(Level.SEVERE, "Unexpected IllegalAccessException trying to access parameterNamesCache field on LocalVariableTableParameterNameDiscoverer class"); } catch (IllegalArgumentException iae) { log.log(Level.SEVERE, "Unexpected IllegalArgumentException trying to access parameterNamesCache field on LocalVariableTableParameterNameDiscoverer class"); } } }
[ "private", "void", "clearLocalVariableTableParameterNameDiscovererCache", "(", "Class", "<", "?", ">", "clazz", ")", "{", "if", "(", "localVariableTableParameterNameDiscovererInstances", "==", "null", ")", "{", "return", ";", "}", "if", "(", "debug", ")", "{", "System", ".", "out", ".", "println", "(", "\"SPRING_PLUGIN: ParameterNamesCache: Clearing parameter name discoverer caches\"", ")", ";", "}", "if", "(", "parameterNamesCacheField", "==", "null", ")", "{", "try", "{", "parameterNamesCacheField", "=", "localVariableTableParameterNameDiscovererInstances", ".", "get", "(", "0", ")", ".", "getClass", "(", ")", ".", "getDeclaredField", "(", "\"parameterNamesCache\"", ")", ";", "}", "catch", "(", "NoSuchFieldException", "nsfe", ")", "{", "log", ".", "log", "(", "Level", ".", "SEVERE", ",", "\"Unexpectedly cannot find parameterNamesCache field on LocalVariableTableParameterNameDiscoverer class\"", ")", ";", "}", "}", "for", "(", "Object", "instance", ":", "localVariableTableParameterNameDiscovererInstances", ")", "{", "try", "{", "parameterNamesCacheField", ".", "setAccessible", "(", "true", ")", ";", "Map", "<", "?", ",", "?", ">", "parameterNamesCache", "=", "(", "Map", "<", "?", ",", "?", ">", ")", "parameterNamesCacheField", ".", "get", "(", "instance", ")", ";", "Object", "o", "=", "parameterNamesCache", ".", "remove", "(", "clazz", ")", ";", "if", "(", "debug", ")", "{", "System", ".", "out", ".", "println", "(", "\"SPRING_PLUGIN: ParameterNamesCache: Removed \"", "+", "clazz", ".", "getName", "(", ")", "+", "\" from cache?\"", "+", "(", "o", "!=", "null", ")", ")", ";", "}", "}", "catch", "(", "IllegalAccessException", "e", ")", "{", "log", ".", "log", "(", "Level", ".", "SEVERE", ",", "\"Unexpected IllegalAccessException trying to access parameterNamesCache field on LocalVariableTableParameterNameDiscoverer class\"", ")", ";", "}", "catch", "(", "IllegalArgumentException", "iae", ")", "{", "log", ".", "log", "(", "Level", ".", "SEVERE", ",", "\"Unexpected IllegalArgumentException trying to access parameterNamesCache field on LocalVariableTableParameterNameDiscoverer class\"", ")", ";", "}", "}", "}" ]
The Spring class LocalVariableTableParameterNameDiscoverer holds a cache of parameter names discovered for members within classes and needs clearing if the class changes. @param clazz the class being reloaded, which may exist in a parameter name discoverer cache
[ "The", "Spring", "class", "LocalVariableTableParameterNameDiscoverer", "holds", "a", "cache", "of", "parameter", "names", "discovered", "for", "members", "within", "classes", "and", "needs", "clearing", "if", "the", "class", "changes", "." ]
59b32f957a05c6d9f149148158053605e2a6205a
https://github.com/spring-projects/spring-loaded/blob/59b32f957a05c6d9f149148158053605e2a6205a/springloaded/src/main/java/org/springsource/loaded/agent/SpringPlugin.java#L189-L226
26,415
spring-projects/spring-loaded
springloaded/src/main/java/org/springsource/loaded/agent/SpringPlugin.java
SpringPlugin.clearMappingRegistry
private void clearMappingRegistry(Object o, Class<?> clazz_AbstractHandlerMethodMapping) { if (debug) { System.out.println("SPRING_PLUGIN: clearing out mapping registry..."); } Object mappingRegistryInstance = null; try { Field field_mappingRegistry = clazz_AbstractHandlerMethodMapping.getDeclaredField("mappingRegistry"); field_mappingRegistry.setAccessible(true); mappingRegistryInstance = field_mappingRegistry.get(o); } catch (NoSuchFieldException e) { if (debug) { System.out.println( "SPRING_PLUGIN: Unable to get mappingRegistry field on AbstractHandlerMethodMapping"); } } catch (IllegalAccessException e) { if (GlobalConfiguration.debugplugins || debug) { System.out.println( "SPRING_PLUGIN: Problem accessing mappingRegistry field on AbstractHandlerMethodMapping: "); e.printStackTrace(System.out); } } if (mappingRegistryInstance == null) { return; } Class mappingRegistryClass = mappingRegistryInstance.getClass(); clearMapField(mappingRegistryClass, mappingRegistryInstance, "registry"); clearMapField(mappingRegistryClass, mappingRegistryInstance, "mappingLookup"); clearMapField(mappingRegistryClass, mappingRegistryInstance, "urlLookup"); clearMapField(mappingRegistryClass, mappingRegistryInstance, "nameLookup"); clearMapField(mappingRegistryClass, mappingRegistryInstance, "corsLookup"); if (debug) { System.out.println("SPRING_PLUGIN: ... cleared out the mapping registry contents"); } }
java
private void clearMappingRegistry(Object o, Class<?> clazz_AbstractHandlerMethodMapping) { if (debug) { System.out.println("SPRING_PLUGIN: clearing out mapping registry..."); } Object mappingRegistryInstance = null; try { Field field_mappingRegistry = clazz_AbstractHandlerMethodMapping.getDeclaredField("mappingRegistry"); field_mappingRegistry.setAccessible(true); mappingRegistryInstance = field_mappingRegistry.get(o); } catch (NoSuchFieldException e) { if (debug) { System.out.println( "SPRING_PLUGIN: Unable to get mappingRegistry field on AbstractHandlerMethodMapping"); } } catch (IllegalAccessException e) { if (GlobalConfiguration.debugplugins || debug) { System.out.println( "SPRING_PLUGIN: Problem accessing mappingRegistry field on AbstractHandlerMethodMapping: "); e.printStackTrace(System.out); } } if (mappingRegistryInstance == null) { return; } Class mappingRegistryClass = mappingRegistryInstance.getClass(); clearMapField(mappingRegistryClass, mappingRegistryInstance, "registry"); clearMapField(mappingRegistryClass, mappingRegistryInstance, "mappingLookup"); clearMapField(mappingRegistryClass, mappingRegistryInstance, "urlLookup"); clearMapField(mappingRegistryClass, mappingRegistryInstance, "nameLookup"); clearMapField(mappingRegistryClass, mappingRegistryInstance, "corsLookup"); if (debug) { System.out.println("SPRING_PLUGIN: ... cleared out the mapping registry contents"); } }
[ "private", "void", "clearMappingRegistry", "(", "Object", "o", ",", "Class", "<", "?", ">", "clazz_AbstractHandlerMethodMapping", ")", "{", "if", "(", "debug", ")", "{", "System", ".", "out", ".", "println", "(", "\"SPRING_PLUGIN: clearing out mapping registry...\"", ")", ";", "}", "Object", "mappingRegistryInstance", "=", "null", ";", "try", "{", "Field", "field_mappingRegistry", "=", "clazz_AbstractHandlerMethodMapping", ".", "getDeclaredField", "(", "\"mappingRegistry\"", ")", ";", "field_mappingRegistry", ".", "setAccessible", "(", "true", ")", ";", "mappingRegistryInstance", "=", "field_mappingRegistry", ".", "get", "(", "o", ")", ";", "}", "catch", "(", "NoSuchFieldException", "e", ")", "{", "if", "(", "debug", ")", "{", "System", ".", "out", ".", "println", "(", "\"SPRING_PLUGIN: Unable to get mappingRegistry field on AbstractHandlerMethodMapping\"", ")", ";", "}", "}", "catch", "(", "IllegalAccessException", "e", ")", "{", "if", "(", "GlobalConfiguration", ".", "debugplugins", "||", "debug", ")", "{", "System", ".", "out", ".", "println", "(", "\"SPRING_PLUGIN: Problem accessing mappingRegistry field on AbstractHandlerMethodMapping: \"", ")", ";", "e", ".", "printStackTrace", "(", "System", ".", "out", ")", ";", "}", "}", "if", "(", "mappingRegistryInstance", "==", "null", ")", "{", "return", ";", "}", "Class", "mappingRegistryClass", "=", "mappingRegistryInstance", ".", "getClass", "(", ")", ";", "clearMapField", "(", "mappingRegistryClass", ",", "mappingRegistryInstance", ",", "\"registry\"", ")", ";", "clearMapField", "(", "mappingRegistryClass", ",", "mappingRegistryInstance", ",", "\"mappingLookup\"", ")", ";", "clearMapField", "(", "mappingRegistryClass", ",", "mappingRegistryInstance", ",", "\"urlLookup\"", ")", ";", "clearMapField", "(", "mappingRegistryClass", ",", "mappingRegistryInstance", ",", "\"nameLookup\"", ")", ";", "clearMapField", "(", "mappingRegistryClass", ",", "mappingRegistryInstance", ",", "\"corsLookup\"", ")", ";", "if", "(", "debug", ")", "{", "System", ".", "out", ".", "println", "(", "\"SPRING_PLUGIN: ... cleared out the mapping registry contents\"", ")", ";", "}", "}" ]
the initHandlerMethods below we will get an error about already existing mappings
[ "the", "initHandlerMethods", "below", "we", "will", "get", "an", "error", "about", "already", "existing", "mappings" ]
59b32f957a05c6d9f149148158053605e2a6205a
https://github.com/spring-projects/spring-loaded/blob/59b32f957a05c6d9f149148158053605e2a6205a/springloaded/src/main/java/org/springsource/loaded/agent/SpringPlugin.java#L447-L484
26,416
spring-projects/spring-loaded
springloaded/src/main/java/org/springsource/loaded/ri/ReflectiveInterceptor.java
ReflectiveInterceptor.asSetableField
private static Field asSetableField(Field field, Object target, Class<?> valueType, Object value, boolean makeAccessibleCopy) throws IllegalAccessException { // Must do the checks exactly in the same order as JVM if we want identical error messages. // JVM doesn't do this, since it cannot happen without reloading, we do it first of all. if (isDeleted(field)) { throw Exceptions.noSuchFieldError(field); } Class<?> clazz = field.getDeclaringClass(); int mods = field.getModifiers(); if (field.isAccessible() || Modifier.isPublic(mods & jlClassGetModifiers(clazz))) { //More expensive check not required / copy not required } else { //More expensive check required Class<?> callerClass = getCallerClass(); JVM.ensureMemberAccess(callerClass, clazz, target, mods); if (makeAccessibleCopy) { //TODO: This code is not covered by a test. It needs a non-reloadable type with non-public // field, being accessed reflectively from a context that is "priviliged" to access it without setting the access flag. field = JVM.copyField(field); // copy: we must not change accessible flag on original field! field.setAccessible(true); } } if (isPrimitive(valueType)) { //It seems for primitive types, the order of the checks (in Sun JVM) is different! typeCheckFieldSet(field, valueType, value); if (!field.isAccessible() && Modifier.isFinal(mods)) { throw Exceptions.illegalSetFinalFieldException(field, field.getType(), coerce(value, field.getType())); } } else { if (!field.isAccessible() && Modifier.isFinal(mods)) { throw Exceptions.illegalSetFinalFieldException(field, valueType, value); } typeCheckFieldSet(field, valueType, value); } return makeAccessibleCopy ? field : null; }
java
private static Field asSetableField(Field field, Object target, Class<?> valueType, Object value, boolean makeAccessibleCopy) throws IllegalAccessException { // Must do the checks exactly in the same order as JVM if we want identical error messages. // JVM doesn't do this, since it cannot happen without reloading, we do it first of all. if (isDeleted(field)) { throw Exceptions.noSuchFieldError(field); } Class<?> clazz = field.getDeclaringClass(); int mods = field.getModifiers(); if (field.isAccessible() || Modifier.isPublic(mods & jlClassGetModifiers(clazz))) { //More expensive check not required / copy not required } else { //More expensive check required Class<?> callerClass = getCallerClass(); JVM.ensureMemberAccess(callerClass, clazz, target, mods); if (makeAccessibleCopy) { //TODO: This code is not covered by a test. It needs a non-reloadable type with non-public // field, being accessed reflectively from a context that is "priviliged" to access it without setting the access flag. field = JVM.copyField(field); // copy: we must not change accessible flag on original field! field.setAccessible(true); } } if (isPrimitive(valueType)) { //It seems for primitive types, the order of the checks (in Sun JVM) is different! typeCheckFieldSet(field, valueType, value); if (!field.isAccessible() && Modifier.isFinal(mods)) { throw Exceptions.illegalSetFinalFieldException(field, field.getType(), coerce(value, field.getType())); } } else { if (!field.isAccessible() && Modifier.isFinal(mods)) { throw Exceptions.illegalSetFinalFieldException(field, valueType, value); } typeCheckFieldSet(field, valueType, value); } return makeAccessibleCopy ? field : null; }
[ "private", "static", "Field", "asSetableField", "(", "Field", "field", ",", "Object", "target", ",", "Class", "<", "?", ">", "valueType", ",", "Object", "value", ",", "boolean", "makeAccessibleCopy", ")", "throws", "IllegalAccessException", "{", "// Must do the checks exactly in the same order as JVM if we want identical error messages.", "// JVM doesn't do this, since it cannot happen without reloading, we do it first of all.", "if", "(", "isDeleted", "(", "field", ")", ")", "{", "throw", "Exceptions", ".", "noSuchFieldError", "(", "field", ")", ";", "}", "Class", "<", "?", ">", "clazz", "=", "field", ".", "getDeclaringClass", "(", ")", ";", "int", "mods", "=", "field", ".", "getModifiers", "(", ")", ";", "if", "(", "field", ".", "isAccessible", "(", ")", "||", "Modifier", ".", "isPublic", "(", "mods", "&", "jlClassGetModifiers", "(", "clazz", ")", ")", ")", "{", "//More expensive check not required / copy not required", "}", "else", "{", "//More expensive check required", "Class", "<", "?", ">", "callerClass", "=", "getCallerClass", "(", ")", ";", "JVM", ".", "ensureMemberAccess", "(", "callerClass", ",", "clazz", ",", "target", ",", "mods", ")", ";", "if", "(", "makeAccessibleCopy", ")", "{", "//TODO: This code is not covered by a test. It needs a non-reloadable type with non-public", "// field, being accessed reflectively from a context that is \"priviliged\" to access it without setting the access flag.", "field", "=", "JVM", ".", "copyField", "(", "field", ")", ";", "// copy: we must not change accessible flag on original field!", "field", ".", "setAccessible", "(", "true", ")", ";", "}", "}", "if", "(", "isPrimitive", "(", "valueType", ")", ")", "{", "//It seems for primitive types, the order of the checks (in Sun JVM) is different!", "typeCheckFieldSet", "(", "field", ",", "valueType", ",", "value", ")", ";", "if", "(", "!", "field", ".", "isAccessible", "(", ")", "&&", "Modifier", ".", "isFinal", "(", "mods", ")", ")", "{", "throw", "Exceptions", ".", "illegalSetFinalFieldException", "(", "field", ",", "field", ".", "getType", "(", ")", ",", "coerce", "(", "value", ",", "field", ".", "getType", "(", ")", ")", ")", ";", "}", "}", "else", "{", "if", "(", "!", "field", ".", "isAccessible", "(", ")", "&&", "Modifier", ".", "isFinal", "(", "mods", ")", ")", "{", "throw", "Exceptions", ".", "illegalSetFinalFieldException", "(", "field", ",", "valueType", ",", "value", ")", ";", "}", "typeCheckFieldSet", "(", "field", ",", "valueType", ",", "value", ")", ";", "}", "return", "makeAccessibleCopy", "?", "field", ":", "null", ";", "}" ]
Performs all necessary checks that need to be done before a field set should be allowed. @throws IllegalAccessException
[ "Performs", "all", "necessary", "checks", "that", "need", "to", "be", "done", "before", "a", "field", "set", "should", "be", "allowed", "." ]
59b32f957a05c6d9f149148158053605e2a6205a
https://github.com/spring-projects/spring-loaded/blob/59b32f957a05c6d9f149148158053605e2a6205a/springloaded/src/main/java/org/springsource/loaded/ri/ReflectiveInterceptor.java#L652-L693
26,417
spring-projects/spring-loaded
springloaded/src/main/java/org/springsource/loaded/ri/ReflectiveInterceptor.java
ReflectiveInterceptor.typeCheckFieldSet
private static void typeCheckFieldSet(Field field, Object value) throws IllegalAccessException { Class<?> fieldType = field.getType(); if (value == null) { if (fieldType.isPrimitive()) { throw Exceptions.illegalSetFieldTypeException(field, null, value); } } else { if (fieldType.isPrimitive()) { fieldType = boxTypeFor(fieldType); } Class<?> valueType = value.getClass(); if (!Utils.isConvertableFrom(fieldType, valueType)) { throw Exceptions.illegalSetFieldTypeException(field, valueType, value); } } }
java
private static void typeCheckFieldSet(Field field, Object value) throws IllegalAccessException { Class<?> fieldType = field.getType(); if (value == null) { if (fieldType.isPrimitive()) { throw Exceptions.illegalSetFieldTypeException(field, null, value); } } else { if (fieldType.isPrimitive()) { fieldType = boxTypeFor(fieldType); } Class<?> valueType = value.getClass(); if (!Utils.isConvertableFrom(fieldType, valueType)) { throw Exceptions.illegalSetFieldTypeException(field, valueType, value); } } }
[ "private", "static", "void", "typeCheckFieldSet", "(", "Field", "field", ",", "Object", "value", ")", "throws", "IllegalAccessException", "{", "Class", "<", "?", ">", "fieldType", "=", "field", ".", "getType", "(", ")", ";", "if", "(", "value", "==", "null", ")", "{", "if", "(", "fieldType", ".", "isPrimitive", "(", ")", ")", "{", "throw", "Exceptions", ".", "illegalSetFieldTypeException", "(", "field", ",", "null", ",", "value", ")", ";", "}", "}", "else", "{", "if", "(", "fieldType", ".", "isPrimitive", "(", ")", ")", "{", "fieldType", "=", "boxTypeFor", "(", "fieldType", ")", ";", "}", "Class", "<", "?", ">", "valueType", "=", "value", ".", "getClass", "(", ")", ";", "if", "(", "!", "Utils", ".", "isConvertableFrom", "(", "fieldType", ",", "valueType", ")", ")", "{", "throw", "Exceptions", ".", "illegalSetFieldTypeException", "(", "field", ",", "valueType", ",", "value", ")", ";", "}", "}", "}" ]
Perform a dynamic type check needed when setting a field value onto a field. Raises the appropriate exception when the check fails and returns normally otherwise. This method should only be called for object types. For primitive types call the three parameter variant instead. @throws IllegalAccessException
[ "Perform", "a", "dynamic", "type", "check", "needed", "when", "setting", "a", "field", "value", "onto", "a", "field", ".", "Raises", "the", "appropriate", "exception", "when", "the", "check", "fails", "and", "returns", "normally", "otherwise", ".", "This", "method", "should", "only", "be", "called", "for", "object", "types", ".", "For", "primitive", "types", "call", "the", "three", "parameter", "variant", "instead", "." ]
59b32f957a05c6d9f149148158053605e2a6205a
https://github.com/spring-projects/spring-loaded/blob/59b32f957a05c6d9f149148158053605e2a6205a/springloaded/src/main/java/org/springsource/loaded/ri/ReflectiveInterceptor.java#L762-L778
26,418
spring-projects/spring-loaded
springloaded/src/main/java/org/springsource/loaded/ri/ReflectiveInterceptor.java
ReflectiveInterceptor.typeCheckFieldSet
private static void typeCheckFieldSet(Field field, Class<?> valueType, Object value) throws IllegalAccessException { if (!isPrimitive(valueType)) { //Call the version of this method that considers autoboxing typeCheckFieldSet(field, value); } else { //Value type is primitive. // Note: In this case value was a primitive value that became boxed, so it can't be null. Class<?> fieldType = field.getType(); if (!Utils.isConvertableFrom(fieldType, valueType)) { throw Exceptions.illegalSetFieldTypeException(field, valueType, value); } } }
java
private static void typeCheckFieldSet(Field field, Class<?> valueType, Object value) throws IllegalAccessException { if (!isPrimitive(valueType)) { //Call the version of this method that considers autoboxing typeCheckFieldSet(field, value); } else { //Value type is primitive. // Note: In this case value was a primitive value that became boxed, so it can't be null. Class<?> fieldType = field.getType(); if (!Utils.isConvertableFrom(fieldType, valueType)) { throw Exceptions.illegalSetFieldTypeException(field, valueType, value); } } }
[ "private", "static", "void", "typeCheckFieldSet", "(", "Field", "field", ",", "Class", "<", "?", ">", "valueType", ",", "Object", "value", ")", "throws", "IllegalAccessException", "{", "if", "(", "!", "isPrimitive", "(", "valueType", ")", ")", "{", "//Call the version of this method that considers autoboxing", "typeCheckFieldSet", "(", "field", ",", "value", ")", ";", "}", "else", "{", "//Value type is primitive.", "// Note: In this case value was a primitive value that became boxed, so it can't be null.", "Class", "<", "?", ">", "fieldType", "=", "field", ".", "getType", "(", ")", ";", "if", "(", "!", "Utils", ".", "isConvertableFrom", "(", "fieldType", ",", "valueType", ")", ")", "{", "throw", "Exceptions", ".", "illegalSetFieldTypeException", "(", "field", ",", "valueType", ",", "value", ")", ";", "}", "}", "}" ]
Perform a dynamic type check needed when setting a field value onto a field. Raises the appropriate exception when the check fails and returns normally otherwise. @throws IllegalAccessException
[ "Perform", "a", "dynamic", "type", "check", "needed", "when", "setting", "a", "field", "value", "onto", "a", "field", ".", "Raises", "the", "appropriate", "exception", "when", "the", "check", "fails", "and", "returns", "normally", "otherwise", "." ]
59b32f957a05c6d9f149148158053605e2a6205a
https://github.com/spring-projects/spring-loaded/blob/59b32f957a05c6d9f149148158053605e2a6205a/springloaded/src/main/java/org/springsource/loaded/ri/ReflectiveInterceptor.java#L786-L799
26,419
spring-projects/spring-loaded
springloaded/src/main/java/org/springsource/loaded/ri/ReflectiveInterceptor.java
ReflectiveInterceptor.jlClassGetModifiers
public static int jlClassGetModifiers(Class<?> clazz) { // ReloadableType rtype = getReloadableTypeIfHasBeenReloaded(clazz); ReloadableType rtype = getRType(clazz); if (rtype == null) { return clazz.getModifiers(); } else { //Note: the "super bit" may be set in class modifiers but we should block it out, it //shouldn't be shown to users of the reflection API. return rtype.getLatestTypeDescriptor().getModifiers() & ~Opcodes.ACC_SUPER; } }
java
public static int jlClassGetModifiers(Class<?> clazz) { // ReloadableType rtype = getReloadableTypeIfHasBeenReloaded(clazz); ReloadableType rtype = getRType(clazz); if (rtype == null) { return clazz.getModifiers(); } else { //Note: the "super bit" may be set in class modifiers but we should block it out, it //shouldn't be shown to users of the reflection API. return rtype.getLatestTypeDescriptor().getModifiers() & ~Opcodes.ACC_SUPER; } }
[ "public", "static", "int", "jlClassGetModifiers", "(", "Class", "<", "?", ">", "clazz", ")", "{", "//\t\tReloadableType rtype = getReloadableTypeIfHasBeenReloaded(clazz);", "ReloadableType", "rtype", "=", "getRType", "(", "clazz", ")", ";", "if", "(", "rtype", "==", "null", ")", "{", "return", "clazz", ".", "getModifiers", "(", ")", ";", "}", "else", "{", "//Note: the \"super bit\" may be set in class modifiers but we should block it out, it", "//shouldn't be shown to users of the reflection API.", "return", "rtype", ".", "getLatestTypeDescriptor", "(", ")", ".", "getModifiers", "(", ")", "&", "~", "Opcodes", ".", "ACC_SUPER", ";", "}", "}" ]
Retrieve modifiers for a Java class, which might or might not be reloadable or reloaded. @param clazz the class for which to discover modifiers @return the modifiers
[ "Retrieve", "modifiers", "for", "a", "Java", "class", "which", "might", "or", "might", "not", "be", "reloadable", "or", "reloaded", "." ]
59b32f957a05c6d9f149148158053605e2a6205a
https://github.com/spring-projects/spring-loaded/blob/59b32f957a05c6d9f149148158053605e2a6205a/springloaded/src/main/java/org/springsource/loaded/ri/ReflectiveInterceptor.java#L832-L843
26,420
spring-projects/spring-loaded
springloaded/src/main/java/org/springsource/loaded/ri/ReflectiveInterceptor.java
ReflectiveInterceptor.getRType
public static ReloadableType getRType(Class<?> clazz) { // ReloadableType rtype = null; WeakReference<ReloadableType> ref = classToRType.get(clazz); ReloadableType rtype = null; if (ref != null) { rtype = ref.get(); } if (rtype == null) { if (!theOldWay) { // 'theOldWay' attempts to grab the field from the type via reflection. This usually works except // in cases where the class is not resolved yet since it can cause the class to resolve and its // static initializer to run. This was happening on a grails compile where the compiler is // loading dependencies (but not initializing them). Instead we can use this route of // discovering the type registry and locating the reloadable type. This does some map lookups // which may be a problem, but once discovered, it is cached in the weak ref so that shouldn't // be an ongoing perf problem. // TODO testcases for something that is reloaded without having been resolved ClassLoader cl = clazz.getClassLoader(); TypeRegistry tr = TypeRegistry.getTypeRegistryFor(cl); if (tr == null) { classToRType.put(clazz, ReloadableType.NOT_RELOADABLE_TYPE_REF); } else { rtype = tr.getReloadableType(clazz.getName().replace('.', '/')); if (rtype == null) { classToRType.put(clazz, ReloadableType.NOT_RELOADABLE_TYPE_REF); } else { classToRType.put(clazz, new WeakReference<ReloadableType>(rtype)); } } } else { // need to work it out Field rtypeField; try { // System.out.println("discovering field for " + clazz.getName()); // TODO cache somewhere - will need a clazz>Field cache rtypeField = clazz.getDeclaredField(Constants.fReloadableTypeFieldName); } catch (NoSuchFieldException nsfe) { classToRType.put(clazz, ReloadableType.NOT_RELOADABLE_TYPE_REF); // expensive if constantly discovering this return null; } try { rtypeField.setAccessible(true); rtype = (ReloadableType) rtypeField.get(null); if (rtype == null) { classToRType.put(clazz, ReloadableType.NOT_RELOADABLE_TYPE_REF); throw new ReloadException("ReloadableType field '" + Constants.fReloadableTypeFieldName + "' is 'null' on type " + clazz.getName()); } else { classToRType.put(clazz, new WeakReference<ReloadableType>(rtype)); } } catch (Exception e) { throw new ReloadException("Unable to access ReloadableType field '" + Constants.fReloadableTypeFieldName + "' on type " + clazz.getName(), e); } } } else if (rtype == ReloadableType.NOT_RELOADABLE_TYPE) { return null; } return rtype; }
java
public static ReloadableType getRType(Class<?> clazz) { // ReloadableType rtype = null; WeakReference<ReloadableType> ref = classToRType.get(clazz); ReloadableType rtype = null; if (ref != null) { rtype = ref.get(); } if (rtype == null) { if (!theOldWay) { // 'theOldWay' attempts to grab the field from the type via reflection. This usually works except // in cases where the class is not resolved yet since it can cause the class to resolve and its // static initializer to run. This was happening on a grails compile where the compiler is // loading dependencies (but not initializing them). Instead we can use this route of // discovering the type registry and locating the reloadable type. This does some map lookups // which may be a problem, but once discovered, it is cached in the weak ref so that shouldn't // be an ongoing perf problem. // TODO testcases for something that is reloaded without having been resolved ClassLoader cl = clazz.getClassLoader(); TypeRegistry tr = TypeRegistry.getTypeRegistryFor(cl); if (tr == null) { classToRType.put(clazz, ReloadableType.NOT_RELOADABLE_TYPE_REF); } else { rtype = tr.getReloadableType(clazz.getName().replace('.', '/')); if (rtype == null) { classToRType.put(clazz, ReloadableType.NOT_RELOADABLE_TYPE_REF); } else { classToRType.put(clazz, new WeakReference<ReloadableType>(rtype)); } } } else { // need to work it out Field rtypeField; try { // System.out.println("discovering field for " + clazz.getName()); // TODO cache somewhere - will need a clazz>Field cache rtypeField = clazz.getDeclaredField(Constants.fReloadableTypeFieldName); } catch (NoSuchFieldException nsfe) { classToRType.put(clazz, ReloadableType.NOT_RELOADABLE_TYPE_REF); // expensive if constantly discovering this return null; } try { rtypeField.setAccessible(true); rtype = (ReloadableType) rtypeField.get(null); if (rtype == null) { classToRType.put(clazz, ReloadableType.NOT_RELOADABLE_TYPE_REF); throw new ReloadException("ReloadableType field '" + Constants.fReloadableTypeFieldName + "' is 'null' on type " + clazz.getName()); } else { classToRType.put(clazz, new WeakReference<ReloadableType>(rtype)); } } catch (Exception e) { throw new ReloadException("Unable to access ReloadableType field '" + Constants.fReloadableTypeFieldName + "' on type " + clazz.getName(), e); } } } else if (rtype == ReloadableType.NOT_RELOADABLE_TYPE) { return null; } return rtype; }
[ "public", "static", "ReloadableType", "getRType", "(", "Class", "<", "?", ">", "clazz", ")", "{", "//\t\tReloadableType rtype = null;", "WeakReference", "<", "ReloadableType", ">", "ref", "=", "classToRType", ".", "get", "(", "clazz", ")", ";", "ReloadableType", "rtype", "=", "null", ";", "if", "(", "ref", "!=", "null", ")", "{", "rtype", "=", "ref", ".", "get", "(", ")", ";", "}", "if", "(", "rtype", "==", "null", ")", "{", "if", "(", "!", "theOldWay", ")", "{", "// 'theOldWay' attempts to grab the field from the type via reflection. This usually works except", "// in cases where the class is not resolved yet since it can cause the class to resolve and its", "// static initializer to run. This was happening on a grails compile where the compiler is", "// loading dependencies (but not initializing them). Instead we can use this route of", "// discovering the type registry and locating the reloadable type. This does some map lookups", "// which may be a problem, but once discovered, it is cached in the weak ref so that shouldn't", "// be an ongoing perf problem.", "// TODO testcases for something that is reloaded without having been resolved", "ClassLoader", "cl", "=", "clazz", ".", "getClassLoader", "(", ")", ";", "TypeRegistry", "tr", "=", "TypeRegistry", ".", "getTypeRegistryFor", "(", "cl", ")", ";", "if", "(", "tr", "==", "null", ")", "{", "classToRType", ".", "put", "(", "clazz", ",", "ReloadableType", ".", "NOT_RELOADABLE_TYPE_REF", ")", ";", "}", "else", "{", "rtype", "=", "tr", ".", "getReloadableType", "(", "clazz", ".", "getName", "(", ")", ".", "replace", "(", "'", "'", ",", "'", "'", ")", ")", ";", "if", "(", "rtype", "==", "null", ")", "{", "classToRType", ".", "put", "(", "clazz", ",", "ReloadableType", ".", "NOT_RELOADABLE_TYPE_REF", ")", ";", "}", "else", "{", "classToRType", ".", "put", "(", "clazz", ",", "new", "WeakReference", "<", "ReloadableType", ">", "(", "rtype", ")", ")", ";", "}", "}", "}", "else", "{", "// need to work it out", "Field", "rtypeField", ";", "try", "{", "//\t\t\t\tSystem.out.println(\"discovering field for \" + clazz.getName());", "// TODO cache somewhere - will need a clazz>Field cache", "rtypeField", "=", "clazz", ".", "getDeclaredField", "(", "Constants", ".", "fReloadableTypeFieldName", ")", ";", "}", "catch", "(", "NoSuchFieldException", "nsfe", ")", "{", "classToRType", ".", "put", "(", "clazz", ",", "ReloadableType", ".", "NOT_RELOADABLE_TYPE_REF", ")", ";", "// expensive if constantly discovering this", "return", "null", ";", "}", "try", "{", "rtypeField", ".", "setAccessible", "(", "true", ")", ";", "rtype", "=", "(", "ReloadableType", ")", "rtypeField", ".", "get", "(", "null", ")", ";", "if", "(", "rtype", "==", "null", ")", "{", "classToRType", ".", "put", "(", "clazz", ",", "ReloadableType", ".", "NOT_RELOADABLE_TYPE_REF", ")", ";", "throw", "new", "ReloadException", "(", "\"ReloadableType field '\"", "+", "Constants", ".", "fReloadableTypeFieldName", "+", "\"' is 'null' on type \"", "+", "clazz", ".", "getName", "(", ")", ")", ";", "}", "else", "{", "classToRType", ".", "put", "(", "clazz", ",", "new", "WeakReference", "<", "ReloadableType", ">", "(", "rtype", ")", ")", ";", "}", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "ReloadException", "(", "\"Unable to access ReloadableType field '\"", "+", "Constants", ".", "fReloadableTypeFieldName", "+", "\"' on type \"", "+", "clazz", ".", "getName", "(", ")", ",", "e", ")", ";", "}", "}", "}", "else", "if", "(", "rtype", "==", "ReloadableType", ".", "NOT_RELOADABLE_TYPE", ")", "{", "return", "null", ";", "}", "return", "rtype", ";", "}" ]
Access and return the ReloadableType field on a specified class. @param clazz the class for which to discover the reloadable type @return the reloadable type for the class, or null if not reloadable
[ "Access", "and", "return", "the", "ReloadableType", "field", "on", "a", "specified", "class", "." ]
59b32f957a05c6d9f149148158053605e2a6205a
https://github.com/spring-projects/spring-loaded/blob/59b32f957a05c6d9f149148158053605e2a6205a/springloaded/src/main/java/org/springsource/loaded/ri/ReflectiveInterceptor.java#L928-L998
26,421
spring-projects/spring-loaded
springloaded/src/main/java/org/springsource/loaded/ri/ReflectiveInterceptor.java
ReflectiveInterceptor.boxTypeFor
private static Class<?> boxTypeFor(Class<?> primType) { if (primType == int.class) { return Integer.class; } else if (primType == boolean.class) { return Boolean.class; } else if (primType == byte.class) { return Byte.class; } else if (primType == char.class) { return Character.class; } else if (primType == double.class) { return Double.class; } else if (primType == float.class) { return Float.class; } else if (primType == long.class) { return Long.class; } else if (primType == short.class) { return Short.class; } throw new IllegalStateException("Forgotten a case in this method?"); }
java
private static Class<?> boxTypeFor(Class<?> primType) { if (primType == int.class) { return Integer.class; } else if (primType == boolean.class) { return Boolean.class; } else if (primType == byte.class) { return Byte.class; } else if (primType == char.class) { return Character.class; } else if (primType == double.class) { return Double.class; } else if (primType == float.class) { return Float.class; } else if (primType == long.class) { return Long.class; } else if (primType == short.class) { return Short.class; } throw new IllegalStateException("Forgotten a case in this method?"); }
[ "private", "static", "Class", "<", "?", ">", "boxTypeFor", "(", "Class", "<", "?", ">", "primType", ")", "{", "if", "(", "primType", "==", "int", ".", "class", ")", "{", "return", "Integer", ".", "class", ";", "}", "else", "if", "(", "primType", "==", "boolean", ".", "class", ")", "{", "return", "Boolean", ".", "class", ";", "}", "else", "if", "(", "primType", "==", "byte", ".", "class", ")", "{", "return", "Byte", ".", "class", ";", "}", "else", "if", "(", "primType", "==", "char", ".", "class", ")", "{", "return", "Character", ".", "class", ";", "}", "else", "if", "(", "primType", "==", "double", ".", "class", ")", "{", "return", "Double", ".", "class", ";", "}", "else", "if", "(", "primType", "==", "float", ".", "class", ")", "{", "return", "Float", ".", "class", ";", "}", "else", "if", "(", "primType", "==", "long", ".", "class", ")", "{", "return", "Long", ".", "class", ";", "}", "else", "if", "(", "primType", "==", "short", ".", "class", ")", "{", "return", "Short", ".", "class", ";", "}", "throw", "new", "IllegalStateException", "(", "\"Forgotten a case in this method?\"", ")", ";", "}" ]
What's the "boxed" version of a given primtive type.
[ "What", "s", "the", "boxed", "version", "of", "a", "given", "primtive", "type", "." ]
59b32f957a05c6d9f149148158053605e2a6205a
https://github.com/spring-projects/spring-loaded/blob/59b32f957a05c6d9f149148158053605e2a6205a/springloaded/src/main/java/org/springsource/loaded/ri/ReflectiveInterceptor.java#L2199-L2225
26,422
spring-projects/spring-loaded
springloaded/src/main/java/org/springsource/loaded/ReloadableType.java
ReloadableType.retransform
private byte[] retransform(byte[] bytes) { if (!determinedNeedToRetransform) { try { String s = System.getProperty("insight.enabled", "false"); if (s.equals("true")) { // Access the weavingTransformer field, of type WeavingTransformer ClassLoader cl = typeRegistry.getClassLoader(); Field f = cl.getClass().getSuperclass().getDeclaredField("weavingTransformer"); if (f != null) { f.setAccessible(true); retransformWeavingTransformer = f.get(cl); // Stash the weavingtransformer instance and transformIfNecessaryMethod // byte[] transformIfNecessary(String className, byte[] bytes) { retransformWeavingTransformMethod = retransformWeavingTransformer.getClass().getDeclaredMethod( "transformIfNecessary", String.class, byte[].class); retransformNecessary = true; } if (GlobalConfiguration.isRuntimeLogging && log.isLoggable(Level.INFO)) { log.info("Determining if retransform necessary, result = " + retransformNecessary); } } } catch (Exception e) { log.log(Level.SEVERE, "Unexpected exception when determining if Spring Insight enabled", e); retransformNecessary = false; } determinedNeedToRetransform = true; } if (retransformNecessary) { try { retransformWeavingTransformMethod.setAccessible(true); byte[] newdata = (byte[]) retransformWeavingTransformMethod.invoke(retransformWeavingTransformer, this.slashedtypename, bytes); // System.err.println("RETRANSFORMATION RUNNING. oldsize=" + bytes.length + " newsize=" + newdata.length); if (GlobalConfiguration.isRuntimeLogging && log.isLoggable(Level.INFO)) { log.info("retransform was attempted, oldsize=" + bytes.length + " newsize=" + newdata.length); } return newdata; } catch (Exception e) { if (GlobalConfiguration.isRuntimeLogging) { log.log(Level.SEVERE, "Unexpected exception when trying to run other weaving transformers", e); } } } return bytes; }
java
private byte[] retransform(byte[] bytes) { if (!determinedNeedToRetransform) { try { String s = System.getProperty("insight.enabled", "false"); if (s.equals("true")) { // Access the weavingTransformer field, of type WeavingTransformer ClassLoader cl = typeRegistry.getClassLoader(); Field f = cl.getClass().getSuperclass().getDeclaredField("weavingTransformer"); if (f != null) { f.setAccessible(true); retransformWeavingTransformer = f.get(cl); // Stash the weavingtransformer instance and transformIfNecessaryMethod // byte[] transformIfNecessary(String className, byte[] bytes) { retransformWeavingTransformMethod = retransformWeavingTransformer.getClass().getDeclaredMethod( "transformIfNecessary", String.class, byte[].class); retransformNecessary = true; } if (GlobalConfiguration.isRuntimeLogging && log.isLoggable(Level.INFO)) { log.info("Determining if retransform necessary, result = " + retransformNecessary); } } } catch (Exception e) { log.log(Level.SEVERE, "Unexpected exception when determining if Spring Insight enabled", e); retransformNecessary = false; } determinedNeedToRetransform = true; } if (retransformNecessary) { try { retransformWeavingTransformMethod.setAccessible(true); byte[] newdata = (byte[]) retransformWeavingTransformMethod.invoke(retransformWeavingTransformer, this.slashedtypename, bytes); // System.err.println("RETRANSFORMATION RUNNING. oldsize=" + bytes.length + " newsize=" + newdata.length); if (GlobalConfiguration.isRuntimeLogging && log.isLoggable(Level.INFO)) { log.info("retransform was attempted, oldsize=" + bytes.length + " newsize=" + newdata.length); } return newdata; } catch (Exception e) { if (GlobalConfiguration.isRuntimeLogging) { log.log(Level.SEVERE, "Unexpected exception when trying to run other weaving transformers", e); } } } return bytes; }
[ "private", "byte", "[", "]", "retransform", "(", "byte", "[", "]", "bytes", ")", "{", "if", "(", "!", "determinedNeedToRetransform", ")", "{", "try", "{", "String", "s", "=", "System", ".", "getProperty", "(", "\"insight.enabled\"", ",", "\"false\"", ")", ";", "if", "(", "s", ".", "equals", "(", "\"true\"", ")", ")", "{", "// Access the weavingTransformer field, of type WeavingTransformer", "ClassLoader", "cl", "=", "typeRegistry", ".", "getClassLoader", "(", ")", ";", "Field", "f", "=", "cl", ".", "getClass", "(", ")", ".", "getSuperclass", "(", ")", ".", "getDeclaredField", "(", "\"weavingTransformer\"", ")", ";", "if", "(", "f", "!=", "null", ")", "{", "f", ".", "setAccessible", "(", "true", ")", ";", "retransformWeavingTransformer", "=", "f", ".", "get", "(", "cl", ")", ";", "// Stash the weavingtransformer instance and transformIfNecessaryMethod", "// byte[] transformIfNecessary(String className, byte[] bytes) {", "retransformWeavingTransformMethod", "=", "retransformWeavingTransformer", ".", "getClass", "(", ")", ".", "getDeclaredMethod", "(", "\"transformIfNecessary\"", ",", "String", ".", "class", ",", "byte", "[", "]", ".", "class", ")", ";", "retransformNecessary", "=", "true", ";", "}", "if", "(", "GlobalConfiguration", ".", "isRuntimeLogging", "&&", "log", ".", "isLoggable", "(", "Level", ".", "INFO", ")", ")", "{", "log", ".", "info", "(", "\"Determining if retransform necessary, result = \"", "+", "retransformNecessary", ")", ";", "}", "}", "}", "catch", "(", "Exception", "e", ")", "{", "log", ".", "log", "(", "Level", ".", "SEVERE", ",", "\"Unexpected exception when determining if Spring Insight enabled\"", ",", "e", ")", ";", "retransformNecessary", "=", "false", ";", "}", "determinedNeedToRetransform", "=", "true", ";", "}", "if", "(", "retransformNecessary", ")", "{", "try", "{", "retransformWeavingTransformMethod", ".", "setAccessible", "(", "true", ")", ";", "byte", "[", "]", "newdata", "=", "(", "byte", "[", "]", ")", "retransformWeavingTransformMethod", ".", "invoke", "(", "retransformWeavingTransformer", ",", "this", ".", "slashedtypename", ",", "bytes", ")", ";", "//\t\t\t\tSystem.err.println(\"RETRANSFORMATION RUNNING. oldsize=\" + bytes.length + \" newsize=\" + newdata.length);", "if", "(", "GlobalConfiguration", ".", "isRuntimeLogging", "&&", "log", ".", "isLoggable", "(", "Level", ".", "INFO", ")", ")", "{", "log", ".", "info", "(", "\"retransform was attempted, oldsize=\"", "+", "bytes", ".", "length", "+", "\" newsize=\"", "+", "newdata", ".", "length", ")", ";", "}", "return", "newdata", ";", "}", "catch", "(", "Exception", "e", ")", "{", "if", "(", "GlobalConfiguration", ".", "isRuntimeLogging", ")", "{", "log", ".", "log", "(", "Level", ".", "SEVERE", ",", "\"Unexpected exception when trying to run other weaving transformers\"", ",", "e", ")", ";", "}", "}", "}", "return", "bytes", ";", "}" ]
This method will attempt to apply any pre-existing transforms to the provided bytecode, if it is thought to be necessary. Currently 'necessary' is determined by finding ourselves running under tcServer and Spring Insight being turned on. @param bytes the new bytes to be possibly transformed. @return either the original bytes or a transformed set of bytes
[ "This", "method", "will", "attempt", "to", "apply", "any", "pre", "-", "existing", "transforms", "to", "the", "provided", "bytecode", "if", "it", "is", "thought", "to", "be", "necessary", ".", "Currently", "necessary", "is", "determined", "by", "finding", "ourselves", "running", "under", "tcServer", "and", "Spring", "Insight", "being", "turned", "on", "." ]
59b32f957a05c6d9f149148158053605e2a6205a
https://github.com/spring-projects/spring-loaded/blob/59b32f957a05c6d9f149148158053605e2a6205a/springloaded/src/main/java/org/springsource/loaded/ReloadableType.java#L230-L276
26,423
spring-projects/spring-loaded
springloaded/src/main/java/org/springsource/loaded/ReloadableType.java
ReloadableType.resetEnumRelatedState
private void resetEnumRelatedState() { if (clazz == null) { // the reloadabletype exists but the class hasn't been loaded yet! return; } try { Field f = clazz.getClass().getDeclaredField("enumConstants"); f.setAccessible(true); f.set(clazz, null); } catch (Exception e) { e.printStackTrace(); } try { Field f = clazz.getClass().getDeclaredField("enumConstantDirectory"); f.setAccessible(true); f.set(clazz, null); } catch (Exception e) { e.printStackTrace(); } }
java
private void resetEnumRelatedState() { if (clazz == null) { // the reloadabletype exists but the class hasn't been loaded yet! return; } try { Field f = clazz.getClass().getDeclaredField("enumConstants"); f.setAccessible(true); f.set(clazz, null); } catch (Exception e) { e.printStackTrace(); } try { Field f = clazz.getClass().getDeclaredField("enumConstantDirectory"); f.setAccessible(true); f.set(clazz, null); } catch (Exception e) { e.printStackTrace(); } }
[ "private", "void", "resetEnumRelatedState", "(", ")", "{", "if", "(", "clazz", "==", "null", ")", "{", "// the reloadabletype exists but the class hasn't been loaded yet!", "return", ";", "}", "try", "{", "Field", "f", "=", "clazz", ".", "getClass", "(", ")", ".", "getDeclaredField", "(", "\"enumConstants\"", ")", ";", "f", ".", "setAccessible", "(", "true", ")", ";", "f", ".", "set", "(", "clazz", ",", "null", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "try", "{", "Field", "f", "=", "clazz", ".", "getClass", "(", ")", ".", "getDeclaredField", "(", "\"enumConstantDirectory\"", ")", ";", "f", ".", "setAccessible", "(", "true", ")", ";", "f", ".", "set", "(", "clazz", ",", "null", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "}" ]
When an enum type is reloaded, two caches need to be cleared out from the Class object for the enum type.
[ "When", "an", "enum", "type", "is", "reloaded", "two", "caches", "need", "to", "be", "cleared", "out", "from", "the", "Class", "object", "for", "the", "enum", "type", "." ]
59b32f957a05c6d9f149148158053605e2a6205a
https://github.com/spring-projects/spring-loaded/blob/59b32f957a05c6d9f149148158053605e2a6205a/springloaded/src/main/java/org/springsource/loaded/ReloadableType.java#L500-L521
26,424
spring-projects/spring-loaded
springloaded/src/main/java/org/springsource/loaded/ReloadableType.java
ReloadableType.getCurrentMethod
public MethodMember getCurrentMethod(String name, String descriptor) { if (liveVersion == null) { return getMethod(name, descriptor); } else { return liveVersion.getReloadableMethod(name, descriptor); } }
java
public MethodMember getCurrentMethod(String name, String descriptor) { if (liveVersion == null) { return getMethod(name, descriptor); } else { return liveVersion.getReloadableMethod(name, descriptor); } }
[ "public", "MethodMember", "getCurrentMethod", "(", "String", "name", ",", "String", "descriptor", ")", "{", "if", "(", "liveVersion", "==", "null", ")", "{", "return", "getMethod", "(", "name", ",", "descriptor", ")", ";", "}", "else", "{", "return", "liveVersion", ".", "getReloadableMethod", "(", "name", ",", "descriptor", ")", ";", "}", "}" ]
Gets the method corresponding to given name and descriptor, taking into consideration changes that have happened by reloading. @param name the member name @param descriptor the member descriptor (e.g. (Ljava/lang/String;)I) @return the MethodMember for that name and descriptor. Null if not found on a live version, or an exception if there is no live version and it cannot be found.
[ "Gets", "the", "method", "corresponding", "to", "given", "name", "and", "descriptor", "taking", "into", "consideration", "changes", "that", "have", "happened", "by", "reloading", "." ]
59b32f957a05c6d9f149148158053605e2a6205a
https://github.com/spring-projects/spring-loaded/blob/59b32f957a05c6d9f149148158053605e2a6205a/springloaded/src/main/java/org/springsource/loaded/ReloadableType.java#L878-L885
26,425
spring-projects/spring-loaded
springloaded/src/main/java/org/springsource/loaded/ReloadableType.java
ReloadableType.changed
@UsedByGeneratedCode public int changed(int methodId) { if (liveVersion == null) { return 0; } else { int retval = 0; // First check if a new version of the type was loaded: if (liveVersion != null) { if (GlobalConfiguration.logging && log.isLoggable(Level.FINER)) { log.info("MethodId=" + methodId + " method=" + typedescriptor.getMethod(methodId)); } // TODO [perf] could be faster to return the executor here and if one isn't returned, do the original thing. // the reason for 3 ret vals here is due to catching methods that have been deleted early - lets let the // executor throw that exception, then this side we don't have to worry so much and instead of 2 check calls (changed then getexecutor) we can // just have one. Will increase speed and reduce generated code (speeding up loadtime!) // was the method deleted? boolean b = liveVersion.incrementalTypeDescriptor.hasBeenDeleted(methodId); if (b) { retval = 2; } else { retval = liveVersion.incrementalTypeDescriptor.mustUseExecutorForThisMethod(methodId) ? 1 : 0; } } // TODO could be extremely fine grained and consider individual method changes // return memberIntMap.get(methodId).hasChanged(); return retval; } }
java
@UsedByGeneratedCode public int changed(int methodId) { if (liveVersion == null) { return 0; } else { int retval = 0; // First check if a new version of the type was loaded: if (liveVersion != null) { if (GlobalConfiguration.logging && log.isLoggable(Level.FINER)) { log.info("MethodId=" + methodId + " method=" + typedescriptor.getMethod(methodId)); } // TODO [perf] could be faster to return the executor here and if one isn't returned, do the original thing. // the reason for 3 ret vals here is due to catching methods that have been deleted early - lets let the // executor throw that exception, then this side we don't have to worry so much and instead of 2 check calls (changed then getexecutor) we can // just have one. Will increase speed and reduce generated code (speeding up loadtime!) // was the method deleted? boolean b = liveVersion.incrementalTypeDescriptor.hasBeenDeleted(methodId); if (b) { retval = 2; } else { retval = liveVersion.incrementalTypeDescriptor.mustUseExecutorForThisMethod(methodId) ? 1 : 0; } } // TODO could be extremely fine grained and consider individual method changes // return memberIntMap.get(methodId).hasChanged(); return retval; } }
[ "@", "UsedByGeneratedCode", "public", "int", "changed", "(", "int", "methodId", ")", "{", "if", "(", "liveVersion", "==", "null", ")", "{", "return", "0", ";", "}", "else", "{", "int", "retval", "=", "0", ";", "// First check if a new version of the type was loaded:", "if", "(", "liveVersion", "!=", "null", ")", "{", "if", "(", "GlobalConfiguration", ".", "logging", "&&", "log", ".", "isLoggable", "(", "Level", ".", "FINER", ")", ")", "{", "log", ".", "info", "(", "\"MethodId=\"", "+", "methodId", "+", "\" method=\"", "+", "typedescriptor", ".", "getMethod", "(", "methodId", ")", ")", ";", "}", "// TODO [perf] could be faster to return the executor here and if one isn't returned, do the original thing.", "// the reason for 3 ret vals here is due to catching methods that have been deleted early - lets let the", "// executor throw that exception, then this side we don't have to worry so much and instead of 2 check calls (changed then getexecutor) we can", "// just have one. Will increase speed and reduce generated code (speeding up loadtime!)", "// was the method deleted?", "boolean", "b", "=", "liveVersion", ".", "incrementalTypeDescriptor", ".", "hasBeenDeleted", "(", "methodId", ")", ";", "if", "(", "b", ")", "{", "retval", "=", "2", ";", "}", "else", "{", "retval", "=", "liveVersion", ".", "incrementalTypeDescriptor", ".", "mustUseExecutorForThisMethod", "(", "methodId", ")", "?", "1", ":", "0", ";", "}", "}", "// TODO could be extremely fine grained and consider individual method changes", "//\t\treturn memberIntMap.get(methodId).hasChanged();", "return", "retval", ";", "}", "}" ]
Check if the specified method is different to the original form from the type as loaded. @param methodId the ID of the method currently executing @return 0 if the method cannot have changed. 1 if the method has changed. 2 if the method has been deleted in a new version.
[ "Check", "if", "the", "specified", "method", "is", "different", "to", "the", "original", "form", "from", "the", "type", "as", "loaded", "." ]
59b32f957a05c6d9f149148158053605e2a6205a
https://github.com/spring-projects/spring-loaded/blob/59b32f957a05c6d9f149148158053605e2a6205a/springloaded/src/main/java/org/springsource/loaded/ReloadableType.java#L1053-L1082
26,426
spring-projects/spring-loaded
springloaded/src/main/java/org/springsource/loaded/ReloadableType.java
ReloadableType.determineDispatcher
@UsedByGeneratedCode public __DynamicallyDispatchable determineDispatcher(Object instance, String nameAndDescriptor) { if (nameAndDescriptor.startsWith("<init>")) { // its a ctor, no dynamic lookup required if (!hasBeenReloaded()) { // TODO evaluate whether this is too naughty. it forces creation of the dispatcher so we can return it loadNewVersion("0", bytesInitial); } return (__DynamicallyDispatchable) getLiveVersion().dispatcherInstance; } String dynamicTypeName = instance.getClass().getName(); // iterate up the hierarchy finding the first person that can satisfy that method from a virtual dispatch perspective ReloadableType rtype = typeRegistry.getReloadableType(dynamicTypeName.replace('.', '/')); if (rtype == null) { throw new ReloadException("ReloadableType.determineDispatcher(): expected " + dynamicTypeName + " to be reloadable"); } boolean found = false; while (rtype != null && !found) { if (rtype.hasBeenReloaded()) { // Does the type now define it: // TODO not sure if we should be looking at deleted methods here. It is possible they are // handled by catchers/executors delegating as appropriate - and in those cases we never // end up in determineDispatcher List<MethodMember> mms = rtype.getLiveVersion().incrementalTypeDescriptor.getNewOrChangedMethods(); for (MethodMember mm : mms) { // boolean wd = IncrementalTypeDescriptor.wasDeleted(mm); if (mm.isPrivate()) { // TODO is skipping of private methods correct thing to do continue; } if (mm.getNameAndDescriptor().equals(nameAndDescriptor)) { // the reloaded version does implement this method found = true; break; } } } else { // Did the type originally define it: MethodMember[] mms = rtype.getTypeDescriptor().getMethods(); for (MethodMember mm : mms) { // TODO don't need superdispatcher check, name won't match will it... if (mm.getNameAndDescriptor().equals(nameAndDescriptor) && !MethodMember.isCatcher(mm) && !MethodMember.isSuperDispatcher(mm)) { // the original version does implement it found = true; break; } } } if (!found) { String slashedSupername = rtype.getTypeDescriptor().getSupertypeName(); rtype = typeRegistry.getReloadableType(slashedSupername); } } if (found) { if (GlobalConfiguration.isRuntimeLogging && log.isLoggable(Level.INFO)) { log.log(Level.INFO, "appears that type " + rtype.getName() + " implements " + nameAndDescriptor); } } if (rtype == null) { return null; } if (!rtype.hasBeenReloaded()) { // TODO evaluate whether this is too naughty. it forces creation of the dispatcher so we can return it rtype.loadNewVersion("0", rtype.bytesInitial); } return (__DynamicallyDispatchable) rtype.getLiveVersion().dispatcherInstance; }
java
@UsedByGeneratedCode public __DynamicallyDispatchable determineDispatcher(Object instance, String nameAndDescriptor) { if (nameAndDescriptor.startsWith("<init>")) { // its a ctor, no dynamic lookup required if (!hasBeenReloaded()) { // TODO evaluate whether this is too naughty. it forces creation of the dispatcher so we can return it loadNewVersion("0", bytesInitial); } return (__DynamicallyDispatchable) getLiveVersion().dispatcherInstance; } String dynamicTypeName = instance.getClass().getName(); // iterate up the hierarchy finding the first person that can satisfy that method from a virtual dispatch perspective ReloadableType rtype = typeRegistry.getReloadableType(dynamicTypeName.replace('.', '/')); if (rtype == null) { throw new ReloadException("ReloadableType.determineDispatcher(): expected " + dynamicTypeName + " to be reloadable"); } boolean found = false; while (rtype != null && !found) { if (rtype.hasBeenReloaded()) { // Does the type now define it: // TODO not sure if we should be looking at deleted methods here. It is possible they are // handled by catchers/executors delegating as appropriate - and in those cases we never // end up in determineDispatcher List<MethodMember> mms = rtype.getLiveVersion().incrementalTypeDescriptor.getNewOrChangedMethods(); for (MethodMember mm : mms) { // boolean wd = IncrementalTypeDescriptor.wasDeleted(mm); if (mm.isPrivate()) { // TODO is skipping of private methods correct thing to do continue; } if (mm.getNameAndDescriptor().equals(nameAndDescriptor)) { // the reloaded version does implement this method found = true; break; } } } else { // Did the type originally define it: MethodMember[] mms = rtype.getTypeDescriptor().getMethods(); for (MethodMember mm : mms) { // TODO don't need superdispatcher check, name won't match will it... if (mm.getNameAndDescriptor().equals(nameAndDescriptor) && !MethodMember.isCatcher(mm) && !MethodMember.isSuperDispatcher(mm)) { // the original version does implement it found = true; break; } } } if (!found) { String slashedSupername = rtype.getTypeDescriptor().getSupertypeName(); rtype = typeRegistry.getReloadableType(slashedSupername); } } if (found) { if (GlobalConfiguration.isRuntimeLogging && log.isLoggable(Level.INFO)) { log.log(Level.INFO, "appears that type " + rtype.getName() + " implements " + nameAndDescriptor); } } if (rtype == null) { return null; } if (!rtype.hasBeenReloaded()) { // TODO evaluate whether this is too naughty. it forces creation of the dispatcher so we can return it rtype.loadNewVersion("0", rtype.bytesInitial); } return (__DynamicallyDispatchable) rtype.getLiveVersion().dispatcherInstance; }
[ "@", "UsedByGeneratedCode", "public", "__DynamicallyDispatchable", "determineDispatcher", "(", "Object", "instance", ",", "String", "nameAndDescriptor", ")", "{", "if", "(", "nameAndDescriptor", ".", "startsWith", "(", "\"<init>\"", ")", ")", "{", "// its a ctor, no dynamic lookup required", "if", "(", "!", "hasBeenReloaded", "(", ")", ")", "{", "// TODO evaluate whether this is too naughty. it forces creation of the dispatcher so we can return it", "loadNewVersion", "(", "\"0\"", ",", "bytesInitial", ")", ";", "}", "return", "(", "__DynamicallyDispatchable", ")", "getLiveVersion", "(", ")", ".", "dispatcherInstance", ";", "}", "String", "dynamicTypeName", "=", "instance", ".", "getClass", "(", ")", ".", "getName", "(", ")", ";", "// iterate up the hierarchy finding the first person that can satisfy that method from a virtual dispatch perspective", "ReloadableType", "rtype", "=", "typeRegistry", ".", "getReloadableType", "(", "dynamicTypeName", ".", "replace", "(", "'", "'", ",", "'", "'", ")", ")", ";", "if", "(", "rtype", "==", "null", ")", "{", "throw", "new", "ReloadException", "(", "\"ReloadableType.determineDispatcher(): expected \"", "+", "dynamicTypeName", "+", "\" to be reloadable\"", ")", ";", "}", "boolean", "found", "=", "false", ";", "while", "(", "rtype", "!=", "null", "&&", "!", "found", ")", "{", "if", "(", "rtype", ".", "hasBeenReloaded", "(", ")", ")", "{", "// Does the type now define it:", "// TODO not sure if we should be looking at deleted methods here. It is possible they are", "// handled by catchers/executors delegating as appropriate - and in those cases we never", "// end up in determineDispatcher", "List", "<", "MethodMember", ">", "mms", "=", "rtype", ".", "getLiveVersion", "(", ")", ".", "incrementalTypeDescriptor", ".", "getNewOrChangedMethods", "(", ")", ";", "for", "(", "MethodMember", "mm", ":", "mms", ")", "{", "// boolean wd = IncrementalTypeDescriptor.wasDeleted(mm);", "if", "(", "mm", ".", "isPrivate", "(", ")", ")", "{", "// TODO is skipping of private methods correct thing to do", "continue", ";", "}", "if", "(", "mm", ".", "getNameAndDescriptor", "(", ")", ".", "equals", "(", "nameAndDescriptor", ")", ")", "{", "// the reloaded version does implement this method", "found", "=", "true", ";", "break", ";", "}", "}", "}", "else", "{", "// Did the type originally define it:", "MethodMember", "[", "]", "mms", "=", "rtype", ".", "getTypeDescriptor", "(", ")", ".", "getMethods", "(", ")", ";", "for", "(", "MethodMember", "mm", ":", "mms", ")", "{", "// TODO don't need superdispatcher check, name won't match will it...", "if", "(", "mm", ".", "getNameAndDescriptor", "(", ")", ".", "equals", "(", "nameAndDescriptor", ")", "&&", "!", "MethodMember", ".", "isCatcher", "(", "mm", ")", "&&", "!", "MethodMember", ".", "isSuperDispatcher", "(", "mm", ")", ")", "{", "// the original version does implement it", "found", "=", "true", ";", "break", ";", "}", "}", "}", "if", "(", "!", "found", ")", "{", "String", "slashedSupername", "=", "rtype", ".", "getTypeDescriptor", "(", ")", ".", "getSupertypeName", "(", ")", ";", "rtype", "=", "typeRegistry", ".", "getReloadableType", "(", "slashedSupername", ")", ";", "}", "}", "if", "(", "found", ")", "{", "if", "(", "GlobalConfiguration", ".", "isRuntimeLogging", "&&", "log", ".", "isLoggable", "(", "Level", ".", "INFO", ")", ")", "{", "log", ".", "log", "(", "Level", ".", "INFO", ",", "\"appears that type \"", "+", "rtype", ".", "getName", "(", ")", "+", "\" implements \"", "+", "nameAndDescriptor", ")", ";", "}", "}", "if", "(", "rtype", "==", "null", ")", "{", "return", "null", ";", "}", "if", "(", "!", "rtype", ".", "hasBeenReloaded", "(", ")", ")", "{", "// TODO evaluate whether this is too naughty. it forces creation of the dispatcher so we can return it", "rtype", ".", "loadNewVersion", "(", "\"0\"", ",", "rtype", ".", "bytesInitial", ")", ";", "}", "return", "(", "__DynamicallyDispatchable", ")", "rtype", ".", "getLiveVersion", "(", ")", ".", "dispatcherInstance", ";", "}" ]
Intended to handle dynamic dispatch. This will determine the right type to handle the specified method and return a dispatcher that can handle it. @param instance the target instance for the invocation @param nameAndDescriptor an encoded method name and descriptor, e.g. foo(Ljava/langString;)V @return a dispatcher that can handle the method indicated
[ "Intended", "to", "handle", "dynamic", "dispatch", ".", "This", "will", "determine", "the", "right", "type", "to", "handle", "the", "specified", "method", "and", "return", "a", "dispatcher", "that", "can", "handle", "it", "." ]
59b32f957a05c6d9f149148158053605e2a6205a
https://github.com/spring-projects/spring-loaded/blob/59b32f957a05c6d9f149148158053605e2a6205a/springloaded/src/main/java/org/springsource/loaded/ReloadableType.java#L1141-L1211
26,427
spring-projects/spring-loaded
springloaded/src/main/java/org/springsource/loaded/ReloadableType.java
ReloadableType.findInstanceField
public FieldMember findInstanceField(String name) { FieldMember found = getLatestTypeDescriptor().getField(name); if (found != null) { return found; } // Walk up the supertypes - this is looking for instance fields so no need to search interfaces String slashedSupername = getTypeDescriptor().getSupertypeName(); ReloadableType rtype = typeRegistry.getReloadableType(slashedSupername); while (rtype != null) { found = rtype.getLatestTypeDescriptor().getField(name); if (found != null) { break; } slashedSupername = rtype.getTypeDescriptor().getSupertypeName(); rtype = typeRegistry.getReloadableType(slashedSupername); } return found; }
java
public FieldMember findInstanceField(String name) { FieldMember found = getLatestTypeDescriptor().getField(name); if (found != null) { return found; } // Walk up the supertypes - this is looking for instance fields so no need to search interfaces String slashedSupername = getTypeDescriptor().getSupertypeName(); ReloadableType rtype = typeRegistry.getReloadableType(slashedSupername); while (rtype != null) { found = rtype.getLatestTypeDescriptor().getField(name); if (found != null) { break; } slashedSupername = rtype.getTypeDescriptor().getSupertypeName(); rtype = typeRegistry.getReloadableType(slashedSupername); } return found; }
[ "public", "FieldMember", "findInstanceField", "(", "String", "name", ")", "{", "FieldMember", "found", "=", "getLatestTypeDescriptor", "(", ")", ".", "getField", "(", "name", ")", ";", "if", "(", "found", "!=", "null", ")", "{", "return", "found", ";", "}", "// Walk up the supertypes - this is looking for instance fields so no need to search interfaces", "String", "slashedSupername", "=", "getTypeDescriptor", "(", ")", ".", "getSupertypeName", "(", ")", ";", "ReloadableType", "rtype", "=", "typeRegistry", ".", "getReloadableType", "(", "slashedSupername", ")", ";", "while", "(", "rtype", "!=", "null", ")", "{", "found", "=", "rtype", ".", "getLatestTypeDescriptor", "(", ")", ".", "getField", "(", "name", ")", ";", "if", "(", "found", "!=", "null", ")", "{", "break", ";", "}", "slashedSupername", "=", "rtype", ".", "getTypeDescriptor", "(", ")", ".", "getSupertypeName", "(", ")", ";", "rtype", "=", "typeRegistry", ".", "getReloadableType", "(", "slashedSupername", ")", ";", "}", "return", "found", ";", "}" ]
Find the named instance field either on this reloadable type or on a reloadable supertype - it will not go into the non-reloadable types. This method also avoids interfaces because it is looking for instance fields. This is slightly naughty but if we assume the code we are reloading is valid code, it should never be referring to interface fields. @param name the name of the field to locate @return the FieldMember or null if the field is not found
[ "Find", "the", "named", "instance", "field", "either", "on", "this", "reloadable", "type", "or", "on", "a", "reloadable", "supertype", "-", "it", "will", "not", "go", "into", "the", "non", "-", "reloadable", "types", ".", "This", "method", "also", "avoids", "interfaces", "because", "it", "is", "looking", "for", "instance", "fields", ".", "This", "is", "slightly", "naughty", "but", "if", "we", "assume", "the", "code", "we", "are", "reloading", "is", "valid", "code", "it", "should", "never", "be", "referring", "to", "interface", "fields", "." ]
59b32f957a05c6d9f149148158053605e2a6205a
https://github.com/spring-projects/spring-loaded/blob/59b32f957a05c6d9f149148158053605e2a6205a/springloaded/src/main/java/org/springsource/loaded/ReloadableType.java#L1279-L1297
26,428
spring-projects/spring-loaded
springloaded/src/main/java/org/springsource/loaded/ReloadableType.java
ReloadableType.setField
public void setField(Object instance, String fieldname, boolean isStatic, Object newValue) throws IllegalAccessException { FieldReaderWriter fieldReaderWriter = locateField(fieldname); if (isStatic && !fieldReaderWriter.isStatic()) { throw new IncompatibleClassChangeError("Expected static field " + fieldReaderWriter.theField.getDeclaringTypeName() + "." + fieldReaderWriter.theField.getName()); } else if (!isStatic && fieldReaderWriter.isStatic()) { throw new IncompatibleClassChangeError("Expected non-static field " + fieldReaderWriter.theField.getDeclaringTypeName() + "." + fieldReaderWriter.theField.getName()); } if (fieldReaderWriter.isStatic()) { fieldReaderWriter.setStaticFieldValue(getClazz(), newValue, null); } else { fieldReaderWriter.setValue(instance, newValue, null); } }
java
public void setField(Object instance, String fieldname, boolean isStatic, Object newValue) throws IllegalAccessException { FieldReaderWriter fieldReaderWriter = locateField(fieldname); if (isStatic && !fieldReaderWriter.isStatic()) { throw new IncompatibleClassChangeError("Expected static field " + fieldReaderWriter.theField.getDeclaringTypeName() + "." + fieldReaderWriter.theField.getName()); } else if (!isStatic && fieldReaderWriter.isStatic()) { throw new IncompatibleClassChangeError("Expected non-static field " + fieldReaderWriter.theField.getDeclaringTypeName() + "." + fieldReaderWriter.theField.getName()); } if (fieldReaderWriter.isStatic()) { fieldReaderWriter.setStaticFieldValue(getClazz(), newValue, null); } else { fieldReaderWriter.setValue(instance, newValue, null); } }
[ "public", "void", "setField", "(", "Object", "instance", ",", "String", "fieldname", ",", "boolean", "isStatic", ",", "Object", "newValue", ")", "throws", "IllegalAccessException", "{", "FieldReaderWriter", "fieldReaderWriter", "=", "locateField", "(", "fieldname", ")", ";", "if", "(", "isStatic", "&&", "!", "fieldReaderWriter", ".", "isStatic", "(", ")", ")", "{", "throw", "new", "IncompatibleClassChangeError", "(", "\"Expected static field \"", "+", "fieldReaderWriter", ".", "theField", ".", "getDeclaringTypeName", "(", ")", "+", "\".\"", "+", "fieldReaderWriter", ".", "theField", ".", "getName", "(", ")", ")", ";", "}", "else", "if", "(", "!", "isStatic", "&&", "fieldReaderWriter", ".", "isStatic", "(", ")", ")", "{", "throw", "new", "IncompatibleClassChangeError", "(", "\"Expected non-static field \"", "+", "fieldReaderWriter", ".", "theField", ".", "getDeclaringTypeName", "(", ")", "+", "\".\"", "+", "fieldReaderWriter", ".", "theField", ".", "getName", "(", ")", ")", ";", "}", "if", "(", "fieldReaderWriter", ".", "isStatic", "(", ")", ")", "{", "fieldReaderWriter", ".", "setStaticFieldValue", "(", "getClazz", "(", ")", ",", "newValue", ",", "null", ")", ";", "}", "else", "{", "fieldReaderWriter", ".", "setValue", "(", "instance", ",", "newValue", ",", "null", ")", ";", "}", "}" ]
Attempt to set the value of a field on an instance to the specified value. @param instance the object upon which to set the field (maybe null for static fields) @param fieldname the name of the field @param isStatic whether the field is static @param newValue the new value to put into the field @throws IllegalAccessException if there is a problem setting the field value
[ "Attempt", "to", "set", "the", "value", "of", "a", "field", "on", "an", "instance", "to", "the", "specified", "value", "." ]
59b32f957a05c6d9f149148158053605e2a6205a
https://github.com/spring-projects/spring-loaded/blob/59b32f957a05c6d9f149148158053605e2a6205a/springloaded/src/main/java/org/springsource/loaded/ReloadableType.java#L1347-L1367
26,429
spring-projects/spring-loaded
springloaded/src/main/java/org/springsource/loaded/ReloadableType.java
ReloadableType.getSuperRtype
public ReloadableType getSuperRtype() { if (superRtype != null) { return superRtype; } if (superclazz == null) { // Not filled in yet? Why is this code different to the interface case? String name = this.getSlashedSupertypeName(); if (name == null) { return null; } else { ReloadableType rtype = typeRegistry.getReloadableSuperType(name); superRtype = rtype; return superRtype; } } else { ClassLoader superClassLoader = superclazz.getClassLoader(); TypeRegistry superTypeRegistry = TypeRegistry.getTypeRegistryFor(superClassLoader); superRtype = superTypeRegistry.getReloadableType(superclazz); return superRtype; } }
java
public ReloadableType getSuperRtype() { if (superRtype != null) { return superRtype; } if (superclazz == null) { // Not filled in yet? Why is this code different to the interface case? String name = this.getSlashedSupertypeName(); if (name == null) { return null; } else { ReloadableType rtype = typeRegistry.getReloadableSuperType(name); superRtype = rtype; return superRtype; } } else { ClassLoader superClassLoader = superclazz.getClassLoader(); TypeRegistry superTypeRegistry = TypeRegistry.getTypeRegistryFor(superClassLoader); superRtype = superTypeRegistry.getReloadableType(superclazz); return superRtype; } }
[ "public", "ReloadableType", "getSuperRtype", "(", ")", "{", "if", "(", "superRtype", "!=", "null", ")", "{", "return", "superRtype", ";", "}", "if", "(", "superclazz", "==", "null", ")", "{", "// Not filled in yet? Why is this code different to the interface case?", "String", "name", "=", "this", ".", "getSlashedSupertypeName", "(", ")", ";", "if", "(", "name", "==", "null", ")", "{", "return", "null", ";", "}", "else", "{", "ReloadableType", "rtype", "=", "typeRegistry", ".", "getReloadableSuperType", "(", "name", ")", ";", "superRtype", "=", "rtype", ";", "return", "superRtype", ";", "}", "}", "else", "{", "ClassLoader", "superClassLoader", "=", "superclazz", ".", "getClassLoader", "(", ")", ";", "TypeRegistry", "superTypeRegistry", "=", "TypeRegistry", ".", "getTypeRegistryFor", "(", "superClassLoader", ")", ";", "superRtype", "=", "superTypeRegistry", ".", "getReloadableType", "(", "superclazz", ")", ";", "return", "superRtype", ";", "}", "}" ]
Return the ReloadableType representing the superclass of this type. If the supertype is not reloadable, this method will return null. The ReloadableType that is returned may not be within the same type registry, if the supertype was loaded by a different classloader. @return the ReloadableType for the supertype or null if it is not reloadable
[ "Return", "the", "ReloadableType", "representing", "the", "superclass", "of", "this", "type", ".", "If", "the", "supertype", "is", "not", "reloadable", "this", "method", "will", "return", "null", ".", "The", "ReloadableType", "that", "is", "returned", "may", "not", "be", "within", "the", "same", "type", "registry", "if", "the", "supertype", "was", "loaded", "by", "a", "different", "classloader", "." ]
59b32f957a05c6d9f149148158053605e2a6205a
https://github.com/spring-projects/spring-loaded/blob/59b32f957a05c6d9f149148158053605e2a6205a/springloaded/src/main/java/org/springsource/loaded/ReloadableType.java#L1631-L1653
26,430
spring-projects/spring-loaded
springloaded/src/main/java/org/springsource/loaded/CurrentLiveVersion.java
CurrentLiveVersion.define
public void define() { staticInitializer = null; haveLookedForStaticInitializer = false; // DEFAULT METHODS - remove the if if (!typeDescriptor.isInterface()) { try { dispatcherClass = reloadableType.typeRegistry.defineClass(dispatcherName, dispatcher, false); } catch (RuntimeException t) { // TODO check for something strange. something to do with the file detection misbehaving, see the same file attempted to be reloaded twice... if (t.getMessage().indexOf("duplicate class definition") == -1) { throw t; } else { t.printStackTrace(); } } } try { executorClass = reloadableType.typeRegistry.defineClass(executorName, executor, false); } catch (RuntimeException t) { // TODO check for something strange. something to do with the file detection misbehaving, see the same file attempted to be reloaded twice... if (t.getMessage().indexOf("duplicate class definition") == -1) { throw t; } else { t.printStackTrace(); } } // DEFAULT METHODS - remove the if if (!typeDescriptor.isInterface()) { try { dispatcherInstance = dispatcherClass.newInstance(); } catch (InstantiationException e) { throw new RuntimeException("Unable to build dispatcher class instance", e); } catch (IllegalAccessException e) { throw new RuntimeException("Unable to build dispatcher class instance", e); } } }
java
public void define() { staticInitializer = null; haveLookedForStaticInitializer = false; // DEFAULT METHODS - remove the if if (!typeDescriptor.isInterface()) { try { dispatcherClass = reloadableType.typeRegistry.defineClass(dispatcherName, dispatcher, false); } catch (RuntimeException t) { // TODO check for something strange. something to do with the file detection misbehaving, see the same file attempted to be reloaded twice... if (t.getMessage().indexOf("duplicate class definition") == -1) { throw t; } else { t.printStackTrace(); } } } try { executorClass = reloadableType.typeRegistry.defineClass(executorName, executor, false); } catch (RuntimeException t) { // TODO check for something strange. something to do with the file detection misbehaving, see the same file attempted to be reloaded twice... if (t.getMessage().indexOf("duplicate class definition") == -1) { throw t; } else { t.printStackTrace(); } } // DEFAULT METHODS - remove the if if (!typeDescriptor.isInterface()) { try { dispatcherInstance = dispatcherClass.newInstance(); } catch (InstantiationException e) { throw new RuntimeException("Unable to build dispatcher class instance", e); } catch (IllegalAccessException e) { throw new RuntimeException("Unable to build dispatcher class instance", e); } } }
[ "public", "void", "define", "(", ")", "{", "staticInitializer", "=", "null", ";", "haveLookedForStaticInitializer", "=", "false", ";", "// DEFAULT METHODS - remove the if", "if", "(", "!", "typeDescriptor", ".", "isInterface", "(", ")", ")", "{", "try", "{", "dispatcherClass", "=", "reloadableType", ".", "typeRegistry", ".", "defineClass", "(", "dispatcherName", ",", "dispatcher", ",", "false", ")", ";", "}", "catch", "(", "RuntimeException", "t", ")", "{", "// TODO check for something strange. something to do with the file detection misbehaving, see the same file attempted to be reloaded twice...", "if", "(", "t", ".", "getMessage", "(", ")", ".", "indexOf", "(", "\"duplicate class definition\"", ")", "==", "-", "1", ")", "{", "throw", "t", ";", "}", "else", "{", "t", ".", "printStackTrace", "(", ")", ";", "}", "}", "}", "try", "{", "executorClass", "=", "reloadableType", ".", "typeRegistry", ".", "defineClass", "(", "executorName", ",", "executor", ",", "false", ")", ";", "}", "catch", "(", "RuntimeException", "t", ")", "{", "// TODO check for something strange. something to do with the file detection misbehaving, see the same file attempted to be reloaded twice...", "if", "(", "t", ".", "getMessage", "(", ")", ".", "indexOf", "(", "\"duplicate class definition\"", ")", "==", "-", "1", ")", "{", "throw", "t", ";", "}", "else", "{", "t", ".", "printStackTrace", "(", ")", ";", "}", "}", "// DEFAULT METHODS - remove the if", "if", "(", "!", "typeDescriptor", ".", "isInterface", "(", ")", ")", "{", "try", "{", "dispatcherInstance", "=", "dispatcherClass", ".", "newInstance", "(", ")", ";", "}", "catch", "(", "InstantiationException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "\"Unable to build dispatcher class instance\"", ",", "e", ")", ";", "}", "catch", "(", "IllegalAccessException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "\"Unable to build dispatcher class instance\"", ",", "e", ")", ";", "}", "}", "}" ]
Defines this version. Called up front but can also be called later if the ChildClassLoader in a type registry is discarded and recreated.
[ "Defines", "this", "version", ".", "Called", "up", "front", "but", "can", "also", "be", "called", "later", "if", "the", "ChildClassLoader", "in", "a", "type", "registry", "is", "discarded", "and", "recreated", "." ]
59b32f957a05c6d9f149148158053605e2a6205a
https://github.com/spring-projects/spring-loaded/blob/59b32f957a05c6d9f149148158053605e2a6205a/springloaded/src/main/java/org/springsource/loaded/CurrentLiveVersion.java#L118-L160
26,431
spring-projects/spring-loaded
springloaded/src/main/java/org/springsource/loaded/TypeDescriptor.java
TypeDescriptor.getByDescriptor
public MethodMember getByDescriptor(String name, String descriptor) { for (MethodMember existingMethod : methods) { if (existingMethod.getName().equals(name) && existingMethod.getDescriptor().equals(descriptor)) { return existingMethod; } } return null; }
java
public MethodMember getByDescriptor(String name, String descriptor) { for (MethodMember existingMethod : methods) { if (existingMethod.getName().equals(name) && existingMethod.getDescriptor().equals(descriptor)) { return existingMethod; } } return null; }
[ "public", "MethodMember", "getByDescriptor", "(", "String", "name", ",", "String", "descriptor", ")", "{", "for", "(", "MethodMember", "existingMethod", ":", "methods", ")", "{", "if", "(", "existingMethod", ".", "getName", "(", ")", ".", "equals", "(", "name", ")", "&&", "existingMethod", ".", "getDescriptor", "(", ")", ".", "equals", "(", "descriptor", ")", ")", "{", "return", "existingMethod", ";", "}", "}", "return", "null", ";", "}" ]
Check if this descriptor defines a method with the specified name and descriptor. Return the method if it is found. Modifiers, generic signature and exceptions are ignored in this search. @param name the member name @param descriptor the member descriptor (e.g. (Ljava/lang/String;)I) @return the MethodMember if there is one
[ "Check", "if", "this", "descriptor", "defines", "a", "method", "with", "the", "specified", "name", "and", "descriptor", ".", "Return", "the", "method", "if", "it", "is", "found", ".", "Modifiers", "generic", "signature", "and", "exceptions", "are", "ignored", "in", "this", "search", "." ]
59b32f957a05c6d9f149148158053605e2a6205a
https://github.com/spring-projects/spring-loaded/blob/59b32f957a05c6d9f149148158053605e2a6205a/springloaded/src/main/java/org/springsource/loaded/TypeDescriptor.java#L182-L189
26,432
spring-projects/spring-loaded
springloaded/src/main/java/org/springsource/loaded/InterfaceExtractor.java
InterfaceExtractor.extract
public static byte[] extract(byte[] classbytes, TypeRegistry registry, TypeDescriptor typeDescriptor) { return new InterfaceExtractor(registry).extract(classbytes, typeDescriptor); }
java
public static byte[] extract(byte[] classbytes, TypeRegistry registry, TypeDescriptor typeDescriptor) { return new InterfaceExtractor(registry).extract(classbytes, typeDescriptor); }
[ "public", "static", "byte", "[", "]", "extract", "(", "byte", "[", "]", "classbytes", ",", "TypeRegistry", "registry", ",", "TypeDescriptor", "typeDescriptor", ")", "{", "return", "new", "InterfaceExtractor", "(", "registry", ")", ".", "extract", "(", "classbytes", ",", "typeDescriptor", ")", ";", "}" ]
Extract the fixed interface for a class and a type descriptor with more details on the methods. @param classbytes bytes for the class which is going through interface extraction @param registry type registry related to the classloader for this class @param typeDescriptor previously extracted type descriptor for the class @return class bytes for extracted interface
[ "Extract", "the", "fixed", "interface", "for", "a", "class", "and", "a", "type", "descriptor", "with", "more", "details", "on", "the", "methods", "." ]
59b32f957a05c6d9f149148158053605e2a6205a
https://github.com/spring-projects/spring-loaded/blob/59b32f957a05c6d9f149148158053605e2a6205a/springloaded/src/main/java/org/springsource/loaded/InterfaceExtractor.java#L69-L71
26,433
spring-projects/spring-loaded
springloaded/src/main/java/org/springsource/loaded/DispatcherBuilder.java
DispatcherBuilder.createFor
public static byte[] createFor(ReloadableType rtype, IncrementalTypeDescriptor newVersionTypeDescriptor, String versionstamp) { ClassReader fileReader = new ClassReader(rtype.interfaceBytes); DispatcherBuilderVisitor dispatcherVisitor = new DispatcherBuilderVisitor(rtype, newVersionTypeDescriptor, versionstamp); fileReader.accept(dispatcherVisitor, 0); return dispatcherVisitor.getBytes(); }
java
public static byte[] createFor(ReloadableType rtype, IncrementalTypeDescriptor newVersionTypeDescriptor, String versionstamp) { ClassReader fileReader = new ClassReader(rtype.interfaceBytes); DispatcherBuilderVisitor dispatcherVisitor = new DispatcherBuilderVisitor(rtype, newVersionTypeDescriptor, versionstamp); fileReader.accept(dispatcherVisitor, 0); return dispatcherVisitor.getBytes(); }
[ "public", "static", "byte", "[", "]", "createFor", "(", "ReloadableType", "rtype", ",", "IncrementalTypeDescriptor", "newVersionTypeDescriptor", ",", "String", "versionstamp", ")", "{", "ClassReader", "fileReader", "=", "new", "ClassReader", "(", "rtype", ".", "interfaceBytes", ")", ";", "DispatcherBuilderVisitor", "dispatcherVisitor", "=", "new", "DispatcherBuilderVisitor", "(", "rtype", ",", "newVersionTypeDescriptor", ",", "versionstamp", ")", ";", "fileReader", ".", "accept", "(", "dispatcherVisitor", ",", "0", ")", ";", "return", "dispatcherVisitor", ".", "getBytes", "(", ")", ";", "}" ]
Factory method that builds the dispatcher for a specified reloadabletype. @param rtype the reloadable type @param newVersionTypeDescriptor the descriptor of the new version (the executor will be generated according to this) @param versionstamp the suffix that should be appended to the generated dispatcher @return the bytecode for the new dispatcher
[ "Factory", "method", "that", "builds", "the", "dispatcher", "for", "a", "specified", "reloadabletype", "." ]
59b32f957a05c6d9f149148158053605e2a6205a
https://github.com/spring-projects/spring-loaded/blob/59b32f957a05c6d9f149148158053605e2a6205a/springloaded/src/main/java/org/springsource/loaded/DispatcherBuilder.java#L52-L59
26,434
spring-projects/spring-loaded
springloaded/src/main/java/org/springsource/loaded/FieldReaderWriter.java
FieldReaderWriter.setValue
public void setValue(Object instance, Object newValue, ISMgr stateManager) throws IllegalAccessException { if (typeDescriptor.isReloadable()) { if (stateManager == null) { // Look it up using reflection stateManager = findInstanceStateManager(instance); } String declaringTypeName = typeDescriptor.getName(); Map<String, Object> typeLevelValues = stateManager.getMap().get(declaringTypeName); if (typeLevelValues == null) { // first time we've accessed this type for an instance field typeLevelValues = new HashMap<String, Object>(); stateManager.getMap().put(declaringTypeName, typeLevelValues); } typeLevelValues.put(theField.getName(), newValue); } else { // the type is not reloadable, must use reflection to access the value // TODO generate get/set in the topmost reloader for these kinds of field and use them? if (typeDescriptor.isInterface()) { // field resolution has left us with an interface field, those can't be set like this throw new IncompatibleClassChangeError("Expected non-static field " + instance.getClass().getName() + "." + theField.getName()); } else { findAndSetFieldValueInHierarchy(instance, newValue); } } }
java
public void setValue(Object instance, Object newValue, ISMgr stateManager) throws IllegalAccessException { if (typeDescriptor.isReloadable()) { if (stateManager == null) { // Look it up using reflection stateManager = findInstanceStateManager(instance); } String declaringTypeName = typeDescriptor.getName(); Map<String, Object> typeLevelValues = stateManager.getMap().get(declaringTypeName); if (typeLevelValues == null) { // first time we've accessed this type for an instance field typeLevelValues = new HashMap<String, Object>(); stateManager.getMap().put(declaringTypeName, typeLevelValues); } typeLevelValues.put(theField.getName(), newValue); } else { // the type is not reloadable, must use reflection to access the value // TODO generate get/set in the topmost reloader for these kinds of field and use them? if (typeDescriptor.isInterface()) { // field resolution has left us with an interface field, those can't be set like this throw new IncompatibleClassChangeError("Expected non-static field " + instance.getClass().getName() + "." + theField.getName()); } else { findAndSetFieldValueInHierarchy(instance, newValue); } } }
[ "public", "void", "setValue", "(", "Object", "instance", ",", "Object", "newValue", ",", "ISMgr", "stateManager", ")", "throws", "IllegalAccessException", "{", "if", "(", "typeDescriptor", ".", "isReloadable", "(", ")", ")", "{", "if", "(", "stateManager", "==", "null", ")", "{", "// Look it up using reflection", "stateManager", "=", "findInstanceStateManager", "(", "instance", ")", ";", "}", "String", "declaringTypeName", "=", "typeDescriptor", ".", "getName", "(", ")", ";", "Map", "<", "String", ",", "Object", ">", "typeLevelValues", "=", "stateManager", ".", "getMap", "(", ")", ".", "get", "(", "declaringTypeName", ")", ";", "if", "(", "typeLevelValues", "==", "null", ")", "{", "// first time we've accessed this type for an instance field", "typeLevelValues", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "stateManager", ".", "getMap", "(", ")", ".", "put", "(", "declaringTypeName", ",", "typeLevelValues", ")", ";", "}", "typeLevelValues", ".", "put", "(", "theField", ".", "getName", "(", ")", ",", "newValue", ")", ";", "}", "else", "{", "// the type is not reloadable, must use reflection to access the value", "// TODO generate get/set in the topmost reloader for these kinds of field and use them?", "if", "(", "typeDescriptor", ".", "isInterface", "(", ")", ")", "{", "// field resolution has left us with an interface field, those can't be set like this", "throw", "new", "IncompatibleClassChangeError", "(", "\"Expected non-static field \"", "+", "instance", ".", "getClass", "(", ")", ".", "getName", "(", ")", "+", "\".\"", "+", "theField", ".", "getName", "(", ")", ")", ";", "}", "else", "{", "findAndSetFieldValueInHierarchy", "(", "instance", ",", "newValue", ")", ";", "}", "}", "}" ]
Set the value of an instance field on the specified instance to the specified value. If a state manager is passed in things can be done in a more optimal way, otherwise the state manager has to be discovered from the instance. @param instance the object instance upon which to set the field @param newValue the new value for that field @param stateManager the optional state manager for this instance, which will be looked up (expensive) if not passed in @throws IllegalAccessException if the field value cannot be set
[ "Set", "the", "value", "of", "an", "instance", "field", "on", "the", "specified", "instance", "to", "the", "specified", "value", ".", "If", "a", "state", "manager", "is", "passed", "in", "things", "can", "be", "done", "in", "a", "more", "optimal", "way", "otherwise", "the", "state", "manager", "has", "to", "be", "discovered", "from", "the", "instance", "." ]
59b32f957a05c6d9f149148158053605e2a6205a
https://github.com/spring-projects/spring-loaded/blob/59b32f957a05c6d9f149148158053605e2a6205a/springloaded/src/main/java/org/springsource/loaded/FieldReaderWriter.java#L63-L90
26,435
spring-projects/spring-loaded
springloaded/src/main/java/org/springsource/loaded/FieldReaderWriter.java
FieldReaderWriter.getValue
public Object getValue(Object instance, ISMgr stateManager) throws IllegalAccessException, IllegalArgumentException { Object result = null; String fieldname = theField.getName(); if (typeDescriptor.isReloadable()) { if (stateManager == null) { // find it using reflection stateManager = findInstanceStateManager(instance); } String declaringTypeName = typeDescriptor.getName(); Map<String, Object> typeLevelValues = stateManager.getMap().get(declaringTypeName); boolean knownField = false; if (typeLevelValues != null) { knownField = typeLevelValues.containsKey(fieldname); } if (knownField) { result = typeLevelValues.get(fieldname); } // If a field has been deleted it may 'reveal' a field in a supertype. The revealed field may be in a type // not yet dealt with. In this case typeLevelValues may be null (type not seen before) or the typelevelValues // may not have heard of our field name. In these cases we need to go and find the field and 'relocate' it // into our map, where it will be processed from now on. if (typeLevelValues == null || !knownField) { FieldMember fieldOnOriginalType = typeDescriptor.getReloadableType().getTypeRegistry() .getReloadableType(declaringTypeName).getTypeDescriptor().getField(fieldname); if (fieldOnOriginalType != null) { // Copy the field into the map - that is where it will live from now on ReloadableType rt = typeDescriptor.getReloadableType(); try { Field f = rt.getClazz().getDeclaredField(fieldname); f.setAccessible(true); result = f.get(instance); if (typeLevelValues == null) { typeLevelValues = new HashMap<String, Object>(); stateManager.getMap().put(declaringTypeName, typeLevelValues); } typeLevelValues.put(fieldname, result); } catch (Exception e) { throw new IllegalStateException("Unexpectedly unable to access field " + fieldname + " on class " + rt.getClazz(), e); } } else { // The field was not on the original type. As not seen before, can default it result = Utils.toResultCheckIfNull(null, theField.getDescriptor()); if (typeLevelValues == null) { typeLevelValues = new HashMap<String, Object>(); stateManager.getMap().put(declaringTypeName, typeLevelValues); } typeLevelValues.put(fieldname, result); return result; } } if (result != null) { result = Utils.checkCompatibility(typeDescriptor.getTypeRegistry(), result, theField.getDescriptor()); if (result == null) { // Was not compatible, forget it typeLevelValues.remove(fieldname); } } result = Utils.toResultCheckIfNull(result, theField.getDescriptor()); } else { // the type is not reloadable, must use reflection to access the value. // TODO measure how often we hit the reflection path, should never happen unless reflection is already on the frame if (typeDescriptor.isInterface()) { // cant be an instance field if it is found to be on an interface throw new IncompatibleClassChangeError("Expected non-static field " + instance.getClass().getName() + "." + fieldname); } else { result = findAndGetFieldValueInHierarchy(instance); } } if (GlobalConfiguration.isRuntimeLogging && log.isLoggable(Level.FINER)) { log.finer("<getValue() value of " + theField + " is " + result); } return result; }
java
public Object getValue(Object instance, ISMgr stateManager) throws IllegalAccessException, IllegalArgumentException { Object result = null; String fieldname = theField.getName(); if (typeDescriptor.isReloadable()) { if (stateManager == null) { // find it using reflection stateManager = findInstanceStateManager(instance); } String declaringTypeName = typeDescriptor.getName(); Map<String, Object> typeLevelValues = stateManager.getMap().get(declaringTypeName); boolean knownField = false; if (typeLevelValues != null) { knownField = typeLevelValues.containsKey(fieldname); } if (knownField) { result = typeLevelValues.get(fieldname); } // If a field has been deleted it may 'reveal' a field in a supertype. The revealed field may be in a type // not yet dealt with. In this case typeLevelValues may be null (type not seen before) or the typelevelValues // may not have heard of our field name. In these cases we need to go and find the field and 'relocate' it // into our map, where it will be processed from now on. if (typeLevelValues == null || !knownField) { FieldMember fieldOnOriginalType = typeDescriptor.getReloadableType().getTypeRegistry() .getReloadableType(declaringTypeName).getTypeDescriptor().getField(fieldname); if (fieldOnOriginalType != null) { // Copy the field into the map - that is where it will live from now on ReloadableType rt = typeDescriptor.getReloadableType(); try { Field f = rt.getClazz().getDeclaredField(fieldname); f.setAccessible(true); result = f.get(instance); if (typeLevelValues == null) { typeLevelValues = new HashMap<String, Object>(); stateManager.getMap().put(declaringTypeName, typeLevelValues); } typeLevelValues.put(fieldname, result); } catch (Exception e) { throw new IllegalStateException("Unexpectedly unable to access field " + fieldname + " on class " + rt.getClazz(), e); } } else { // The field was not on the original type. As not seen before, can default it result = Utils.toResultCheckIfNull(null, theField.getDescriptor()); if (typeLevelValues == null) { typeLevelValues = new HashMap<String, Object>(); stateManager.getMap().put(declaringTypeName, typeLevelValues); } typeLevelValues.put(fieldname, result); return result; } } if (result != null) { result = Utils.checkCompatibility(typeDescriptor.getTypeRegistry(), result, theField.getDescriptor()); if (result == null) { // Was not compatible, forget it typeLevelValues.remove(fieldname); } } result = Utils.toResultCheckIfNull(result, theField.getDescriptor()); } else { // the type is not reloadable, must use reflection to access the value. // TODO measure how often we hit the reflection path, should never happen unless reflection is already on the frame if (typeDescriptor.isInterface()) { // cant be an instance field if it is found to be on an interface throw new IncompatibleClassChangeError("Expected non-static field " + instance.getClass().getName() + "." + fieldname); } else { result = findAndGetFieldValueInHierarchy(instance); } } if (GlobalConfiguration.isRuntimeLogging && log.isLoggable(Level.FINER)) { log.finer("<getValue() value of " + theField + " is " + result); } return result; }
[ "public", "Object", "getValue", "(", "Object", "instance", ",", "ISMgr", "stateManager", ")", "throws", "IllegalAccessException", ",", "IllegalArgumentException", "{", "Object", "result", "=", "null", ";", "String", "fieldname", "=", "theField", ".", "getName", "(", ")", ";", "if", "(", "typeDescriptor", ".", "isReloadable", "(", ")", ")", "{", "if", "(", "stateManager", "==", "null", ")", "{", "// find it using reflection", "stateManager", "=", "findInstanceStateManager", "(", "instance", ")", ";", "}", "String", "declaringTypeName", "=", "typeDescriptor", ".", "getName", "(", ")", ";", "Map", "<", "String", ",", "Object", ">", "typeLevelValues", "=", "stateManager", ".", "getMap", "(", ")", ".", "get", "(", "declaringTypeName", ")", ";", "boolean", "knownField", "=", "false", ";", "if", "(", "typeLevelValues", "!=", "null", ")", "{", "knownField", "=", "typeLevelValues", ".", "containsKey", "(", "fieldname", ")", ";", "}", "if", "(", "knownField", ")", "{", "result", "=", "typeLevelValues", ".", "get", "(", "fieldname", ")", ";", "}", "// If a field has been deleted it may 'reveal' a field in a supertype. The revealed field may be in a type", "// not yet dealt with. In this case typeLevelValues may be null (type not seen before) or the typelevelValues", "// may not have heard of our field name. In these cases we need to go and find the field and 'relocate' it", "// into our map, where it will be processed from now on.", "if", "(", "typeLevelValues", "==", "null", "||", "!", "knownField", ")", "{", "FieldMember", "fieldOnOriginalType", "=", "typeDescriptor", ".", "getReloadableType", "(", ")", ".", "getTypeRegistry", "(", ")", ".", "getReloadableType", "(", "declaringTypeName", ")", ".", "getTypeDescriptor", "(", ")", ".", "getField", "(", "fieldname", ")", ";", "if", "(", "fieldOnOriginalType", "!=", "null", ")", "{", "// Copy the field into the map - that is where it will live from now on", "ReloadableType", "rt", "=", "typeDescriptor", ".", "getReloadableType", "(", ")", ";", "try", "{", "Field", "f", "=", "rt", ".", "getClazz", "(", ")", ".", "getDeclaredField", "(", "fieldname", ")", ";", "f", ".", "setAccessible", "(", "true", ")", ";", "result", "=", "f", ".", "get", "(", "instance", ")", ";", "if", "(", "typeLevelValues", "==", "null", ")", "{", "typeLevelValues", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "stateManager", ".", "getMap", "(", ")", ".", "put", "(", "declaringTypeName", ",", "typeLevelValues", ")", ";", "}", "typeLevelValues", ".", "put", "(", "fieldname", ",", "result", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "IllegalStateException", "(", "\"Unexpectedly unable to access field \"", "+", "fieldname", "+", "\" on class \"", "+", "rt", ".", "getClazz", "(", ")", ",", "e", ")", ";", "}", "}", "else", "{", "// The field was not on the original type. As not seen before, can default it", "result", "=", "Utils", ".", "toResultCheckIfNull", "(", "null", ",", "theField", ".", "getDescriptor", "(", ")", ")", ";", "if", "(", "typeLevelValues", "==", "null", ")", "{", "typeLevelValues", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "stateManager", ".", "getMap", "(", ")", ".", "put", "(", "declaringTypeName", ",", "typeLevelValues", ")", ";", "}", "typeLevelValues", ".", "put", "(", "fieldname", ",", "result", ")", ";", "return", "result", ";", "}", "}", "if", "(", "result", "!=", "null", ")", "{", "result", "=", "Utils", ".", "checkCompatibility", "(", "typeDescriptor", ".", "getTypeRegistry", "(", ")", ",", "result", ",", "theField", ".", "getDescriptor", "(", ")", ")", ";", "if", "(", "result", "==", "null", ")", "{", "// Was not compatible, forget it", "typeLevelValues", ".", "remove", "(", "fieldname", ")", ";", "}", "}", "result", "=", "Utils", ".", "toResultCheckIfNull", "(", "result", ",", "theField", ".", "getDescriptor", "(", ")", ")", ";", "}", "else", "{", "// the type is not reloadable, must use reflection to access the value.", "// TODO measure how often we hit the reflection path, should never happen unless reflection is already on the frame", "if", "(", "typeDescriptor", ".", "isInterface", "(", ")", ")", "{", "// cant be an instance field if it is found to be on an interface", "throw", "new", "IncompatibleClassChangeError", "(", "\"Expected non-static field \"", "+", "instance", ".", "getClass", "(", ")", ".", "getName", "(", ")", "+", "\".\"", "+", "fieldname", ")", ";", "}", "else", "{", "result", "=", "findAndGetFieldValueInHierarchy", "(", "instance", ")", ";", "}", "}", "if", "(", "GlobalConfiguration", ".", "isRuntimeLogging", "&&", "log", ".", "isLoggable", "(", "Level", ".", "FINER", ")", ")", "{", "log", ".", "finer", "(", "\"<getValue() value of \"", "+", "theField", "+", "\" is \"", "+", "result", ")", ";", "}", "return", "result", ";", "}" ]
Return the value of the field for which is reader-writer exists. To improve performance a fieldAccessor can be supplied but if it is missing the code will go and discover it. @param instance the instance for which the field should be fetched @param stateManager an optional state manager containing the map of values (will be discovered if not supplied) @return the value of the field @throws IllegalAccessException if there is a problem accessing the field value
[ "Return", "the", "value", "of", "the", "field", "for", "which", "is", "reader", "-", "writer", "exists", ".", "To", "improve", "performance", "a", "fieldAccessor", "can", "be", "supplied", "but", "if", "it", "is", "missing", "the", "code", "will", "go", "and", "discover", "it", "." ]
59b32f957a05c6d9f149148158053605e2a6205a
https://github.com/spring-projects/spring-loaded/blob/59b32f957a05c6d9f149148158053605e2a6205a/springloaded/src/main/java/org/springsource/loaded/FieldReaderWriter.java#L136-L220
26,436
spring-projects/spring-loaded
springloaded/src/main/java/org/springsource/loaded/FieldReaderWriter.java
FieldReaderWriter.locateFieldByReflection
private Field locateFieldByReflection(Class<?> clazz, String typeWanted, boolean isInterface, String name) { if (clazz.getName().equals(typeWanted)) { Field[] fs = clazz.getDeclaredFields(); if (fs != null) { for (Field f : fs) { if (f.getName().equals(name)) { return f; } } } } // Check interfaces if (!isInterface) { // not worth looking! Class<?>[] interfaces = clazz.getInterfaces(); if (interfaces != null) { for (Class<?> intface : interfaces) { Field f = locateFieldByReflection(intface, typeWanted, isInterface, name); if (f != null) { return f; } } } } // Check superclass Class<?> superclass = clazz.getSuperclass(); if (superclass == null) { return null; } else { return locateFieldByReflection(superclass, typeWanted, isInterface, name); } }
java
private Field locateFieldByReflection(Class<?> clazz, String typeWanted, boolean isInterface, String name) { if (clazz.getName().equals(typeWanted)) { Field[] fs = clazz.getDeclaredFields(); if (fs != null) { for (Field f : fs) { if (f.getName().equals(name)) { return f; } } } } // Check interfaces if (!isInterface) { // not worth looking! Class<?>[] interfaces = clazz.getInterfaces(); if (interfaces != null) { for (Class<?> intface : interfaces) { Field f = locateFieldByReflection(intface, typeWanted, isInterface, name); if (f != null) { return f; } } } } // Check superclass Class<?> superclass = clazz.getSuperclass(); if (superclass == null) { return null; } else { return locateFieldByReflection(superclass, typeWanted, isInterface, name); } }
[ "private", "Field", "locateFieldByReflection", "(", "Class", "<", "?", ">", "clazz", ",", "String", "typeWanted", ",", "boolean", "isInterface", ",", "String", "name", ")", "{", "if", "(", "clazz", ".", "getName", "(", ")", ".", "equals", "(", "typeWanted", ")", ")", "{", "Field", "[", "]", "fs", "=", "clazz", ".", "getDeclaredFields", "(", ")", ";", "if", "(", "fs", "!=", "null", ")", "{", "for", "(", "Field", "f", ":", "fs", ")", "{", "if", "(", "f", ".", "getName", "(", ")", ".", "equals", "(", "name", ")", ")", "{", "return", "f", ";", "}", "}", "}", "}", "// Check interfaces", "if", "(", "!", "isInterface", ")", "{", "// not worth looking!", "Class", "<", "?", ">", "[", "]", "interfaces", "=", "clazz", ".", "getInterfaces", "(", ")", ";", "if", "(", "interfaces", "!=", "null", ")", "{", "for", "(", "Class", "<", "?", ">", "intface", ":", "interfaces", ")", "{", "Field", "f", "=", "locateFieldByReflection", "(", "intface", ",", "typeWanted", ",", "isInterface", ",", "name", ")", ";", "if", "(", "f", "!=", "null", ")", "{", "return", "f", ";", "}", "}", "}", "}", "// Check superclass", "Class", "<", "?", ">", "superclass", "=", "clazz", ".", "getSuperclass", "(", ")", ";", "if", "(", "superclass", "==", "null", ")", "{", "return", "null", ";", "}", "else", "{", "return", "locateFieldByReflection", "(", "superclass", ",", "typeWanted", ",", "isInterface", ",", "name", ")", ";", "}", "}" ]
Discover the named field in the hierarchy using the standard rules of resolution. @param clazz the class upon which to start looking @param typeWanted where the field is! @param name the name of the field to find @return the jlrField object representing that field, or null if not found
[ "Discover", "the", "named", "field", "in", "the", "hierarchy", "using", "the", "standard", "rules", "of", "resolution", "." ]
59b32f957a05c6d9f149148158053605e2a6205a
https://github.com/spring-projects/spring-loaded/blob/59b32f957a05c6d9f149148158053605e2a6205a/springloaded/src/main/java/org/springsource/loaded/FieldReaderWriter.java#L343-L374
26,437
spring-projects/spring-loaded
springloaded/src/main/java/org/springsource/loaded/FieldReaderWriter.java
FieldReaderWriter.findInstanceStateManager
private ISMgr findInstanceStateManager(Object instance) { Class<?> clazz = typeDescriptor.getReloadableType().getClazz(); try { Field fieldAccessorField = clazz.getField(Constants.fInstanceFieldsName); if (fieldAccessorField == null) { throw new IllegalStateException("Cant find field accessor for type " + clazz.getName()); } ISMgr stateManager = (ISMgr) fieldAccessorField.get(instance); if (stateManager == null) { // Looks to not have been initialized yet, this can happen if a non standard ctor was used. // We could push this step into the generated ctors... ISMgr instanceStateManager = new ISMgr(instance, typeDescriptor.getReloadableType()); fieldAccessorField.set(instance, instanceStateManager); stateManager = (ISMgr) fieldAccessorField.get(instance); // For some reason it didn't stick! if (stateManager == null) { throw new IllegalStateException("The class '" + clazz.getName() + "' has a null instance state manager object, instance is " + instance); } } return stateManager; } catch (Exception e) { throw new IllegalStateException("Unexpectedly unable to find instance state manager on class " + clazz.getName(), e); } }
java
private ISMgr findInstanceStateManager(Object instance) { Class<?> clazz = typeDescriptor.getReloadableType().getClazz(); try { Field fieldAccessorField = clazz.getField(Constants.fInstanceFieldsName); if (fieldAccessorField == null) { throw new IllegalStateException("Cant find field accessor for type " + clazz.getName()); } ISMgr stateManager = (ISMgr) fieldAccessorField.get(instance); if (stateManager == null) { // Looks to not have been initialized yet, this can happen if a non standard ctor was used. // We could push this step into the generated ctors... ISMgr instanceStateManager = new ISMgr(instance, typeDescriptor.getReloadableType()); fieldAccessorField.set(instance, instanceStateManager); stateManager = (ISMgr) fieldAccessorField.get(instance); // For some reason it didn't stick! if (stateManager == null) { throw new IllegalStateException("The class '" + clazz.getName() + "' has a null instance state manager object, instance is " + instance); } } return stateManager; } catch (Exception e) { throw new IllegalStateException("Unexpectedly unable to find instance state manager on class " + clazz.getName(), e); } }
[ "private", "ISMgr", "findInstanceStateManager", "(", "Object", "instance", ")", "{", "Class", "<", "?", ">", "clazz", "=", "typeDescriptor", ".", "getReloadableType", "(", ")", ".", "getClazz", "(", ")", ";", "try", "{", "Field", "fieldAccessorField", "=", "clazz", ".", "getField", "(", "Constants", ".", "fInstanceFieldsName", ")", ";", "if", "(", "fieldAccessorField", "==", "null", ")", "{", "throw", "new", "IllegalStateException", "(", "\"Cant find field accessor for type \"", "+", "clazz", ".", "getName", "(", ")", ")", ";", "}", "ISMgr", "stateManager", "=", "(", "ISMgr", ")", "fieldAccessorField", ".", "get", "(", "instance", ")", ";", "if", "(", "stateManager", "==", "null", ")", "{", "// Looks to not have been initialized yet, this can happen if a non standard ctor was used.", "// We could push this step into the generated ctors...", "ISMgr", "instanceStateManager", "=", "new", "ISMgr", "(", "instance", ",", "typeDescriptor", ".", "getReloadableType", "(", ")", ")", ";", "fieldAccessorField", ".", "set", "(", "instance", ",", "instanceStateManager", ")", ";", "stateManager", "=", "(", "ISMgr", ")", "fieldAccessorField", ".", "get", "(", "instance", ")", ";", "// For some reason it didn't stick!", "if", "(", "stateManager", "==", "null", ")", "{", "throw", "new", "IllegalStateException", "(", "\"The class '\"", "+", "clazz", ".", "getName", "(", ")", "+", "\"' has a null instance state manager object, instance is \"", "+", "instance", ")", ";", "}", "}", "return", "stateManager", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "IllegalStateException", "(", "\"Unexpectedly unable to find instance state manager on class \"", "+", "clazz", ".", "getName", "(", ")", ",", "e", ")", ";", "}", "}" ]
Discover the instance state manager for the specific object instance. Will fail by exception rather than returning null. @param instance the object instance on which to look @return the discovered state manager
[ "Discover", "the", "instance", "state", "manager", "for", "the", "specific", "object", "instance", ".", "Will", "fail", "by", "exception", "rather", "than", "returning", "null", "." ]
59b32f957a05c6d9f149148158053605e2a6205a
https://github.com/spring-projects/spring-loaded/blob/59b32f957a05c6d9f149148158053605e2a6205a/springloaded/src/main/java/org/springsource/loaded/FieldReaderWriter.java#L383-L409
26,438
spring-projects/spring-loaded
springloaded/src/main/java/org/springsource/loaded/FieldReaderWriter.java
FieldReaderWriter.findStaticStateManager
private SSMgr findStaticStateManager(Class<?> clazz) { try { Field stateManagerField = clazz.getField(Constants.fStaticFieldsName); if (stateManagerField == null) { throw new IllegalStateException("Cant find field accessor for type " + typeDescriptor.getReloadableType().getName()); } SSMgr stateManager = (SSMgr) stateManagerField.get(null); // Field should always have been initialized - it is done at the start of the top most reloadable type <clinit> if (stateManager == null) { throw new IllegalStateException("Instance of this class has no state manager: " + clazz.getName()); } return stateManager; } catch (Exception e) { throw new IllegalStateException("Unexpectedly unable to find static state manager on class " + clazz.getName(), e); } }
java
private SSMgr findStaticStateManager(Class<?> clazz) { try { Field stateManagerField = clazz.getField(Constants.fStaticFieldsName); if (stateManagerField == null) { throw new IllegalStateException("Cant find field accessor for type " + typeDescriptor.getReloadableType().getName()); } SSMgr stateManager = (SSMgr) stateManagerField.get(null); // Field should always have been initialized - it is done at the start of the top most reloadable type <clinit> if (stateManager == null) { throw new IllegalStateException("Instance of this class has no state manager: " + clazz.getName()); } return stateManager; } catch (Exception e) { throw new IllegalStateException("Unexpectedly unable to find static state manager on class " + clazz.getName(), e); } }
[ "private", "SSMgr", "findStaticStateManager", "(", "Class", "<", "?", ">", "clazz", ")", "{", "try", "{", "Field", "stateManagerField", "=", "clazz", ".", "getField", "(", "Constants", ".", "fStaticFieldsName", ")", ";", "if", "(", "stateManagerField", "==", "null", ")", "{", "throw", "new", "IllegalStateException", "(", "\"Cant find field accessor for type \"", "+", "typeDescriptor", ".", "getReloadableType", "(", ")", ".", "getName", "(", ")", ")", ";", "}", "SSMgr", "stateManager", "=", "(", "SSMgr", ")", "stateManagerField", ".", "get", "(", "null", ")", ";", "// Field should always have been initialized - it is done at the start of the top most reloadable type <clinit>", "if", "(", "stateManager", "==", "null", ")", "{", "throw", "new", "IllegalStateException", "(", "\"Instance of this class has no state manager: \"", "+", "clazz", ".", "getName", "(", ")", ")", ";", "}", "return", "stateManager", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "IllegalStateException", "(", "\"Unexpectedly unable to find static state manager on class \"", "+", "clazz", ".", "getName", "(", ")", ",", "e", ")", ";", "}", "}" ]
Discover the static state manager on the specified class and return it. Will fail by exception rather than returning null. @param clazz the class on which to look @return the discovered state manager
[ "Discover", "the", "static", "state", "manager", "on", "the", "specified", "class", "and", "return", "it", ".", "Will", "fail", "by", "exception", "rather", "than", "returning", "null", "." ]
59b32f957a05c6d9f149148158053605e2a6205a
https://github.com/spring-projects/spring-loaded/blob/59b32f957a05c6d9f149148158053605e2a6205a/springloaded/src/main/java/org/springsource/loaded/FieldReaderWriter.java#L418-L436
26,439
spring-projects/spring-loaded
springloaded/src/main/java/org/springsource/loaded/FieldReaderWriter.java
FieldReaderWriter.findAndGetFieldValueInHierarchy
private Object findAndGetFieldValueInHierarchy(Object instance) { Class<?> clazz = instance.getClass(); String fieldname = theField.getName(); String searchName = typeDescriptor.getName().replace('/', '.'); while (clazz != null && !clazz.getName().equals(searchName)) { clazz = clazz.getSuperclass(); } if (clazz == null) { throw new IllegalStateException("Failed to find " + searchName + " in hierarchy of " + instance.getClass()); } try { Field f = clazz.getDeclaredField(fieldname); f.setAccessible(true); return f.get(instance); } catch (Exception e) { throw new IllegalStateException("Unexpectedly could not access field named " + fieldname + " on class " + clazz.getName()); } }
java
private Object findAndGetFieldValueInHierarchy(Object instance) { Class<?> clazz = instance.getClass(); String fieldname = theField.getName(); String searchName = typeDescriptor.getName().replace('/', '.'); while (clazz != null && !clazz.getName().equals(searchName)) { clazz = clazz.getSuperclass(); } if (clazz == null) { throw new IllegalStateException("Failed to find " + searchName + " in hierarchy of " + instance.getClass()); } try { Field f = clazz.getDeclaredField(fieldname); f.setAccessible(true); return f.get(instance); } catch (Exception e) { throw new IllegalStateException("Unexpectedly could not access field named " + fieldname + " on class " + clazz.getName()); } }
[ "private", "Object", "findAndGetFieldValueInHierarchy", "(", "Object", "instance", ")", "{", "Class", "<", "?", ">", "clazz", "=", "instance", ".", "getClass", "(", ")", ";", "String", "fieldname", "=", "theField", ".", "getName", "(", ")", ";", "String", "searchName", "=", "typeDescriptor", ".", "getName", "(", ")", ".", "replace", "(", "'", "'", ",", "'", "'", ")", ";", "while", "(", "clazz", "!=", "null", "&&", "!", "clazz", ".", "getName", "(", ")", ".", "equals", "(", "searchName", ")", ")", "{", "clazz", "=", "clazz", ".", "getSuperclass", "(", ")", ";", "}", "if", "(", "clazz", "==", "null", ")", "{", "throw", "new", "IllegalStateException", "(", "\"Failed to find \"", "+", "searchName", "+", "\" in hierarchy of \"", "+", "instance", ".", "getClass", "(", ")", ")", ";", "}", "try", "{", "Field", "f", "=", "clazz", ".", "getDeclaredField", "(", "fieldname", ")", ";", "f", ".", "setAccessible", "(", "true", ")", ";", "return", "f", ".", "get", "(", "instance", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "IllegalStateException", "(", "\"Unexpectedly could not access field named \"", "+", "fieldname", "+", "\" on class \"", "+", "clazz", ".", "getName", "(", ")", ")", ";", "}", "}" ]
Walk up the instance hierarchy looking for the field, and when it is found access it and return the result. Will exit via exception if it cannot find the field or something goes wrong when accessing it. @param instance the object instance upon which the field is being accessed @return the value of the field
[ "Walk", "up", "the", "instance", "hierarchy", "looking", "for", "the", "field", "and", "when", "it", "is", "found", "access", "it", "and", "return", "the", "result", ".", "Will", "exit", "via", "exception", "if", "it", "cannot", "find", "the", "field", "or", "something", "goes", "wrong", "when", "accessing", "it", "." ]
59b32f957a05c6d9f149148158053605e2a6205a
https://github.com/spring-projects/spring-loaded/blob/59b32f957a05c6d9f149148158053605e2a6205a/springloaded/src/main/java/org/springsource/loaded/FieldReaderWriter.java#L449-L468
26,440
spring-projects/spring-loaded
springloaded/src/main/java/org/springsource/loaded/Utils.java
Utils.addCorrectReturnInstruction
public static void addCorrectReturnInstruction(MethodVisitor mv, ReturnType returnType, boolean createCast) { if (returnType.isPrimitive()) { char ch = returnType.descriptor.charAt(0); switch (ch) { case 'V': // void is treated as a special primitive mv.visitInsn(RETURN); break; case 'I': case 'Z': case 'S': case 'B': case 'C': mv.visitInsn(IRETURN); break; case 'F': mv.visitInsn(FRETURN); break; case 'D': mv.visitInsn(DRETURN); break; case 'J': mv.visitInsn(LRETURN); break; default: throw new IllegalArgumentException("Not supported for '" + ch + "'"); } } else { // either array or reference type if (GlobalConfiguration.assertsMode) { // Must not end with a ';' unless it starts with a '[' if (returnType.descriptor.endsWith(";") && !returnType.descriptor.startsWith("[")) { throw new IllegalArgumentException("Invalid signature of '" + returnType.descriptor + "'"); } } if (createCast) { mv.visitTypeInsn(CHECKCAST, returnType.descriptor); } mv.visitInsn(ARETURN); } }
java
public static void addCorrectReturnInstruction(MethodVisitor mv, ReturnType returnType, boolean createCast) { if (returnType.isPrimitive()) { char ch = returnType.descriptor.charAt(0); switch (ch) { case 'V': // void is treated as a special primitive mv.visitInsn(RETURN); break; case 'I': case 'Z': case 'S': case 'B': case 'C': mv.visitInsn(IRETURN); break; case 'F': mv.visitInsn(FRETURN); break; case 'D': mv.visitInsn(DRETURN); break; case 'J': mv.visitInsn(LRETURN); break; default: throw new IllegalArgumentException("Not supported for '" + ch + "'"); } } else { // either array or reference type if (GlobalConfiguration.assertsMode) { // Must not end with a ';' unless it starts with a '[' if (returnType.descriptor.endsWith(";") && !returnType.descriptor.startsWith("[")) { throw new IllegalArgumentException("Invalid signature of '" + returnType.descriptor + "'"); } } if (createCast) { mv.visitTypeInsn(CHECKCAST, returnType.descriptor); } mv.visitInsn(ARETURN); } }
[ "public", "static", "void", "addCorrectReturnInstruction", "(", "MethodVisitor", "mv", ",", "ReturnType", "returnType", ",", "boolean", "createCast", ")", "{", "if", "(", "returnType", ".", "isPrimitive", "(", ")", ")", "{", "char", "ch", "=", "returnType", ".", "descriptor", ".", "charAt", "(", "0", ")", ";", "switch", "(", "ch", ")", "{", "case", "'", "'", ":", "// void is treated as a special primitive", "mv", ".", "visitInsn", "(", "RETURN", ")", ";", "break", ";", "case", "'", "'", ":", "case", "'", "'", ":", "case", "'", "'", ":", "case", "'", "'", ":", "case", "'", "'", ":", "mv", ".", "visitInsn", "(", "IRETURN", ")", ";", "break", ";", "case", "'", "'", ":", "mv", ".", "visitInsn", "(", "FRETURN", ")", ";", "break", ";", "case", "'", "'", ":", "mv", ".", "visitInsn", "(", "DRETURN", ")", ";", "break", ";", "case", "'", "'", ":", "mv", ".", "visitInsn", "(", "LRETURN", ")", ";", "break", ";", "default", ":", "throw", "new", "IllegalArgumentException", "(", "\"Not supported for '\"", "+", "ch", "+", "\"'\"", ")", ";", "}", "}", "else", "{", "// either array or reference type", "if", "(", "GlobalConfiguration", ".", "assertsMode", ")", "{", "// Must not end with a ';' unless it starts with a '['", "if", "(", "returnType", ".", "descriptor", ".", "endsWith", "(", "\";\"", ")", "&&", "!", "returnType", ".", "descriptor", ".", "startsWith", "(", "\"[\"", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Invalid signature of '\"", "+", "returnType", ".", "descriptor", "+", "\"'\"", ")", ";", "}", "}", "if", "(", "createCast", ")", "{", "mv", ".", "visitTypeInsn", "(", "CHECKCAST", ",", "returnType", ".", "descriptor", ")", ";", "}", "mv", ".", "visitInsn", "(", "ARETURN", ")", ";", "}", "}" ]
Depending on the signature of the return type, add the appropriate instructions to the method visitor. @param mv where to visit to append the instructions @param returnType return type descriptor @param createCast whether to include CHECKCAST instructions for return type values
[ "Depending", "on", "the", "signature", "of", "the", "return", "type", "add", "the", "appropriate", "instructions", "to", "the", "method", "visitor", "." ]
59b32f957a05c6d9f149148158053605e2a6205a
https://github.com/spring-projects/spring-loaded/blob/59b32f957a05c6d9f149148158053605e2a6205a/springloaded/src/main/java/org/springsource/loaded/Utils.java#L113-L153
26,441
spring-projects/spring-loaded
springloaded/src/main/java/org/springsource/loaded/Utils.java
Utils.getParameterCount
public static int getParameterCount(String methodDescriptor) { int pos = 1; // after the '(' int count = 0; char ch; while ((ch = methodDescriptor.charAt(pos)) != ')') { // Either 'L' or '[' or primitive if (ch == 'L') { // skip to ';' pos = methodDescriptor.indexOf(';', pos + 1); } else if (ch == '[') { while (methodDescriptor.charAt(++pos) == '[') { } if (methodDescriptor.charAt(pos) == 'L') { // reference array like [[Ljava/lang/String; pos = methodDescriptor.indexOf(';', pos + 1); } } count++; pos++; } return count; }
java
public static int getParameterCount(String methodDescriptor) { int pos = 1; // after the '(' int count = 0; char ch; while ((ch = methodDescriptor.charAt(pos)) != ')') { // Either 'L' or '[' or primitive if (ch == 'L') { // skip to ';' pos = methodDescriptor.indexOf(';', pos + 1); } else if (ch == '[') { while (methodDescriptor.charAt(++pos) == '[') { } if (methodDescriptor.charAt(pos) == 'L') { // reference array like [[Ljava/lang/String; pos = methodDescriptor.indexOf(';', pos + 1); } } count++; pos++; } return count; }
[ "public", "static", "int", "getParameterCount", "(", "String", "methodDescriptor", ")", "{", "int", "pos", "=", "1", ";", "// after the '('", "int", "count", "=", "0", ";", "char", "ch", ";", "while", "(", "(", "ch", "=", "methodDescriptor", ".", "charAt", "(", "pos", ")", ")", "!=", "'", "'", ")", "{", "// Either 'L' or '[' or primitive", "if", "(", "ch", "==", "'", "'", ")", "{", "// skip to ';'", "pos", "=", "methodDescriptor", ".", "indexOf", "(", "'", "'", ",", "pos", "+", "1", ")", ";", "}", "else", "if", "(", "ch", "==", "'", "'", ")", "{", "while", "(", "methodDescriptor", ".", "charAt", "(", "++", "pos", ")", "==", "'", "'", ")", "{", "}", "if", "(", "methodDescriptor", ".", "charAt", "(", "pos", ")", "==", "'", "'", ")", "{", "// reference array like [[Ljava/lang/String;", "pos", "=", "methodDescriptor", ".", "indexOf", "(", "'", "'", ",", "pos", "+", "1", ")", ";", "}", "}", "count", "++", ";", "pos", "++", ";", "}", "return", "count", ";", "}" ]
Return the number of parameters in the descriptor. Copes with primitives and arrays and reference types. @param methodDescriptor a method descriptor of the form (Ljava/lang/String;I[[Z)I @return number of parameters in the descriptor
[ "Return", "the", "number", "of", "parameters", "in", "the", "descriptor", ".", "Copes", "with", "primitives", "and", "arrays", "and", "reference", "types", "." ]
59b32f957a05c6d9f149148158053605e2a6205a
https://github.com/spring-projects/spring-loaded/blob/59b32f957a05c6d9f149148158053605e2a6205a/springloaded/src/main/java/org/springsource/loaded/Utils.java#L161-L183
26,442
spring-projects/spring-loaded
springloaded/src/main/java/org/springsource/loaded/Utils.java
Utils.createLoadsBasedOnDescriptor
public static void createLoadsBasedOnDescriptor(MethodVisitor mv, String descriptor, int startindex) { int slot = startindex; int descriptorpos = 1; // start after the '(' char ch; while ((ch = descriptor.charAt(descriptorpos)) != ')') { switch (ch) { case '[': mv.visitVarInsn(ALOAD, slot); slot++; // jump to end of array, could be [[[[I while (descriptor.charAt(++descriptorpos) == '[') { } if (descriptor.charAt(descriptorpos) == 'L') { descriptorpos = descriptor.indexOf(';', descriptorpos) + 1; } else { // Just a primitive array descriptorpos++; } break; case 'L': mv.visitVarInsn(ALOAD, slot); slot++; // jump to end of 'L' signature descriptorpos = descriptor.indexOf(';', descriptorpos) + 1; break; case 'J': mv.visitVarInsn(LLOAD, slot); slot += 2; // double slotter descriptorpos++; break; case 'D': mv.visitVarInsn(DLOAD, slot); slot += 2; // double slotter descriptorpos++; break; case 'F': mv.visitVarInsn(FLOAD, slot); descriptorpos++; slot++; break; case 'I': case 'Z': case 'B': case 'C': case 'S': mv.visitVarInsn(ILOAD, slot); descriptorpos++; slot++; break; default: throw new IllegalStateException("Unexpected type in descriptor: " + ch); } } }
java
public static void createLoadsBasedOnDescriptor(MethodVisitor mv, String descriptor, int startindex) { int slot = startindex; int descriptorpos = 1; // start after the '(' char ch; while ((ch = descriptor.charAt(descriptorpos)) != ')') { switch (ch) { case '[': mv.visitVarInsn(ALOAD, slot); slot++; // jump to end of array, could be [[[[I while (descriptor.charAt(++descriptorpos) == '[') { } if (descriptor.charAt(descriptorpos) == 'L') { descriptorpos = descriptor.indexOf(';', descriptorpos) + 1; } else { // Just a primitive array descriptorpos++; } break; case 'L': mv.visitVarInsn(ALOAD, slot); slot++; // jump to end of 'L' signature descriptorpos = descriptor.indexOf(';', descriptorpos) + 1; break; case 'J': mv.visitVarInsn(LLOAD, slot); slot += 2; // double slotter descriptorpos++; break; case 'D': mv.visitVarInsn(DLOAD, slot); slot += 2; // double slotter descriptorpos++; break; case 'F': mv.visitVarInsn(FLOAD, slot); descriptorpos++; slot++; break; case 'I': case 'Z': case 'B': case 'C': case 'S': mv.visitVarInsn(ILOAD, slot); descriptorpos++; slot++; break; default: throw new IllegalStateException("Unexpected type in descriptor: " + ch); } } }
[ "public", "static", "void", "createLoadsBasedOnDescriptor", "(", "MethodVisitor", "mv", ",", "String", "descriptor", ",", "int", "startindex", ")", "{", "int", "slot", "=", "startindex", ";", "int", "descriptorpos", "=", "1", ";", "// start after the '('", "char", "ch", ";", "while", "(", "(", "ch", "=", "descriptor", ".", "charAt", "(", "descriptorpos", ")", ")", "!=", "'", "'", ")", "{", "switch", "(", "ch", ")", "{", "case", "'", "'", ":", "mv", ".", "visitVarInsn", "(", "ALOAD", ",", "slot", ")", ";", "slot", "++", ";", "// jump to end of array, could be [[[[I", "while", "(", "descriptor", ".", "charAt", "(", "++", "descriptorpos", ")", "==", "'", "'", ")", "{", "}", "if", "(", "descriptor", ".", "charAt", "(", "descriptorpos", ")", "==", "'", "'", ")", "{", "descriptorpos", "=", "descriptor", ".", "indexOf", "(", "'", "'", ",", "descriptorpos", ")", "+", "1", ";", "}", "else", "{", "// Just a primitive array", "descriptorpos", "++", ";", "}", "break", ";", "case", "'", "'", ":", "mv", ".", "visitVarInsn", "(", "ALOAD", ",", "slot", ")", ";", "slot", "++", ";", "// jump to end of 'L' signature", "descriptorpos", "=", "descriptor", ".", "indexOf", "(", "'", "'", ",", "descriptorpos", ")", "+", "1", ";", "break", ";", "case", "'", "'", ":", "mv", ".", "visitVarInsn", "(", "LLOAD", ",", "slot", ")", ";", "slot", "+=", "2", ";", "// double slotter", "descriptorpos", "++", ";", "break", ";", "case", "'", "'", ":", "mv", ".", "visitVarInsn", "(", "DLOAD", ",", "slot", ")", ";", "slot", "+=", "2", ";", "// double slotter", "descriptorpos", "++", ";", "break", ";", "case", "'", "'", ":", "mv", ".", "visitVarInsn", "(", "FLOAD", ",", "slot", ")", ";", "descriptorpos", "++", ";", "slot", "++", ";", "break", ";", "case", "'", "'", ":", "case", "'", "'", ":", "case", "'", "'", ":", "case", "'", "'", ":", "case", "'", "'", ":", "mv", ".", "visitVarInsn", "(", "ILOAD", ",", "slot", ")", ";", "descriptorpos", "++", ";", "slot", "++", ";", "break", ";", "default", ":", "throw", "new", "IllegalStateException", "(", "\"Unexpected type in descriptor: \"", "+", "ch", ")", ";", "}", "}", "}" ]
Create the set of LOAD instructions to load the method parameters. Take into account the size and type. @param mv the method visitor to recieve the load instructions @param descriptor the complete method descriptor (eg. "(ILjava/lang/String;)V") - params and return type are skipped @param startindex the initial index in which to assume the first parameter is stored
[ "Create", "the", "set", "of", "LOAD", "instructions", "to", "load", "the", "method", "parameters", ".", "Take", "into", "account", "the", "size", "and", "type", "." ]
59b32f957a05c6d9f149148158053605e2a6205a
https://github.com/spring-projects/spring-loaded/blob/59b32f957a05c6d9f149148158053605e2a6205a/springloaded/src/main/java/org/springsource/loaded/Utils.java#L193-L247
26,443
spring-projects/spring-loaded
springloaded/src/main/java/org/springsource/loaded/Utils.java
Utils.toParamClasses
public static Class<?>[] toParamClasses(String methodDescriptor, ClassLoader classLoader) throws ClassNotFoundException { Type[] paramTypes = Type.getArgumentTypes(methodDescriptor); Class<?>[] paramClasses = new Class<?>[paramTypes.length]; for (int i = 0; i < paramClasses.length; i++) { paramClasses[i] = toClass(paramTypes[i], classLoader); } return paramClasses; }
java
public static Class<?>[] toParamClasses(String methodDescriptor, ClassLoader classLoader) throws ClassNotFoundException { Type[] paramTypes = Type.getArgumentTypes(methodDescriptor); Class<?>[] paramClasses = new Class<?>[paramTypes.length]; for (int i = 0; i < paramClasses.length; i++) { paramClasses[i] = toClass(paramTypes[i], classLoader); } return paramClasses; }
[ "public", "static", "Class", "<", "?", ">", "[", "]", "toParamClasses", "(", "String", "methodDescriptor", ",", "ClassLoader", "classLoader", ")", "throws", "ClassNotFoundException", "{", "Type", "[", "]", "paramTypes", "=", "Type", ".", "getArgumentTypes", "(", "methodDescriptor", ")", ";", "Class", "<", "?", ">", "[", "]", "paramClasses", "=", "new", "Class", "<", "?", ">", "[", "paramTypes", ".", "length", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "paramClasses", ".", "length", ";", "i", "++", ")", "{", "paramClasses", "[", "i", "]", "=", "toClass", "(", "paramTypes", "[", "i", "]", ",", "classLoader", ")", ";", "}", "return", "paramClasses", ";", "}" ]
Given a method descriptor, extract the parameter descriptor and convert into corresponding Class objects. This requires a reference to a class loader to convert type names into Class objects. @param methodDescriptor a method descriptor (e.g (Ljava/lang/String;)I) @param classLoader a class loader that can be used to lookup types @return an array for classes representing the types in the method descriptor @throws ClassNotFoundException if there is a problem finding the Class for a particular name in the descriptor
[ "Given", "a", "method", "descriptor", "extract", "the", "parameter", "descriptor", "and", "convert", "into", "corresponding", "Class", "objects", ".", "This", "requires", "a", "reference", "to", "a", "class", "loader", "to", "convert", "type", "names", "into", "Class", "objects", "." ]
59b32f957a05c6d9f149148158053605e2a6205a
https://github.com/spring-projects/spring-loaded/blob/59b32f957a05c6d9f149148158053605e2a6205a/springloaded/src/main/java/org/springsource/loaded/Utils.java#L624-L632
26,444
spring-projects/spring-loaded
springloaded/src/main/java/org/springsource/loaded/Utils.java
Utils.toClass
public static Class<?> toClass(Type type, ClassLoader classLoader) throws ClassNotFoundException { switch (type.getSort()) { case Type.VOID: return void.class; case Type.BOOLEAN: return boolean.class; case Type.CHAR: return char.class; case Type.BYTE: return byte.class; case Type.SHORT: return short.class; case Type.INT: return int.class; case Type.FLOAT: return float.class; case Type.LONG: return long.class; case Type.DOUBLE: return double.class; case Type.ARRAY: Class<?> clazz = toClass(type.getElementType(), classLoader); return Array.newInstance(clazz, 0).getClass(); default: // case OBJECT: return Class.forName(type.getClassName(), false, classLoader); } }
java
public static Class<?> toClass(Type type, ClassLoader classLoader) throws ClassNotFoundException { switch (type.getSort()) { case Type.VOID: return void.class; case Type.BOOLEAN: return boolean.class; case Type.CHAR: return char.class; case Type.BYTE: return byte.class; case Type.SHORT: return short.class; case Type.INT: return int.class; case Type.FLOAT: return float.class; case Type.LONG: return long.class; case Type.DOUBLE: return double.class; case Type.ARRAY: Class<?> clazz = toClass(type.getElementType(), classLoader); return Array.newInstance(clazz, 0).getClass(); default: // case OBJECT: return Class.forName(type.getClassName(), false, classLoader); } }
[ "public", "static", "Class", "<", "?", ">", "toClass", "(", "Type", "type", ",", "ClassLoader", "classLoader", ")", "throws", "ClassNotFoundException", "{", "switch", "(", "type", ".", "getSort", "(", ")", ")", "{", "case", "Type", ".", "VOID", ":", "return", "void", ".", "class", ";", "case", "Type", ".", "BOOLEAN", ":", "return", "boolean", ".", "class", ";", "case", "Type", ".", "CHAR", ":", "return", "char", ".", "class", ";", "case", "Type", ".", "BYTE", ":", "return", "byte", ".", "class", ";", "case", "Type", ".", "SHORT", ":", "return", "short", ".", "class", ";", "case", "Type", ".", "INT", ":", "return", "int", ".", "class", ";", "case", "Type", ".", "FLOAT", ":", "return", "float", ".", "class", ";", "case", "Type", ".", "LONG", ":", "return", "long", ".", "class", ";", "case", "Type", ".", "DOUBLE", ":", "return", "double", ".", "class", ";", "case", "Type", ".", "ARRAY", ":", "Class", "<", "?", ">", "clazz", "=", "toClass", "(", "type", ".", "getElementType", "(", ")", ",", "classLoader", ")", ";", "return", "Array", ".", "newInstance", "(", "clazz", ",", "0", ")", ".", "getClass", "(", ")", ";", "default", ":", "// case OBJECT:", "return", "Class", ".", "forName", "(", "type", ".", "getClassName", "(", ")", ",", "false", ",", "classLoader", ")", ";", "}", "}" ]
Convert an asm Type into a corresponding Class object, requires a reference to a ClassLoader to be able to convert classnames to class objects. @param type the asm Type @param classLoader a class loader that can be used to find types @return the JVM Class for the type @throws ClassNotFoundException if there is a problem finding the Class for the type
[ "Convert", "an", "asm", "Type", "into", "a", "corresponding", "Class", "object", "requires", "a", "reference", "to", "a", "ClassLoader", "to", "be", "able", "to", "convert", "classnames", "to", "class", "objects", "." ]
59b32f957a05c6d9f149148158053605e2a6205a
https://github.com/spring-projects/spring-loaded/blob/59b32f957a05c6d9f149148158053605e2a6205a/springloaded/src/main/java/org/springsource/loaded/Utils.java#L643-L670
26,445
spring-projects/spring-loaded
springloaded/src/main/java/org/springsource/loaded/Utils.java
Utils.toPaddedNumber
public static String toPaddedNumber(int value, int width) { StringBuilder s = new StringBuilder("00000000").append(Integer.toString(value)); return s.substring(s.length() - width); }
java
public static String toPaddedNumber(int value, int width) { StringBuilder s = new StringBuilder("00000000").append(Integer.toString(value)); return s.substring(s.length() - width); }
[ "public", "static", "String", "toPaddedNumber", "(", "int", "value", ",", "int", "width", ")", "{", "StringBuilder", "s", "=", "new", "StringBuilder", "(", "\"00000000\"", ")", ".", "append", "(", "Integer", ".", "toString", "(", "value", ")", ")", ";", "return", "s", ".", "substring", "(", "s", ".", "length", "(", ")", "-", "width", ")", ";", "}" ]
Create the string representation of an integer and pad it to a particular width using leading zeroes. @param value the value to convert to a string @param width the width (in chars) that the resultant string should be @return the padded string
[ "Create", "the", "string", "representation", "of", "an", "integer", "and", "pad", "it", "to", "a", "particular", "width", "using", "leading", "zeroes", "." ]
59b32f957a05c6d9f149148158053605e2a6205a
https://github.com/spring-projects/spring-loaded/blob/59b32f957a05c6d9f149148158053605e2a6205a/springloaded/src/main/java/org/springsource/loaded/Utils.java#L753-L756
26,446
spring-projects/spring-loaded
springloaded/src/main/java/org/springsource/loaded/Utils.java
Utils.loadBytesFromStream
public static byte[] loadBytesFromStream(InputStream stream) { try { BufferedInputStream bis = new BufferedInputStream(stream); byte[] theData = new byte[10000000]; int dataReadSoFar = 0; byte[] buffer = new byte[1024]; int read = 0; while ((read = bis.read(buffer)) != -1) { System.arraycopy(buffer, 0, theData, dataReadSoFar, read); dataReadSoFar += read; } bis.close(); // Resize to actual data read byte[] returnData = new byte[dataReadSoFar]; System.arraycopy(theData, 0, returnData, 0, dataReadSoFar); return returnData; } catch (IOException e) { throw new RuntimeException(e); } }
java
public static byte[] loadBytesFromStream(InputStream stream) { try { BufferedInputStream bis = new BufferedInputStream(stream); byte[] theData = new byte[10000000]; int dataReadSoFar = 0; byte[] buffer = new byte[1024]; int read = 0; while ((read = bis.read(buffer)) != -1) { System.arraycopy(buffer, 0, theData, dataReadSoFar, read); dataReadSoFar += read; } bis.close(); // Resize to actual data read byte[] returnData = new byte[dataReadSoFar]; System.arraycopy(theData, 0, returnData, 0, dataReadSoFar); return returnData; } catch (IOException e) { throw new RuntimeException(e); } }
[ "public", "static", "byte", "[", "]", "loadBytesFromStream", "(", "InputStream", "stream", ")", "{", "try", "{", "BufferedInputStream", "bis", "=", "new", "BufferedInputStream", "(", "stream", ")", ";", "byte", "[", "]", "theData", "=", "new", "byte", "[", "10000000", "]", ";", "int", "dataReadSoFar", "=", "0", ";", "byte", "[", "]", "buffer", "=", "new", "byte", "[", "1024", "]", ";", "int", "read", "=", "0", ";", "while", "(", "(", "read", "=", "bis", ".", "read", "(", "buffer", ")", ")", "!=", "-", "1", ")", "{", "System", ".", "arraycopy", "(", "buffer", ",", "0", ",", "theData", ",", "dataReadSoFar", ",", "read", ")", ";", "dataReadSoFar", "+=", "read", ";", "}", "bis", ".", "close", "(", ")", ";", "// Resize to actual data read", "byte", "[", "]", "returnData", "=", "new", "byte", "[", "dataReadSoFar", "]", ";", "System", ".", "arraycopy", "(", "theData", ",", "0", ",", "returnData", ",", "0", ",", "dataReadSoFar", ")", ";", "return", "returnData", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "}" ]
Load all the byte data from an input stream. @param stream the input stream from which to read @return a byte array containing all the data from the stream
[ "Load", "all", "the", "byte", "data", "from", "an", "input", "stream", "." ]
59b32f957a05c6d9f149148158053605e2a6205a
https://github.com/spring-projects/spring-loaded/blob/59b32f957a05c6d9f149148158053605e2a6205a/springloaded/src/main/java/org/springsource/loaded/Utils.java#L841-L861
26,447
spring-projects/spring-loaded
springloaded/src/main/java/org/springsource/loaded/Utils.java
Utils.sizeOf
public static int sizeOf(String typeDescriptor) { if (typeDescriptor.length() != 1) { return 1; } char ch = typeDescriptor.charAt(0); if (ch == 'J' || ch == 'D') { return 2; } else { return 1; } }
java
public static int sizeOf(String typeDescriptor) { if (typeDescriptor.length() != 1) { return 1; } char ch = typeDescriptor.charAt(0); if (ch == 'J' || ch == 'D') { return 2; } else { return 1; } }
[ "public", "static", "int", "sizeOf", "(", "String", "typeDescriptor", ")", "{", "if", "(", "typeDescriptor", ".", "length", "(", ")", "!=", "1", ")", "{", "return", "1", ";", "}", "char", "ch", "=", "typeDescriptor", ".", "charAt", "(", "0", ")", ";", "if", "(", "ch", "==", "'", "'", "||", "ch", "==", "'", "'", ")", "{", "return", "2", ";", "}", "else", "{", "return", "1", ";", "}", "}" ]
Return the size of a type. The size is usually 1 except for double and long which are of size 2. The descriptor passed in is the full descriptor, including any leading 'L' and trailing ';'. @param typeDescriptor the descriptor for a single type, may be primitive. For example: I, J, Z, Ljava/lang/String; @return the size of the descriptor (number of slots it will consume), either 1 or 2
[ "Return", "the", "size", "of", "a", "type", ".", "The", "size", "is", "usually", "1", "except", "for", "double", "and", "long", "which", "are", "of", "size", "2", ".", "The", "descriptor", "passed", "in", "is", "the", "full", "descriptor", "including", "any", "leading", "L", "and", "trailing", ";", "." ]
59b32f957a05c6d9f149148158053605e2a6205a
https://github.com/spring-projects/spring-loaded/blob/59b32f957a05c6d9f149148158053605e2a6205a/springloaded/src/main/java/org/springsource/loaded/Utils.java#L1181-L1192
26,448
spring-projects/spring-loaded
springloaded/src/main/java/org/springsource/loaded/Utils.java
Utils.dumpClass
public static void dumpClass(String file, byte[] bytes) { File f = new File(file); try { FileOutputStream fos = new FileOutputStream(f); fos.write(bytes); fos.flush(); fos.close(); } catch (IOException ioe) { ioe.printStackTrace(); } }
java
public static void dumpClass(String file, byte[] bytes) { File f = new File(file); try { FileOutputStream fos = new FileOutputStream(f); fos.write(bytes); fos.flush(); fos.close(); } catch (IOException ioe) { ioe.printStackTrace(); } }
[ "public", "static", "void", "dumpClass", "(", "String", "file", ",", "byte", "[", "]", "bytes", ")", "{", "File", "f", "=", "new", "File", "(", "file", ")", ";", "try", "{", "FileOutputStream", "fos", "=", "new", "FileOutputStream", "(", "f", ")", ";", "fos", ".", "write", "(", "bytes", ")", ";", "fos", ".", "flush", "(", ")", ";", "fos", ".", "close", "(", ")", ";", "}", "catch", "(", "IOException", "ioe", ")", "{", "ioe", ".", "printStackTrace", "(", ")", ";", "}", "}" ]
Dump some bytes into the specified file. @param file full filename for where to dump the stuff (e.g. c:/temp/Foo.class) @param bytes the bytes to write to the file
[ "Dump", "some", "bytes", "into", "the", "specified", "file", "." ]
59b32f957a05c6d9f149148158053605e2a6205a
https://github.com/spring-projects/spring-loaded/blob/59b32f957a05c6d9f149148158053605e2a6205a/springloaded/src/main/java/org/springsource/loaded/Utils.java#L1200-L1211
26,449
spring-projects/spring-loaded
springloaded/src/main/java/org/springsource/loaded/Utils.java
Utils.getSize
public static int getSize(String descriptor) { int size = 0; int descriptorpos = 1; // start after the '(' char ch; while ((ch = descriptor.charAt(descriptorpos)) != ')') { switch (ch) { case '[': size++; // jump to end of array, could be [[[[I while (descriptor.charAt(++descriptorpos) == '[') { ; } if (descriptor.charAt(descriptorpos) == 'L') { descriptorpos = descriptor.indexOf(';', descriptorpos) + 1; } else { // Just a primitive array descriptorpos++; } break; case 'L': size++; // jump to end of 'L' signature descriptorpos = descriptor.indexOf(';', descriptorpos) + 1; break; case 'J': size = size + 2; descriptorpos++; break; case 'D': size = size + 2; descriptorpos++; break; case 'F': case 'B': case 'S': case 'I': case 'Z': case 'C': size++; descriptorpos++; break; default: throw new IllegalStateException("Unexpected character in descriptor: " + ch); } } return size; }
java
public static int getSize(String descriptor) { int size = 0; int descriptorpos = 1; // start after the '(' char ch; while ((ch = descriptor.charAt(descriptorpos)) != ')') { switch (ch) { case '[': size++; // jump to end of array, could be [[[[I while (descriptor.charAt(++descriptorpos) == '[') { ; } if (descriptor.charAt(descriptorpos) == 'L') { descriptorpos = descriptor.indexOf(';', descriptorpos) + 1; } else { // Just a primitive array descriptorpos++; } break; case 'L': size++; // jump to end of 'L' signature descriptorpos = descriptor.indexOf(';', descriptorpos) + 1; break; case 'J': size = size + 2; descriptorpos++; break; case 'D': size = size + 2; descriptorpos++; break; case 'F': case 'B': case 'S': case 'I': case 'Z': case 'C': size++; descriptorpos++; break; default: throw new IllegalStateException("Unexpected character in descriptor: " + ch); } } return size; }
[ "public", "static", "int", "getSize", "(", "String", "descriptor", ")", "{", "int", "size", "=", "0", ";", "int", "descriptorpos", "=", "1", ";", "// start after the '('", "char", "ch", ";", "while", "(", "(", "ch", "=", "descriptor", ".", "charAt", "(", "descriptorpos", ")", ")", "!=", "'", "'", ")", "{", "switch", "(", "ch", ")", "{", "case", "'", "'", ":", "size", "++", ";", "// jump to end of array, could be [[[[I", "while", "(", "descriptor", ".", "charAt", "(", "++", "descriptorpos", ")", "==", "'", "'", ")", "{", ";", "}", "if", "(", "descriptor", ".", "charAt", "(", "descriptorpos", ")", "==", "'", "'", ")", "{", "descriptorpos", "=", "descriptor", ".", "indexOf", "(", "'", "'", ",", "descriptorpos", ")", "+", "1", ";", "}", "else", "{", "// Just a primitive array", "descriptorpos", "++", ";", "}", "break", ";", "case", "'", "'", ":", "size", "++", ";", "// jump to end of 'L' signature", "descriptorpos", "=", "descriptor", ".", "indexOf", "(", "'", "'", ",", "descriptorpos", ")", "+", "1", ";", "break", ";", "case", "'", "'", ":", "size", "=", "size", "+", "2", ";", "descriptorpos", "++", ";", "break", ";", "case", "'", "'", ":", "size", "=", "size", "+", "2", ";", "descriptorpos", "++", ";", "break", ";", "case", "'", "'", ":", "case", "'", "'", ":", "case", "'", "'", ":", "case", "'", "'", ":", "case", "'", "'", ":", "case", "'", "'", ":", "size", "++", ";", "descriptorpos", "++", ";", "break", ";", "default", ":", "throw", "new", "IllegalStateException", "(", "\"Unexpected character in descriptor: \"", "+", "ch", ")", ";", "}", "}", "return", "size", ";", "}" ]
Compute the size required for a specific method descriptor. @param descriptor a method descriptor, for example (Ljava/lang/String;ZZ)V @return number of stack/var entries necessary for that descriptor
[ "Compute", "the", "size", "required", "for", "a", "specific", "method", "descriptor", "." ]
59b32f957a05c6d9f149148158053605e2a6205a
https://github.com/spring-projects/spring-loaded/blob/59b32f957a05c6d9f149148158053605e2a6205a/springloaded/src/main/java/org/springsource/loaded/Utils.java#L1234-L1281
26,450
spring-projects/spring-loaded
springloaded/src/main/java/org/springsource/loaded/Utils.java
Utils.loadFromStream
public static byte[] loadFromStream(InputStream stream) { try { BufferedInputStream bis = new BufferedInputStream(stream); int size = 2048; byte[] theData = new byte[size]; int dataReadSoFar = 0; byte[] buffer = new byte[size / 2]; int read = 0; while ((read = bis.read(buffer)) != -1) { if ((read + dataReadSoFar) > theData.length) { // need to make more room byte[] newTheData = new byte[theData.length * 2]; // System.out.println("doubled to " + newTheData.length); System.arraycopy(theData, 0, newTheData, 0, dataReadSoFar); theData = newTheData; } System.arraycopy(buffer, 0, theData, dataReadSoFar, read); dataReadSoFar += read; } bis.close(); // Resize to actual data read byte[] returnData = new byte[dataReadSoFar]; System.arraycopy(theData, 0, returnData, 0, dataReadSoFar); return returnData; } catch (IOException e) { throw new ReloadException("Unexpectedly unable to load bytedata from input stream", e); } }
java
public static byte[] loadFromStream(InputStream stream) { try { BufferedInputStream bis = new BufferedInputStream(stream); int size = 2048; byte[] theData = new byte[size]; int dataReadSoFar = 0; byte[] buffer = new byte[size / 2]; int read = 0; while ((read = bis.read(buffer)) != -1) { if ((read + dataReadSoFar) > theData.length) { // need to make more room byte[] newTheData = new byte[theData.length * 2]; // System.out.println("doubled to " + newTheData.length); System.arraycopy(theData, 0, newTheData, 0, dataReadSoFar); theData = newTheData; } System.arraycopy(buffer, 0, theData, dataReadSoFar, read); dataReadSoFar += read; } bis.close(); // Resize to actual data read byte[] returnData = new byte[dataReadSoFar]; System.arraycopy(theData, 0, returnData, 0, dataReadSoFar); return returnData; } catch (IOException e) { throw new ReloadException("Unexpectedly unable to load bytedata from input stream", e); } }
[ "public", "static", "byte", "[", "]", "loadFromStream", "(", "InputStream", "stream", ")", "{", "try", "{", "BufferedInputStream", "bis", "=", "new", "BufferedInputStream", "(", "stream", ")", ";", "int", "size", "=", "2048", ";", "byte", "[", "]", "theData", "=", "new", "byte", "[", "size", "]", ";", "int", "dataReadSoFar", "=", "0", ";", "byte", "[", "]", "buffer", "=", "new", "byte", "[", "size", "/", "2", "]", ";", "int", "read", "=", "0", ";", "while", "(", "(", "read", "=", "bis", ".", "read", "(", "buffer", ")", ")", "!=", "-", "1", ")", "{", "if", "(", "(", "read", "+", "dataReadSoFar", ")", ">", "theData", ".", "length", ")", "{", "// need to make more room", "byte", "[", "]", "newTheData", "=", "new", "byte", "[", "theData", ".", "length", "*", "2", "]", ";", "// System.out.println(\"doubled to \" + newTheData.length);", "System", ".", "arraycopy", "(", "theData", ",", "0", ",", "newTheData", ",", "0", ",", "dataReadSoFar", ")", ";", "theData", "=", "newTheData", ";", "}", "System", ".", "arraycopy", "(", "buffer", ",", "0", ",", "theData", ",", "dataReadSoFar", ",", "read", ")", ";", "dataReadSoFar", "+=", "read", ";", "}", "bis", ".", "close", "(", ")", ";", "// Resize to actual data read", "byte", "[", "]", "returnData", "=", "new", "byte", "[", "dataReadSoFar", "]", ";", "System", ".", "arraycopy", "(", "theData", ",", "0", ",", "returnData", ",", "0", ",", "dataReadSoFar", ")", ";", "return", "returnData", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "ReloadException", "(", "\"Unexpectedly unable to load bytedata from input stream\"", ",", "e", ")", ";", "}", "}" ]
Load the contents of an input stream. @param stream input stream that contains the bytes to load @return the byte array loaded from the input stream
[ "Load", "the", "contents", "of", "an", "input", "stream", "." ]
59b32f957a05c6d9f149148158053605e2a6205a
https://github.com/spring-projects/spring-loaded/blob/59b32f957a05c6d9f149148158053605e2a6205a/springloaded/src/main/java/org/springsource/loaded/Utils.java#L1399-L1427
26,451
spring-projects/spring-loaded
springloaded/src/main/java/org/springsource/loaded/Utils.java
Utils.arrayCopyOf
public static <T> T[] arrayCopyOf(T[] array, int newSize) { @SuppressWarnings("unchecked") T[] newArr = (T[]) Array.newInstance(array.getClass().getComponentType(), newSize); System.arraycopy(array, 0, newArr, 0, Math.min(newSize, newArr.length)); return newArr; }
java
public static <T> T[] arrayCopyOf(T[] array, int newSize) { @SuppressWarnings("unchecked") T[] newArr = (T[]) Array.newInstance(array.getClass().getComponentType(), newSize); System.arraycopy(array, 0, newArr, 0, Math.min(newSize, newArr.length)); return newArr; }
[ "public", "static", "<", "T", ">", "T", "[", "]", "arrayCopyOf", "(", "T", "[", "]", "array", ",", "int", "newSize", ")", "{", "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "T", "[", "]", "newArr", "=", "(", "T", "[", "]", ")", "Array", ".", "newInstance", "(", "array", ".", "getClass", "(", ")", ".", "getComponentType", "(", ")", ",", "newSize", ")", ";", "System", ".", "arraycopy", "(", "array", ",", "0", ",", "newArr", ",", "0", ",", "Math", ".", "min", "(", "newSize", ",", "newArr", ".", "length", ")", ")", ";", "return", "newArr", ";", "}" ]
Utility method similar to Java 1.6 Arrays.copyOf, used instead of that method to stick to Java 1.5 only API. @param <T> the type of the array entries @param array the array to copy @param newSize the size of the new array @return a new array of the specified size containing the supplied array elements at the beginning
[ "Utility", "method", "similar", "to", "Java", "1", ".", "6", "Arrays", ".", "copyOf", "used", "instead", "of", "that", "method", "to", "stick", "to", "Java", "1", ".", "5", "only", "API", "." ]
59b32f957a05c6d9f149148158053605e2a6205a
https://github.com/spring-projects/spring-loaded/blob/59b32f957a05c6d9f149148158053605e2a6205a/springloaded/src/main/java/org/springsource/loaded/Utils.java#L1499-L1504
26,452
spring-projects/spring-loaded
springloaded/src/main/java/org/springsource/loaded/Utils.java
Utils.makePublicNonFinal
public static int makePublicNonFinal(int access) { access = (access & ~(ACC_PRIVATE | ACC_PROTECTED)) | ACC_PUBLIC; access = (access & ~ACC_FINAL); return access; }
java
public static int makePublicNonFinal(int access) { access = (access & ~(ACC_PRIVATE | ACC_PROTECTED)) | ACC_PUBLIC; access = (access & ~ACC_FINAL); return access; }
[ "public", "static", "int", "makePublicNonFinal", "(", "int", "access", ")", "{", "access", "=", "(", "access", "&", "~", "(", "ACC_PRIVATE", "|", "ACC_PROTECTED", ")", ")", "|", "ACC_PUBLIC", ";", "access", "=", "(", "access", "&", "~", "ACC_FINAL", ")", ";", "return", "access", ";", "}" ]
Modify visibility to be public. @param access existing access @return modified access, adjusted to public non-final
[ "Modify", "visibility", "to", "be", "public", "." ]
59b32f957a05c6d9f149148158053605e2a6205a
https://github.com/spring-projects/spring-loaded/blob/59b32f957a05c6d9f149148158053605e2a6205a/springloaded/src/main/java/org/springsource/loaded/Utils.java#L1512-L1516
26,453
spring-projects/spring-loaded
springloaded/src/main/java/org/springsource/loaded/Utils.java
Utils.insertPopsForAllParameters
public static int insertPopsForAllParameters(MethodVisitor mv, String desc) { String descSequence = Utils.getParamSequence(desc); if (descSequence == null) { return 0; // nothing to do, there are no parameters } int count = descSequence.length(); for (int dpos = count - 1; dpos >= 0; dpos--) { char ch = descSequence.charAt(dpos); switch (ch) { case 'O': case 'I': case 'Z': case 'F': case 'S': case 'C': case 'B': mv.visitInsn(POP); break; case 'J': // long - double slot case 'D': // double - double slot mv.visitInsn(POP2); break; default: throw new IllegalStateException("Unexpected character: " + ch + " from " + desc + ":" + dpos); } } return count; }
java
public static int insertPopsForAllParameters(MethodVisitor mv, String desc) { String descSequence = Utils.getParamSequence(desc); if (descSequence == null) { return 0; // nothing to do, there are no parameters } int count = descSequence.length(); for (int dpos = count - 1; dpos >= 0; dpos--) { char ch = descSequence.charAt(dpos); switch (ch) { case 'O': case 'I': case 'Z': case 'F': case 'S': case 'C': case 'B': mv.visitInsn(POP); break; case 'J': // long - double slot case 'D': // double - double slot mv.visitInsn(POP2); break; default: throw new IllegalStateException("Unexpected character: " + ch + " from " + desc + ":" + dpos); } } return count; }
[ "public", "static", "int", "insertPopsForAllParameters", "(", "MethodVisitor", "mv", ",", "String", "desc", ")", "{", "String", "descSequence", "=", "Utils", ".", "getParamSequence", "(", "desc", ")", ";", "if", "(", "descSequence", "==", "null", ")", "{", "return", "0", ";", "// nothing to do, there are no parameters", "}", "int", "count", "=", "descSequence", ".", "length", "(", ")", ";", "for", "(", "int", "dpos", "=", "count", "-", "1", ";", "dpos", ">=", "0", ";", "dpos", "--", ")", "{", "char", "ch", "=", "descSequence", ".", "charAt", "(", "dpos", ")", ";", "switch", "(", "ch", ")", "{", "case", "'", "'", ":", "case", "'", "'", ":", "case", "'", "'", ":", "case", "'", "'", ":", "case", "'", "'", ":", "case", "'", "'", ":", "case", "'", "'", ":", "mv", ".", "visitInsn", "(", "POP", ")", ";", "break", ";", "case", "'", "'", ":", "// long - double slot", "case", "'", "'", ":", "// double - double slot", "mv", ".", "visitInsn", "(", "POP2", ")", ";", "break", ";", "default", ":", "throw", "new", "IllegalStateException", "(", "\"Unexpected character: \"", "+", "ch", "+", "\" from \"", "+", "desc", "+", "\":\"", "+", "dpos", ")", ";", "}", "}", "return", "count", ";", "}" ]
Looks at the supplied descriptor and inserts enough pops to remove all parameters. Should be used when about to avoid a method call. @param mv the method visitor to append instructions to @param desc the method descriptor for the parameter sequence (e.g. (Ljava/lang/String;IZZ)V) @return number of parameters popped
[ "Looks", "at", "the", "supplied", "descriptor", "and", "inserts", "enough", "pops", "to", "remove", "all", "parameters", ".", "Should", "be", "used", "when", "about", "to", "avoid", "a", "method", "call", "." ]
59b32f957a05c6d9f149148158053605e2a6205a
https://github.com/spring-projects/spring-loaded/blob/59b32f957a05c6d9f149148158053605e2a6205a/springloaded/src/main/java/org/springsource/loaded/Utils.java#L1760-L1787
26,454
spring-projects/spring-loaded
springloaded/src/main/java/org/springsource/loaded/Utils.java
Utils.discoverClassname
public static String discoverClassname(byte[] classbytes) { ClassReader cr = new ClassReader(classbytes); ClassnameDiscoveryVisitor v = new ClassnameDiscoveryVisitor(); cr.accept(v, 0); return v.classname; }
java
public static String discoverClassname(byte[] classbytes) { ClassReader cr = new ClassReader(classbytes); ClassnameDiscoveryVisitor v = new ClassnameDiscoveryVisitor(); cr.accept(v, 0); return v.classname; }
[ "public", "static", "String", "discoverClassname", "(", "byte", "[", "]", "classbytes", ")", "{", "ClassReader", "cr", "=", "new", "ClassReader", "(", "classbytes", ")", ";", "ClassnameDiscoveryVisitor", "v", "=", "new", "ClassnameDiscoveryVisitor", "(", ")", ";", "cr", ".", "accept", "(", "v", ",", "0", ")", ";", "return", "v", ".", "classname", ";", "}" ]
Discover the classname specified in the supplied bytecode and return it. @param classbytes the bytecode for the class @return the classname recovered from the bytecode
[ "Discover", "the", "classname", "specified", "in", "the", "supplied", "bytecode", "and", "return", "it", "." ]
59b32f957a05c6d9f149148158053605e2a6205a
https://github.com/spring-projects/spring-loaded/blob/59b32f957a05c6d9f149148158053605e2a6205a/springloaded/src/main/java/org/springsource/loaded/Utils.java#L1933-L1938
26,455
spring-projects/spring-loaded
springloaded/src/main/java/org/springsource/loaded/pluginhelpers/EmptyCtor.java
EmptyCtor.invoke
public static byte[] invoke(byte[] bytesIn, String... descriptors) { ClassReader cr = new ClassReader(bytesIn); EmptyCtor ca = new EmptyCtor(descriptors); cr.accept(ca, 0); byte[] newbytes = ca.getBytes(); return newbytes; }
java
public static byte[] invoke(byte[] bytesIn, String... descriptors) { ClassReader cr = new ClassReader(bytesIn); EmptyCtor ca = new EmptyCtor(descriptors); cr.accept(ca, 0); byte[] newbytes = ca.getBytes(); return newbytes; }
[ "public", "static", "byte", "[", "]", "invoke", "(", "byte", "[", "]", "bytesIn", ",", "String", "...", "descriptors", ")", "{", "ClassReader", "cr", "=", "new", "ClassReader", "(", "bytesIn", ")", ";", "EmptyCtor", "ca", "=", "new", "EmptyCtor", "(", "descriptors", ")", ";", "cr", ".", "accept", "(", "ca", ",", "0", ")", ";", "byte", "[", "]", "newbytes", "=", "ca", ".", "getBytes", "(", ")", ";", "return", "newbytes", ";", "}" ]
Empty the constructors with the specified descriptors. @param bytesIn input class as bytes @param descriptors descriptors of interest (e.g. "()V") @return modified class as byte array
[ "Empty", "the", "constructors", "with", "the", "specified", "descriptors", "." ]
59b32f957a05c6d9f149148158053605e2a6205a
https://github.com/spring-projects/spring-loaded/blob/59b32f957a05c6d9f149148158053605e2a6205a/springloaded/src/main/java/org/springsource/loaded/pluginhelpers/EmptyCtor.java#L47-L53
26,456
spring-projects/spring-loaded
springloaded/src/main/java/org/springsource/loaded/support/Java8.java
Java8.emulateInvokeDynamic
public static Object emulateInvokeDynamic(ReloadableType rtype, Class<?> executorClass, Handle handle, Object[] bsmArgs, Object lookup, String indyNameAndDescriptor, Object[] indyParams) { try { CallSite callsite = callLambdaMetaFactory(rtype, bsmArgs, lookup, indyNameAndDescriptor, executorClass); return callsite.dynamicInvoker().invokeWithArguments(indyParams); } catch (Throwable t) { throw new RuntimeException(t); } }
java
public static Object emulateInvokeDynamic(ReloadableType rtype, Class<?> executorClass, Handle handle, Object[] bsmArgs, Object lookup, String indyNameAndDescriptor, Object[] indyParams) { try { CallSite callsite = callLambdaMetaFactory(rtype, bsmArgs, lookup, indyNameAndDescriptor, executorClass); return callsite.dynamicInvoker().invokeWithArguments(indyParams); } catch (Throwable t) { throw new RuntimeException(t); } }
[ "public", "static", "Object", "emulateInvokeDynamic", "(", "ReloadableType", "rtype", ",", "Class", "<", "?", ">", "executorClass", ",", "Handle", "handle", ",", "Object", "[", "]", "bsmArgs", ",", "Object", "lookup", ",", "String", "indyNameAndDescriptor", ",", "Object", "[", "]", "indyParams", ")", "{", "try", "{", "CallSite", "callsite", "=", "callLambdaMetaFactory", "(", "rtype", ",", "bsmArgs", ",", "lookup", ",", "indyNameAndDescriptor", ",", "executorClass", ")", ";", "return", "callsite", ".", "dynamicInvoker", "(", ")", ".", "invokeWithArguments", "(", "indyParams", ")", ";", "}", "catch", "(", "Throwable", "t", ")", "{", "throw", "new", "RuntimeException", "(", "t", ")", ";", "}", "}" ]
Programmatic emulation of INVOKEDYNAMIC so initialize the callsite via use of the bootstrap method then invoke the result. @param executorClass the executor that will contain the lambda function, null if not yet reloaded @param handle bootstrap method handle @param bsmArgs bootstrap method arguments @param lookup The MethodHandles.Lookup object that can be used to find types @param indyNameAndDescriptor Method name and descriptor at invokedynamic site @param indyParams parameters when the invokedynamic call is made @return the result of the invokedynamic call
[ "Programmatic", "emulation", "of", "INVOKEDYNAMIC", "so", "initialize", "the", "callsite", "via", "use", "of", "the", "bootstrap", "method", "then", "invoke", "the", "result", "." ]
59b32f957a05c6d9f149148158053605e2a6205a
https://github.com/spring-projects/spring-loaded/blob/59b32f957a05c6d9f149148158053605e2a6205a/springloaded/src/main/java/org/springsource/loaded/support/Java8.java#L85-L94
26,457
spring-projects/spring-loaded
springloaded/src/main/java/org/springsource/loaded/ConstantPoolChecker2.java
ConstantPoolChecker2.main
public static void main(String[] args) throws Exception { File[] fs = new File("./bin").listFiles(); // File[] fs = new File("../testdata-groovy/bin").listFiles(); // File[] fs = new File("/Users/aclement/grailsreload/foo/target/classes").listFiles(); checkThemAll(fs); System.out.println("total=" + total / 1000000d); }
java
public static void main(String[] args) throws Exception { File[] fs = new File("./bin").listFiles(); // File[] fs = new File("../testdata-groovy/bin").listFiles(); // File[] fs = new File("/Users/aclement/grailsreload/foo/target/classes").listFiles(); checkThemAll(fs); System.out.println("total=" + total / 1000000d); }
[ "public", "static", "void", "main", "(", "String", "[", "]", "args", ")", "throws", "Exception", "{", "File", "[", "]", "fs", "=", "new", "File", "(", "\"./bin\"", ")", ".", "listFiles", "(", ")", ";", "//\t\tFile[] fs = new File(\"../testdata-groovy/bin\").listFiles();", "//\t\tFile[] fs = new File(\"/Users/aclement/grailsreload/foo/target/classes\").listFiles();", "checkThemAll", "(", "fs", ")", ";", "System", ".", "out", ".", "println", "(", "\"total=\"", "+", "total", "/", "1000000d", ")", ";", "}" ]
Test entry point just goes through all the code in the bin folder
[ "Test", "entry", "point", "just", "goes", "through", "all", "the", "code", "in", "the", "bin", "folder" ]
59b32f957a05c6d9f149148158053605e2a6205a
https://github.com/spring-projects/spring-loaded/blob/59b32f957a05c6d9f149148158053605e2a6205a/springloaded/src/main/java/org/springsource/loaded/ConstantPoolChecker2.java#L73-L80
26,458
spring-projects/spring-loaded
springloaded/src/main/java/org/springsource/loaded/ConstantPoolScanner.java
ConstantPoolScanner.accessUtf8
private String accessUtf8(int cpIndex) { Object object = cpdata[cpIndex]; if (object instanceof String) { return (String) object; } int[] ptrAndLen = (int[]) object; String value; try { value = new String(classbytes, ptrAndLen[0], ptrAndLen[1], "UTF8"); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("Bad data found at constant pool position " + cpIndex + " offset=" + ptrAndLen[0] + " length=" + ptrAndLen[1], e); } cpdata[cpIndex] = value; return value; }
java
private String accessUtf8(int cpIndex) { Object object = cpdata[cpIndex]; if (object instanceof String) { return (String) object; } int[] ptrAndLen = (int[]) object; String value; try { value = new String(classbytes, ptrAndLen[0], ptrAndLen[1], "UTF8"); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("Bad data found at constant pool position " + cpIndex + " offset=" + ptrAndLen[0] + " length=" + ptrAndLen[1], e); } cpdata[cpIndex] = value; return value; }
[ "private", "String", "accessUtf8", "(", "int", "cpIndex", ")", "{", "Object", "object", "=", "cpdata", "[", "cpIndex", "]", ";", "if", "(", "object", "instanceof", "String", ")", "{", "return", "(", "String", ")", "object", ";", "}", "int", "[", "]", "ptrAndLen", "=", "(", "int", "[", "]", ")", "object", ";", "String", "value", ";", "try", "{", "value", "=", "new", "String", "(", "classbytes", ",", "ptrAndLen", "[", "0", "]", ",", "ptrAndLen", "[", "1", "]", ",", "\"UTF8\"", ")", ";", "}", "catch", "(", "UnsupportedEncodingException", "e", ")", "{", "throw", "new", "IllegalStateException", "(", "\"Bad data found at constant pool position \"", "+", "cpIndex", "+", "\" offset=\"", "+", "ptrAndLen", "[", "0", "]", "+", "\" length=\"", "+", "ptrAndLen", "[", "1", "]", ",", "e", ")", ";", "}", "cpdata", "[", "cpIndex", "]", "=", "value", ";", "return", "value", ";", "}" ]
Return the UTF8 at the specified index in the constant pool. The data found at the constant pool for that index may not have been unpacked yet if this is the first access of the string. If not unpacked the constant pool entry is a pair of ints in an array representing the offset and length within the classbytes where the UTF8 string is encoded. Once decoded the constant pool entry is flipped from an int array to a String for future fast access. @param cpIndex constant pool index @return UTF8 string at that constant pool index
[ "Return", "the", "UTF8", "at", "the", "specified", "index", "in", "the", "constant", "pool", ".", "The", "data", "found", "at", "the", "constant", "pool", "for", "that", "index", "may", "not", "have", "been", "unpacked", "yet", "if", "this", "is", "the", "first", "access", "of", "the", "string", ".", "If", "not", "unpacked", "the", "constant", "pool", "entry", "is", "a", "pair", "of", "ints", "in", "an", "array", "representing", "the", "offset", "and", "length", "within", "the", "classbytes", "where", "the", "UTF8", "string", "is", "encoded", ".", "Once", "decoded", "the", "constant", "pool", "entry", "is", "flipped", "from", "an", "int", "array", "to", "a", "String", "for", "future", "fast", "access", "." ]
59b32f957a05c6d9f149148158053605e2a6205a
https://github.com/spring-projects/spring-loaded/blob/59b32f957a05c6d9f149148158053605e2a6205a/springloaded/src/main/java/org/springsource/loaded/ConstantPoolScanner.java#L157-L173
26,459
spring-projects/spring-loaded
springloaded/src/main/java/org/springsource/loaded/TypeDiffComputer.java
TypeDiffComputer.computeAnyMethodDifferences
private static void computeAnyMethodDifferences(MethodNode oMethod, MethodNode nMethod, TypeDelta td) { MethodDelta md = new MethodDelta(oMethod.name, oMethod.desc); if (oMethod.access != nMethod.access) { md.setAccessChanged(oMethod.access, nMethod.access); } // TODO annotations InsnList oInstructions = oMethod.instructions; InsnList nInstructions = nMethod.instructions; if (oInstructions.size() != nInstructions.size()) { md.setInstructionsChanged(oInstructions.toArray(), nInstructions.toArray()); } else { // TODO Just interested in constructors right now - should add others if (oMethod.name.charAt(0) == '<') { String oInvokeSpecialDescriptor = null; String nInvokeSpecialDescriptor = null; int oUninitCount = 0; int nUninitCount = 0; boolean codeChange = false; for (int i = 0, max = oInstructions.size(); i < max; i++) { AbstractInsnNode oInstruction = oInstructions.get(i); AbstractInsnNode nInstruction = nInstructions.get(i); if (!codeChange) { if (!sameInstruction(oInstruction, nInstruction)) { codeChange = true; } } if (oInstruction.getType() == AbstractInsnNode.TYPE_INSN) { if (oInstruction.getOpcode() == Opcodes.NEW) { oUninitCount++; } } if (nInstruction.getType() == AbstractInsnNode.TYPE_INSN) { if (nInstruction.getOpcode() == Opcodes.NEW) { nUninitCount++; } } if (oInstruction.getType() == AbstractInsnNode.METHOD_INSN) { MethodInsnNode mi = (MethodInsnNode) oInstruction; if (mi.getOpcode() == INVOKESPECIAL && mi.name.equals("<init>")) { if (oUninitCount == 0) { // this is the one! oInvokeSpecialDescriptor = mi.desc; } else { oUninitCount--; } } } if (nInstruction.getType() == AbstractInsnNode.METHOD_INSN) { MethodInsnNode mi = (MethodInsnNode) nInstruction; if (mi.getOpcode() == INVOKESPECIAL && mi.name.equals("<init>")) { if (nUninitCount == 0) { // this is the one! nInvokeSpecialDescriptor = mi.desc; } else { nUninitCount--; } } } } // Has the invokespecial changed? if (oInvokeSpecialDescriptor == null) { if (nInvokeSpecialDescriptor != null) { md.setInvokespecialChanged(oInvokeSpecialDescriptor, nInvokeSpecialDescriptor); } } else { if (!oInvokeSpecialDescriptor.equals(nInvokeSpecialDescriptor)) { md.setInvokespecialChanged(oInvokeSpecialDescriptor, nInvokeSpecialDescriptor); } } if (codeChange) { md.setCodeChanged(oInstructions.toArray(), nInstructions.toArray()); } } } if (md.hasAnyChanges()) { // it needs recording td.addChangedMethod(md); } }
java
private static void computeAnyMethodDifferences(MethodNode oMethod, MethodNode nMethod, TypeDelta td) { MethodDelta md = new MethodDelta(oMethod.name, oMethod.desc); if (oMethod.access != nMethod.access) { md.setAccessChanged(oMethod.access, nMethod.access); } // TODO annotations InsnList oInstructions = oMethod.instructions; InsnList nInstructions = nMethod.instructions; if (oInstructions.size() != nInstructions.size()) { md.setInstructionsChanged(oInstructions.toArray(), nInstructions.toArray()); } else { // TODO Just interested in constructors right now - should add others if (oMethod.name.charAt(0) == '<') { String oInvokeSpecialDescriptor = null; String nInvokeSpecialDescriptor = null; int oUninitCount = 0; int nUninitCount = 0; boolean codeChange = false; for (int i = 0, max = oInstructions.size(); i < max; i++) { AbstractInsnNode oInstruction = oInstructions.get(i); AbstractInsnNode nInstruction = nInstructions.get(i); if (!codeChange) { if (!sameInstruction(oInstruction, nInstruction)) { codeChange = true; } } if (oInstruction.getType() == AbstractInsnNode.TYPE_INSN) { if (oInstruction.getOpcode() == Opcodes.NEW) { oUninitCount++; } } if (nInstruction.getType() == AbstractInsnNode.TYPE_INSN) { if (nInstruction.getOpcode() == Opcodes.NEW) { nUninitCount++; } } if (oInstruction.getType() == AbstractInsnNode.METHOD_INSN) { MethodInsnNode mi = (MethodInsnNode) oInstruction; if (mi.getOpcode() == INVOKESPECIAL && mi.name.equals("<init>")) { if (oUninitCount == 0) { // this is the one! oInvokeSpecialDescriptor = mi.desc; } else { oUninitCount--; } } } if (nInstruction.getType() == AbstractInsnNode.METHOD_INSN) { MethodInsnNode mi = (MethodInsnNode) nInstruction; if (mi.getOpcode() == INVOKESPECIAL && mi.name.equals("<init>")) { if (nUninitCount == 0) { // this is the one! nInvokeSpecialDescriptor = mi.desc; } else { nUninitCount--; } } } } // Has the invokespecial changed? if (oInvokeSpecialDescriptor == null) { if (nInvokeSpecialDescriptor != null) { md.setInvokespecialChanged(oInvokeSpecialDescriptor, nInvokeSpecialDescriptor); } } else { if (!oInvokeSpecialDescriptor.equals(nInvokeSpecialDescriptor)) { md.setInvokespecialChanged(oInvokeSpecialDescriptor, nInvokeSpecialDescriptor); } } if (codeChange) { md.setCodeChanged(oInstructions.toArray(), nInstructions.toArray()); } } } if (md.hasAnyChanges()) { // it needs recording td.addChangedMethod(md); } }
[ "private", "static", "void", "computeAnyMethodDifferences", "(", "MethodNode", "oMethod", ",", "MethodNode", "nMethod", ",", "TypeDelta", "td", ")", "{", "MethodDelta", "md", "=", "new", "MethodDelta", "(", "oMethod", ".", "name", ",", "oMethod", ".", "desc", ")", ";", "if", "(", "oMethod", ".", "access", "!=", "nMethod", ".", "access", ")", "{", "md", ".", "setAccessChanged", "(", "oMethod", ".", "access", ",", "nMethod", ".", "access", ")", ";", "}", "// TODO annotations", "InsnList", "oInstructions", "=", "oMethod", ".", "instructions", ";", "InsnList", "nInstructions", "=", "nMethod", ".", "instructions", ";", "if", "(", "oInstructions", ".", "size", "(", ")", "!=", "nInstructions", ".", "size", "(", ")", ")", "{", "md", ".", "setInstructionsChanged", "(", "oInstructions", ".", "toArray", "(", ")", ",", "nInstructions", ".", "toArray", "(", ")", ")", ";", "}", "else", "{", "// TODO Just interested in constructors right now - should add others", "if", "(", "oMethod", ".", "name", ".", "charAt", "(", "0", ")", "==", "'", "'", ")", "{", "String", "oInvokeSpecialDescriptor", "=", "null", ";", "String", "nInvokeSpecialDescriptor", "=", "null", ";", "int", "oUninitCount", "=", "0", ";", "int", "nUninitCount", "=", "0", ";", "boolean", "codeChange", "=", "false", ";", "for", "(", "int", "i", "=", "0", ",", "max", "=", "oInstructions", ".", "size", "(", ")", ";", "i", "<", "max", ";", "i", "++", ")", "{", "AbstractInsnNode", "oInstruction", "=", "oInstructions", ".", "get", "(", "i", ")", ";", "AbstractInsnNode", "nInstruction", "=", "nInstructions", ".", "get", "(", "i", ")", ";", "if", "(", "!", "codeChange", ")", "{", "if", "(", "!", "sameInstruction", "(", "oInstruction", ",", "nInstruction", ")", ")", "{", "codeChange", "=", "true", ";", "}", "}", "if", "(", "oInstruction", ".", "getType", "(", ")", "==", "AbstractInsnNode", ".", "TYPE_INSN", ")", "{", "if", "(", "oInstruction", ".", "getOpcode", "(", ")", "==", "Opcodes", ".", "NEW", ")", "{", "oUninitCount", "++", ";", "}", "}", "if", "(", "nInstruction", ".", "getType", "(", ")", "==", "AbstractInsnNode", ".", "TYPE_INSN", ")", "{", "if", "(", "nInstruction", ".", "getOpcode", "(", ")", "==", "Opcodes", ".", "NEW", ")", "{", "nUninitCount", "++", ";", "}", "}", "if", "(", "oInstruction", ".", "getType", "(", ")", "==", "AbstractInsnNode", ".", "METHOD_INSN", ")", "{", "MethodInsnNode", "mi", "=", "(", "MethodInsnNode", ")", "oInstruction", ";", "if", "(", "mi", ".", "getOpcode", "(", ")", "==", "INVOKESPECIAL", "&&", "mi", ".", "name", ".", "equals", "(", "\"<init>\"", ")", ")", "{", "if", "(", "oUninitCount", "==", "0", ")", "{", "// this is the one!", "oInvokeSpecialDescriptor", "=", "mi", ".", "desc", ";", "}", "else", "{", "oUninitCount", "--", ";", "}", "}", "}", "if", "(", "nInstruction", ".", "getType", "(", ")", "==", "AbstractInsnNode", ".", "METHOD_INSN", ")", "{", "MethodInsnNode", "mi", "=", "(", "MethodInsnNode", ")", "nInstruction", ";", "if", "(", "mi", ".", "getOpcode", "(", ")", "==", "INVOKESPECIAL", "&&", "mi", ".", "name", ".", "equals", "(", "\"<init>\"", ")", ")", "{", "if", "(", "nUninitCount", "==", "0", ")", "{", "// this is the one!", "nInvokeSpecialDescriptor", "=", "mi", ".", "desc", ";", "}", "else", "{", "nUninitCount", "--", ";", "}", "}", "}", "}", "// Has the invokespecial changed?", "if", "(", "oInvokeSpecialDescriptor", "==", "null", ")", "{", "if", "(", "nInvokeSpecialDescriptor", "!=", "null", ")", "{", "md", ".", "setInvokespecialChanged", "(", "oInvokeSpecialDescriptor", ",", "nInvokeSpecialDescriptor", ")", ";", "}", "}", "else", "{", "if", "(", "!", "oInvokeSpecialDescriptor", ".", "equals", "(", "nInvokeSpecialDescriptor", ")", ")", "{", "md", ".", "setInvokespecialChanged", "(", "oInvokeSpecialDescriptor", ",", "nInvokeSpecialDescriptor", ")", ";", "}", "}", "if", "(", "codeChange", ")", "{", "md", ".", "setCodeChanged", "(", "oInstructions", ".", "toArray", "(", ")", ",", "nInstructions", ".", "toArray", "(", ")", ")", ";", "}", "}", "}", "if", "(", "md", ".", "hasAnyChanges", "(", ")", ")", "{", "// it needs recording", "td", ".", "addChangedMethod", "(", "md", ")", ";", "}", "}" ]
Determine if there any differences between the methods supplied. A MethodDelta object is built to record any differences and stored against the type delta. @param oMethod 'old' method @param nMethod 'new' method @param td the type delta where changes are currently being accumulated
[ "Determine", "if", "there", "any", "differences", "between", "the", "methods", "supplied", ".", "A", "MethodDelta", "object", "is", "built", "to", "record", "any", "differences", "and", "stored", "against", "the", "type", "delta", "." ]
59b32f957a05c6d9f149148158053605e2a6205a
https://github.com/spring-projects/spring-loaded/blob/59b32f957a05c6d9f149148158053605e2a6205a/springloaded/src/main/java/org/springsource/loaded/TypeDiffComputer.java#L184-L268
26,460
igniterealtime/Smack
smack-extensions/src/main/java/org/jivesoftware/smackx/filetransfer/IncomingFileTransfer.java
IncomingFileTransfer.receiveFile
public InputStream receiveFile() throws SmackException, XMPPErrorException, InterruptedException { if (inputStream != null) { throw new IllegalStateException("Transfer already negotiated!"); } try { inputStream = negotiateStream(); } catch (XMPPErrorException e) { setException(e); throw e; } return inputStream; }
java
public InputStream receiveFile() throws SmackException, XMPPErrorException, InterruptedException { if (inputStream != null) { throw new IllegalStateException("Transfer already negotiated!"); } try { inputStream = negotiateStream(); } catch (XMPPErrorException e) { setException(e); throw e; } return inputStream; }
[ "public", "InputStream", "receiveFile", "(", ")", "throws", "SmackException", ",", "XMPPErrorException", ",", "InterruptedException", "{", "if", "(", "inputStream", "!=", "null", ")", "{", "throw", "new", "IllegalStateException", "(", "\"Transfer already negotiated!\"", ")", ";", "}", "try", "{", "inputStream", "=", "negotiateStream", "(", ")", ";", "}", "catch", "(", "XMPPErrorException", "e", ")", "{", "setException", "(", "e", ")", ";", "throw", "e", ";", "}", "return", "inputStream", ";", "}" ]
Negotiates the stream method to transfer the file over and then returns the negotiated stream. @return The negotiated InputStream from which to read the data. @throws SmackException @throws XMPPErrorException If there is an error in the negotiation process an exception is thrown. @throws InterruptedException
[ "Negotiates", "the", "stream", "method", "to", "transfer", "the", "file", "over", "and", "then", "returns", "the", "negotiated", "stream", "." ]
870756997faec1e1bfabfac0cd6c2395b04da873
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-extensions/src/main/java/org/jivesoftware/smackx/filetransfer/IncomingFileTransfer.java#L82-L96
26,461
igniterealtime/Smack
smack-extensions/src/main/java/org/jivesoftware/smackx/filetransfer/IncomingFileTransfer.java
IncomingFileTransfer.receiveFile
public void receiveFile(final File file) throws SmackException, IOException { if (file == null) { throw new IllegalArgumentException("File cannot be null"); } if (!file.exists()) { file.createNewFile(); } if (!file.canWrite()) { throw new IllegalArgumentException("Cannot write to provided file"); } Thread transferThread = new Thread(new Runnable() { @Override public void run() { try { inputStream = negotiateStream(); } catch (Exception e) { setStatus(FileTransfer.Status.error); setException(e); return; } OutputStream outputStream = null; try { outputStream = new FileOutputStream(file); setStatus(Status.in_progress); writeToStream(inputStream, outputStream); } catch (FileNotFoundException e) { setStatus(Status.error); setError(Error.bad_file); setException(e); } catch (IOException e) { setStatus(Status.error); setError(Error.stream); setException(e); } if (getStatus().equals(Status.in_progress)) { setStatus(Status.complete); } CloseableUtil.maybeClose(inputStream, LOGGER); CloseableUtil.maybeClose(outputStream, LOGGER); } }, "File Transfer " + streamID); transferThread.start(); }
java
public void receiveFile(final File file) throws SmackException, IOException { if (file == null) { throw new IllegalArgumentException("File cannot be null"); } if (!file.exists()) { file.createNewFile(); } if (!file.canWrite()) { throw new IllegalArgumentException("Cannot write to provided file"); } Thread transferThread = new Thread(new Runnable() { @Override public void run() { try { inputStream = negotiateStream(); } catch (Exception e) { setStatus(FileTransfer.Status.error); setException(e); return; } OutputStream outputStream = null; try { outputStream = new FileOutputStream(file); setStatus(Status.in_progress); writeToStream(inputStream, outputStream); } catch (FileNotFoundException e) { setStatus(Status.error); setError(Error.bad_file); setException(e); } catch (IOException e) { setStatus(Status.error); setError(Error.stream); setException(e); } if (getStatus().equals(Status.in_progress)) { setStatus(Status.complete); } CloseableUtil.maybeClose(inputStream, LOGGER); CloseableUtil.maybeClose(outputStream, LOGGER); } }, "File Transfer " + streamID); transferThread.start(); }
[ "public", "void", "receiveFile", "(", "final", "File", "file", ")", "throws", "SmackException", ",", "IOException", "{", "if", "(", "file", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"File cannot be null\"", ")", ";", "}", "if", "(", "!", "file", ".", "exists", "(", ")", ")", "{", "file", ".", "createNewFile", "(", ")", ";", "}", "if", "(", "!", "file", ".", "canWrite", "(", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Cannot write to provided file\"", ")", ";", "}", "Thread", "transferThread", "=", "new", "Thread", "(", "new", "Runnable", "(", ")", "{", "@", "Override", "public", "void", "run", "(", ")", "{", "try", "{", "inputStream", "=", "negotiateStream", "(", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "setStatus", "(", "FileTransfer", ".", "Status", ".", "error", ")", ";", "setException", "(", "e", ")", ";", "return", ";", "}", "OutputStream", "outputStream", "=", "null", ";", "try", "{", "outputStream", "=", "new", "FileOutputStream", "(", "file", ")", ";", "setStatus", "(", "Status", ".", "in_progress", ")", ";", "writeToStream", "(", "inputStream", ",", "outputStream", ")", ";", "}", "catch", "(", "FileNotFoundException", "e", ")", "{", "setStatus", "(", "Status", ".", "error", ")", ";", "setError", "(", "Error", ".", "bad_file", ")", ";", "setException", "(", "e", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "setStatus", "(", "Status", ".", "error", ")", ";", "setError", "(", "Error", ".", "stream", ")", ";", "setException", "(", "e", ")", ";", "}", "if", "(", "getStatus", "(", ")", ".", "equals", "(", "Status", ".", "in_progress", ")", ")", "{", "setStatus", "(", "Status", ".", "complete", ")", ";", "}", "CloseableUtil", ".", "maybeClose", "(", "inputStream", ",", "LOGGER", ")", ";", "CloseableUtil", ".", "maybeClose", "(", "outputStream", ",", "LOGGER", ")", ";", "}", "}", ",", "\"File Transfer \"", "+", "streamID", ")", ";", "transferThread", ".", "start", "(", ")", ";", "}" ]
This method negotiates the stream and then transfer's the file over the negotiated stream. The transferred file will be saved at the provided location. This method will return immediately, file transfer progress can be monitored through several methods: <UL> <LI>{@link FileTransfer#getStatus()}</LI> <LI>{@link FileTransfer#getProgress()}</LI> <LI>{@link FileTransfer#isDone()}</LI> </UL> @param file The location to save the file. @throws SmackException when the file transfer fails @throws IOException @throws IllegalArgumentException This exception is thrown when the the provided file is either null, or cannot be written to.
[ "This", "method", "negotiates", "the", "stream", "and", "then", "transfer", "s", "the", "file", "over", "the", "negotiated", "stream", ".", "The", "transferred", "file", "will", "be", "saved", "at", "the", "provided", "location", "." ]
870756997faec1e1bfabfac0cd6c2395b04da873
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-extensions/src/main/java/org/jivesoftware/smackx/filetransfer/IncomingFileTransfer.java#L117-L166
26,462
igniterealtime/Smack
smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/jmf/AudioFormatUtils.java
AudioFormatUtils.getAudioFormat
public static AudioFormat getAudioFormat(PayloadType payloadtype) { switch (payloadtype.getId()) { case 0: return new AudioFormat(AudioFormat.ULAW_RTP); case 3: return new AudioFormat(AudioFormat.GSM_RTP); case 4: return new AudioFormat(AudioFormat.G723_RTP); default: return null; } }
java
public static AudioFormat getAudioFormat(PayloadType payloadtype) { switch (payloadtype.getId()) { case 0: return new AudioFormat(AudioFormat.ULAW_RTP); case 3: return new AudioFormat(AudioFormat.GSM_RTP); case 4: return new AudioFormat(AudioFormat.G723_RTP); default: return null; } }
[ "public", "static", "AudioFormat", "getAudioFormat", "(", "PayloadType", "payloadtype", ")", "{", "switch", "(", "payloadtype", ".", "getId", "(", ")", ")", "{", "case", "0", ":", "return", "new", "AudioFormat", "(", "AudioFormat", ".", "ULAW_RTP", ")", ";", "case", "3", ":", "return", "new", "AudioFormat", "(", "AudioFormat", ".", "GSM_RTP", ")", ";", "case", "4", ":", "return", "new", "AudioFormat", "(", "AudioFormat", ".", "G723_RTP", ")", ";", "default", ":", "return", "null", ";", "}", "}" ]
Return a JMF AudioFormat for a given Jingle Payload type. Return null if the payload is not supported by this jmf API. @param payloadtype payloadtype @return correspondent audioType
[ "Return", "a", "JMF", "AudioFormat", "for", "a", "given", "Jingle", "Payload", "type", ".", "Return", "null", "if", "the", "payload", "is", "not", "supported", "by", "this", "jmf", "API", "." ]
870756997faec1e1bfabfac0cd6c2395b04da873
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/jmf/AudioFormatUtils.java#L37-L50
26,463
igniterealtime/Smack
smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/nat/JingleTransportManager.java
JingleTransportManager.getResolver
public TransportResolver getResolver(JingleSession session) throws XMPPException, SmackException, InterruptedException { TransportResolver resolver = createResolver(session); if (resolver == null) { resolver = new BasicResolver(); } resolver.initializeAndWait(); return resolver; }
java
public TransportResolver getResolver(JingleSession session) throws XMPPException, SmackException, InterruptedException { TransportResolver resolver = createResolver(session); if (resolver == null) { resolver = new BasicResolver(); } resolver.initializeAndWait(); return resolver; }
[ "public", "TransportResolver", "getResolver", "(", "JingleSession", "session", ")", "throws", "XMPPException", ",", "SmackException", ",", "InterruptedException", "{", "TransportResolver", "resolver", "=", "createResolver", "(", "session", ")", ";", "if", "(", "resolver", "==", "null", ")", "{", "resolver", "=", "new", "BasicResolver", "(", ")", ";", "}", "resolver", ".", "initializeAndWait", "(", ")", ";", "return", "resolver", ";", "}" ]
Get a new Transport Resolver to be used in a Jingle Session. @return the TransportResolver to be used @throws InterruptedException
[ "Get", "a", "new", "Transport", "Resolver", "to", "be", "used", "in", "a", "Jingle", "Session", "." ]
870756997faec1e1bfabfac0cd6c2395b04da873
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/nat/JingleTransportManager.java#L57-L65
26,464
igniterealtime/Smack
smack-extensions/src/main/java/org/jivesoftware/smackx/xdata/packet/DataForm.java
DataForm.setInstructions
public void setInstructions(List<String> instructions) { synchronized (this.instructions) { this.instructions.clear(); this.instructions.addAll(instructions); } }
java
public void setInstructions(List<String> instructions) { synchronized (this.instructions) { this.instructions.clear(); this.instructions.addAll(instructions); } }
[ "public", "void", "setInstructions", "(", "List", "<", "String", ">", "instructions", ")", "{", "synchronized", "(", "this", ".", "instructions", ")", "{", "this", ".", "instructions", ".", "clear", "(", ")", ";", "this", ".", "instructions", ".", "addAll", "(", "instructions", ")", ";", "}", "}" ]
Sets the list of instructions that explain how to fill out the form and what the form is about. The dataform could include multiple instructions since each instruction could not contain newlines characters. @param instructions list of instructions that explain how to fill out the form.
[ "Sets", "the", "list", "of", "instructions", "that", "explain", "how", "to", "fill", "out", "the", "form", "and", "what", "the", "form", "is", "about", ".", "The", "dataform", "could", "include", "multiple", "instructions", "since", "each", "instruction", "could", "not", "contain", "newlines", "characters", "." ]
870756997faec1e1bfabfac0cd6c2395b04da873
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-extensions/src/main/java/org/jivesoftware/smackx/xdata/packet/DataForm.java#L203-L208
26,465
igniterealtime/Smack
smack-extensions/src/main/java/org/jivesoftware/smackx/xdata/packet/DataForm.java
DataForm.addField
public void addField(FormField field) { String fieldVariableName = field.getVariable(); // Form field values must be unique unless they are of type 'fixed', in // which case their variable name may be 'null', and therefore could // appear multiple times within the same form. if (fieldVariableName != null && hasField(fieldVariableName)) { throw new IllegalArgumentException("This data form already contains a form field with the variable name '" + fieldVariableName + "'"); } synchronized (fields) { fields.put(fieldVariableName, field); } }
java
public void addField(FormField field) { String fieldVariableName = field.getVariable(); // Form field values must be unique unless they are of type 'fixed', in // which case their variable name may be 'null', and therefore could // appear multiple times within the same form. if (fieldVariableName != null && hasField(fieldVariableName)) { throw new IllegalArgumentException("This data form already contains a form field with the variable name '" + fieldVariableName + "'"); } synchronized (fields) { fields.put(fieldVariableName, field); } }
[ "public", "void", "addField", "(", "FormField", "field", ")", "{", "String", "fieldVariableName", "=", "field", ".", "getVariable", "(", ")", ";", "// Form field values must be unique unless they are of type 'fixed', in", "// which case their variable name may be 'null', and therefore could", "// appear multiple times within the same form.", "if", "(", "fieldVariableName", "!=", "null", "&&", "hasField", "(", "fieldVariableName", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"This data form already contains a form field with the variable name '\"", "+", "fieldVariableName", "+", "\"'\"", ")", ";", "}", "synchronized", "(", "fields", ")", "{", "fields", ".", "put", "(", "fieldVariableName", ",", "field", ")", ";", "}", "}" ]
Adds a new field as part of the form. @param field the field to add to the form.
[ "Adds", "a", "new", "field", "as", "part", "of", "the", "form", "." ]
870756997faec1e1bfabfac0cd6c2395b04da873
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-extensions/src/main/java/org/jivesoftware/smackx/xdata/packet/DataForm.java#L224-L236
26,466
igniterealtime/Smack
smack-extensions/src/main/java/org/jivesoftware/smackx/xdata/packet/DataForm.java
DataForm.addFields
public boolean addFields(Collection<FormField> fieldsToAdd) { boolean fieldOverridden = false; synchronized (fields) { for (FormField field : fieldsToAdd) { FormField previousField = fields.put(field.getVariable(), field); if (previousField != null) { fieldOverridden = true; } } } return fieldOverridden; }
java
public boolean addFields(Collection<FormField> fieldsToAdd) { boolean fieldOverridden = false; synchronized (fields) { for (FormField field : fieldsToAdd) { FormField previousField = fields.put(field.getVariable(), field); if (previousField != null) { fieldOverridden = true; } } } return fieldOverridden; }
[ "public", "boolean", "addFields", "(", "Collection", "<", "FormField", ">", "fieldsToAdd", ")", "{", "boolean", "fieldOverridden", "=", "false", ";", "synchronized", "(", "fields", ")", "{", "for", "(", "FormField", "field", ":", "fieldsToAdd", ")", "{", "FormField", "previousField", "=", "fields", ".", "put", "(", "field", ".", "getVariable", "(", ")", ",", "field", ")", ";", "if", "(", "previousField", "!=", "null", ")", "{", "fieldOverridden", "=", "true", ";", "}", "}", "}", "return", "fieldOverridden", ";", "}" ]
Add the given fields to this form. @param fieldsToAdd @return true if a field was overridden. @since 4.3.0
[ "Add", "the", "given", "fields", "to", "this", "form", "." ]
870756997faec1e1bfabfac0cd6c2395b04da873
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-extensions/src/main/java/org/jivesoftware/smackx/xdata/packet/DataForm.java#L245-L256
26,467
igniterealtime/Smack
smack-extensions/src/main/java/org/jivesoftware/smackx/xdata/packet/DataForm.java
DataForm.getHiddenFormTypeField
public FormField getHiddenFormTypeField() { FormField field = getField(FormField.FORM_TYPE); if (field != null && field.getType() == FormField.Type.hidden) { return field; } return null; }
java
public FormField getHiddenFormTypeField() { FormField field = getField(FormField.FORM_TYPE); if (field != null && field.getType() == FormField.Type.hidden) { return field; } return null; }
[ "public", "FormField", "getHiddenFormTypeField", "(", ")", "{", "FormField", "field", "=", "getField", "(", "FormField", ".", "FORM_TYPE", ")", ";", "if", "(", "field", "!=", "null", "&&", "field", ".", "getType", "(", ")", "==", "FormField", ".", "Type", ".", "hidden", ")", "{", "return", "field", ";", "}", "return", "null", ";", "}" ]
Returns the hidden FORM_TYPE field or null if this data form has none. @return the hidden FORM_TYPE field or null. @since 4.1
[ "Returns", "the", "hidden", "FORM_TYPE", "field", "or", "null", "if", "this", "data", "form", "has", "none", "." ]
870756997faec1e1bfabfac0cd6c2395b04da873
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-extensions/src/main/java/org/jivesoftware/smackx/xdata/packet/DataForm.java#L296-L302
26,468
igniterealtime/Smack
smack-extensions/src/main/java/org/jivesoftware/smackx/xdata/Form.java
Form.setAnswer
public void setAnswer(String variable, int value) { FormField field = getField(variable); if (field == null) { throw new IllegalArgumentException("Field not found for the specified variable name."); } validateThatFieldIsText(field); setAnswer(field, value); }
java
public void setAnswer(String variable, int value) { FormField field = getField(variable); if (field == null) { throw new IllegalArgumentException("Field not found for the specified variable name."); } validateThatFieldIsText(field); setAnswer(field, value); }
[ "public", "void", "setAnswer", "(", "String", "variable", ",", "int", "value", ")", "{", "FormField", "field", "=", "getField", "(", "variable", ")", ";", "if", "(", "field", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Field not found for the specified variable name.\"", ")", ";", "}", "validateThatFieldIsText", "(", "field", ")", ";", "setAnswer", "(", "field", ",", "value", ")", ";", "}" ]
Sets a new int value to a given form's field. The field whose variable matches the requested variable will be completed with the specified value. If no field could be found for the specified variable then an exception will be raised. @param variable the variable name that was completed. @param value the int value that was answered. @throws IllegalStateException if the form is not of type "submit". @throws IllegalArgumentException if the form does not include the specified variable or if the answer type does not correspond with the field type.
[ "Sets", "a", "new", "int", "value", "to", "a", "given", "form", "s", "field", ".", "The", "field", "whose", "variable", "matches", "the", "requested", "variable", "will", "be", "completed", "with", "the", "specified", "value", ".", "If", "no", "field", "could", "be", "found", "for", "the", "specified", "variable", "then", "an", "exception", "will", "be", "raised", "." ]
870756997faec1e1bfabfac0cd6c2395b04da873
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-extensions/src/main/java/org/jivesoftware/smackx/xdata/Form.java#L139-L146
26,469
igniterealtime/Smack
smack-extensions/src/main/java/org/jivesoftware/smackx/xdata/Form.java
Form.setAnswer
public void setAnswer(String variable, boolean value) { FormField field = getField(variable); if (field == null) { throw new IllegalArgumentException("Field not found for the specified variable name."); } if (field.getType() != FormField.Type.bool) { throw new IllegalArgumentException("This field is not of type boolean."); } setAnswer(field, Boolean.toString(value)); }
java
public void setAnswer(String variable, boolean value) { FormField field = getField(variable); if (field == null) { throw new IllegalArgumentException("Field not found for the specified variable name."); } if (field.getType() != FormField.Type.bool) { throw new IllegalArgumentException("This field is not of type boolean."); } setAnswer(field, Boolean.toString(value)); }
[ "public", "void", "setAnswer", "(", "String", "variable", ",", "boolean", "value", ")", "{", "FormField", "field", "=", "getField", "(", "variable", ")", ";", "if", "(", "field", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Field not found for the specified variable name.\"", ")", ";", "}", "if", "(", "field", ".", "getType", "(", ")", "!=", "FormField", ".", "Type", ".", "bool", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"This field is not of type boolean.\"", ")", ";", "}", "setAnswer", "(", "field", ",", "Boolean", ".", "toString", "(", "value", ")", ")", ";", "}" ]
Sets a new boolean value to a given form's field. The field whose variable matches the requested variable will be completed with the specified value. If no field could be found for the specified variable then an exception will be raised. @param variable the variable name that was completed. @param value the boolean value that was answered. @throws IllegalStateException if the form is not of type "submit". @throws IllegalArgumentException if the form does not include the specified variable or if the answer type does not correspond with the field type.
[ "Sets", "a", "new", "boolean", "value", "to", "a", "given", "form", "s", "field", ".", "The", "field", "whose", "variable", "matches", "the", "requested", "variable", "will", "be", "completed", "with", "the", "specified", "value", ".", "If", "no", "field", "could", "be", "found", "for", "the", "specified", "variable", "then", "an", "exception", "will", "be", "raised", "." ]
870756997faec1e1bfabfac0cd6c2395b04da873
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-extensions/src/main/java/org/jivesoftware/smackx/xdata/Form.java#L230-L239
26,470
igniterealtime/Smack
smack-extensions/src/main/java/org/jivesoftware/smackx/xdata/Form.java
Form.setDefaultAnswer
public void setDefaultAnswer(String variable) { if (!isSubmitType()) { throw new IllegalStateException("Cannot set an answer if the form is not of type " + "\"submit\""); } FormField field = getField(variable); if (field != null) { // Clear the old values field.resetValues(); // Set the default value for (CharSequence value : field.getValues()) { field.addValue(value); } } else { throw new IllegalArgumentException("Couldn't find a field for the specified variable."); } }
java
public void setDefaultAnswer(String variable) { if (!isSubmitType()) { throw new IllegalStateException("Cannot set an answer if the form is not of type " + "\"submit\""); } FormField field = getField(variable); if (field != null) { // Clear the old values field.resetValues(); // Set the default value for (CharSequence value : field.getValues()) { field.addValue(value); } } else { throw new IllegalArgumentException("Couldn't find a field for the specified variable."); } }
[ "public", "void", "setDefaultAnswer", "(", "String", "variable", ")", "{", "if", "(", "!", "isSubmitType", "(", ")", ")", "{", "throw", "new", "IllegalStateException", "(", "\"Cannot set an answer if the form is not of type \"", "+", "\"\\\"submit\\\"\"", ")", ";", "}", "FormField", "field", "=", "getField", "(", "variable", ")", ";", "if", "(", "field", "!=", "null", ")", "{", "// Clear the old values", "field", ".", "resetValues", "(", ")", ";", "// Set the default value", "for", "(", "CharSequence", "value", ":", "field", ".", "getValues", "(", ")", ")", "{", "field", ".", "addValue", "(", "value", ")", ";", "}", "}", "else", "{", "throw", "new", "IllegalArgumentException", "(", "\"Couldn't find a field for the specified variable.\"", ")", ";", "}", "}" ]
Sets the default value as the value of a given form's field. The field whose variable matches the requested variable will be completed with its default value. If no field could be found for the specified variable then an exception will be raised. @param variable the variable to complete with its default value. @throws IllegalStateException if the form is not of type "submit". @throws IllegalArgumentException if the form does not include the specified variable.
[ "Sets", "the", "default", "value", "as", "the", "value", "of", "a", "given", "form", "s", "field", ".", "The", "field", "whose", "variable", "matches", "the", "requested", "variable", "will", "be", "completed", "with", "its", "default", "value", ".", "If", "no", "field", "could", "be", "found", "for", "the", "specified", "variable", "then", "an", "exception", "will", "be", "raised", "." ]
870756997faec1e1bfabfac0cd6c2395b04da873
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-extensions/src/main/java/org/jivesoftware/smackx/xdata/Form.java#L317-L334
26,471
igniterealtime/Smack
smack-extensions/src/main/java/org/jivesoftware/smackx/xdata/Form.java
Form.getInstructions
public String getInstructions() { StringBuilder sb = new StringBuilder(); // Join the list of instructions together separated by newlines for (Iterator<String> it = dataForm.getInstructions().iterator(); it.hasNext();) { sb.append(it.next()); // If this is not the last instruction then append a newline if (it.hasNext()) { sb.append('\n'); } } return sb.toString(); }
java
public String getInstructions() { StringBuilder sb = new StringBuilder(); // Join the list of instructions together separated by newlines for (Iterator<String> it = dataForm.getInstructions().iterator(); it.hasNext();) { sb.append(it.next()); // If this is not the last instruction then append a newline if (it.hasNext()) { sb.append('\n'); } } return sb.toString(); }
[ "public", "String", "getInstructions", "(", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "// Join the list of instructions together separated by newlines", "for", "(", "Iterator", "<", "String", ">", "it", "=", "dataForm", ".", "getInstructions", "(", ")", ".", "iterator", "(", ")", ";", "it", ".", "hasNext", "(", ")", ";", ")", "{", "sb", ".", "append", "(", "it", ".", "next", "(", ")", ")", ";", "// If this is not the last instruction then append a newline", "if", "(", "it", ".", "hasNext", "(", ")", ")", "{", "sb", ".", "append", "(", "'", "'", ")", ";", "}", "}", "return", "sb", ".", "toString", "(", ")", ";", "}" ]
Returns the instructions that explain how to fill out the form and what the form is about. @return instructions that explain how to fill out the form.
[ "Returns", "the", "instructions", "that", "explain", "how", "to", "fill", "out", "the", "form", "and", "what", "the", "form", "is", "about", "." ]
870756997faec1e1bfabfac0cd6c2395b04da873
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-extensions/src/main/java/org/jivesoftware/smackx/xdata/Form.java#L373-L384
26,472
igniterealtime/Smack
smack-extensions/src/main/java/org/jivesoftware/smackx/xdata/Form.java
Form.setInstructions
public void setInstructions(String instructions) { // Split the instructions into multiple instructions for each existent newline ArrayList<String> instructionsList = new ArrayList<>(); StringTokenizer st = new StringTokenizer(instructions, "\n"); while (st.hasMoreTokens()) { instructionsList.add(st.nextToken()); } // Set the new list of instructions dataForm.setInstructions(instructionsList); }
java
public void setInstructions(String instructions) { // Split the instructions into multiple instructions for each existent newline ArrayList<String> instructionsList = new ArrayList<>(); StringTokenizer st = new StringTokenizer(instructions, "\n"); while (st.hasMoreTokens()) { instructionsList.add(st.nextToken()); } // Set the new list of instructions dataForm.setInstructions(instructionsList); }
[ "public", "void", "setInstructions", "(", "String", "instructions", ")", "{", "// Split the instructions into multiple instructions for each existent newline", "ArrayList", "<", "String", ">", "instructionsList", "=", "new", "ArrayList", "<>", "(", ")", ";", "StringTokenizer", "st", "=", "new", "StringTokenizer", "(", "instructions", ",", "\"\\n\"", ")", ";", "while", "(", "st", ".", "hasMoreTokens", "(", ")", ")", "{", "instructionsList", ".", "add", "(", "st", ".", "nextToken", "(", ")", ")", ";", "}", "// Set the new list of instructions", "dataForm", ".", "setInstructions", "(", "instructionsList", ")", ";", "}" ]
Sets instructions that explain how to fill out the form and what the form is about. @param instructions instructions that explain how to fill out the form.
[ "Sets", "instructions", "that", "explain", "how", "to", "fill", "out", "the", "form", "and", "what", "the", "form", "is", "about", "." ]
870756997faec1e1bfabfac0cd6c2395b04da873
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-extensions/src/main/java/org/jivesoftware/smackx/xdata/Form.java#L414-L424
26,473
igniterealtime/Smack
smack-experimental/src/main/java/org/jivesoftware/smackx/sid/StableUniqueStanzaIdManager.java
StableUniqueStanzaIdManager.enable
public synchronized void enable() { ServiceDiscoveryManager.getInstanceFor(connection()).addFeature(NAMESPACE); StanzaFilter filter = new AndFilter(OUTGOING_FILTER, new NotFilter(OUTGOING_FILTER)); connection().addStanzaInterceptor(ADD_ORIGIN_ID_INTERCEPTOR, filter); }
java
public synchronized void enable() { ServiceDiscoveryManager.getInstanceFor(connection()).addFeature(NAMESPACE); StanzaFilter filter = new AndFilter(OUTGOING_FILTER, new NotFilter(OUTGOING_FILTER)); connection().addStanzaInterceptor(ADD_ORIGIN_ID_INTERCEPTOR, filter); }
[ "public", "synchronized", "void", "enable", "(", ")", "{", "ServiceDiscoveryManager", ".", "getInstanceFor", "(", "connection", "(", ")", ")", ".", "addFeature", "(", "NAMESPACE", ")", ";", "StanzaFilter", "filter", "=", "new", "AndFilter", "(", "OUTGOING_FILTER", ",", "new", "NotFilter", "(", "OUTGOING_FILTER", ")", ")", ";", "connection", "(", ")", ".", "addStanzaInterceptor", "(", "ADD_ORIGIN_ID_INTERCEPTOR", ",", "filter", ")", ";", "}" ]
Start appending origin-id elements to outgoing stanzas and add the feature to disco.
[ "Start", "appending", "origin", "-", "id", "elements", "to", "outgoing", "stanzas", "and", "add", "the", "feature", "to", "disco", "." ]
870756997faec1e1bfabfac0cd6c2395b04da873
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-experimental/src/main/java/org/jivesoftware/smackx/sid/StableUniqueStanzaIdManager.java#L93-L97
26,474
igniterealtime/Smack
smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/packet/JingleDescription.java
JingleDescription.addPayloadType
public void addPayloadType(final PayloadType pt) { synchronized (payloads) { if (pt == null) { LOGGER.severe("Null payload type"); } else { payloads.add(pt); } } }
java
public void addPayloadType(final PayloadType pt) { synchronized (payloads) { if (pt == null) { LOGGER.severe("Null payload type"); } else { payloads.add(pt); } } }
[ "public", "void", "addPayloadType", "(", "final", "PayloadType", "pt", ")", "{", "synchronized", "(", "payloads", ")", "{", "if", "(", "pt", "==", "null", ")", "{", "LOGGER", ".", "severe", "(", "\"Null payload type\"", ")", ";", "}", "else", "{", "payloads", ".", "add", "(", "pt", ")", ";", "}", "}", "}" ]
Adds a audio payload type to the packet. @param pt the audio payload type to add.
[ "Adds", "a", "audio", "payload", "type", "to", "the", "packet", "." ]
870756997faec1e1bfabfac0cd6c2395b04da873
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/packet/JingleDescription.java#L76-L84
26,475
igniterealtime/Smack
smack-legacy/src/main/java/org/jivesoftware/smackx/xroster/RemoteRosterEntry.java
RemoteRosterEntry.getGroupArrayNames
public String[] getGroupArrayNames() { synchronized (groupNames) { return Collections.unmodifiableList(groupNames).toArray(new String[groupNames.size()]); } }
java
public String[] getGroupArrayNames() { synchronized (groupNames) { return Collections.unmodifiableList(groupNames).toArray(new String[groupNames.size()]); } }
[ "public", "String", "[", "]", "getGroupArrayNames", "(", ")", "{", "synchronized", "(", "groupNames", ")", "{", "return", "Collections", ".", "unmodifiableList", "(", "groupNames", ")", ".", "toArray", "(", "new", "String", "[", "groupNames", ".", "size", "(", ")", "]", ")", ";", "}", "}" ]
Returns a String array for the group names that the roster entry belongs to. @return a String[] for the group names.
[ "Returns", "a", "String", "array", "for", "the", "group", "names", "that", "the", "roster", "entry", "belongs", "to", "." ]
870756997faec1e1bfabfac0cd6c2395b04da873
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-legacy/src/main/java/org/jivesoftware/smackx/xroster/RemoteRosterEntry.java#L95-L99
26,476
igniterealtime/Smack
smack-extensions/src/main/java/org/jivesoftware/smackx/chatstates/ChatStateManager.java
ChatStateManager.getInstance
public static synchronized ChatStateManager getInstance(final XMPPConnection connection) { ChatStateManager manager = INSTANCES.get(connection); if (manager == null) { manager = new ChatStateManager(connection); INSTANCES.put(connection, manager); } return manager; }
java
public static synchronized ChatStateManager getInstance(final XMPPConnection connection) { ChatStateManager manager = INSTANCES.get(connection); if (manager == null) { manager = new ChatStateManager(connection); INSTANCES.put(connection, manager); } return manager; }
[ "public", "static", "synchronized", "ChatStateManager", "getInstance", "(", "final", "XMPPConnection", "connection", ")", "{", "ChatStateManager", "manager", "=", "INSTANCES", ".", "get", "(", "connection", ")", ";", "if", "(", "manager", "==", "null", ")", "{", "manager", "=", "new", "ChatStateManager", "(", "connection", ")", ";", "INSTANCES", ".", "put", "(", "connection", ",", "manager", ")", ";", "}", "return", "manager", ";", "}" ]
Returns the ChatStateManager related to the XMPPConnection and it will create one if it does not yet exist. @param connection the connection to return the ChatStateManager @return the ChatStateManager related the the connection.
[ "Returns", "the", "ChatStateManager", "related", "to", "the", "XMPPConnection", "and", "it", "will", "create", "one", "if", "it", "does", "not", "yet", "exist", "." ]
870756997faec1e1bfabfac0cd6c2395b04da873
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-extensions/src/main/java/org/jivesoftware/smackx/chatstates/ChatStateManager.java#L98-L105
26,477
igniterealtime/Smack
smack-extensions/src/main/java/org/jivesoftware/smackx/muc/MultiUserChatManager.java
MultiUserChatManager.getInstanceFor
public static synchronized MultiUserChatManager getInstanceFor(XMPPConnection connection) { MultiUserChatManager multiUserChatManager = INSTANCES.get(connection); if (multiUserChatManager == null) { multiUserChatManager = new MultiUserChatManager(connection); INSTANCES.put(connection, multiUserChatManager); } return multiUserChatManager; }
java
public static synchronized MultiUserChatManager getInstanceFor(XMPPConnection connection) { MultiUserChatManager multiUserChatManager = INSTANCES.get(connection); if (multiUserChatManager == null) { multiUserChatManager = new MultiUserChatManager(connection); INSTANCES.put(connection, multiUserChatManager); } return multiUserChatManager; }
[ "public", "static", "synchronized", "MultiUserChatManager", "getInstanceFor", "(", "XMPPConnection", "connection", ")", "{", "MultiUserChatManager", "multiUserChatManager", "=", "INSTANCES", ".", "get", "(", "connection", ")", ";", "if", "(", "multiUserChatManager", "==", "null", ")", "{", "multiUserChatManager", "=", "new", "MultiUserChatManager", "(", "connection", ")", ";", "INSTANCES", ".", "put", "(", "connection", ",", "multiUserChatManager", ")", ";", "}", "return", "multiUserChatManager", ";", "}" ]
Get a instance of a multi user chat manager for the given connection. @param connection @return a multi user chat manager.
[ "Get", "a", "instance", "of", "a", "multi", "user", "chat", "manager", "for", "the", "given", "connection", "." ]
870756997faec1e1bfabfac0cd6c2395b04da873
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-extensions/src/main/java/org/jivesoftware/smackx/muc/MultiUserChatManager.java#L126-L133
26,478
igniterealtime/Smack
smack-extensions/src/main/java/org/jivesoftware/smackx/muc/MultiUserChatManager.java
MultiUserChatManager.isServiceEnabled
public boolean isServiceEnabled(Jid user) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { return serviceDiscoveryManager.supportsFeature(user, MUCInitialPresence.NAMESPACE); }
java
public boolean isServiceEnabled(Jid user) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { return serviceDiscoveryManager.supportsFeature(user, MUCInitialPresence.NAMESPACE); }
[ "public", "boolean", "isServiceEnabled", "(", "Jid", "user", ")", "throws", "NoResponseException", ",", "XMPPErrorException", ",", "NotConnectedException", ",", "InterruptedException", "{", "return", "serviceDiscoveryManager", ".", "supportsFeature", "(", "user", ",", "MUCInitialPresence", ".", "NAMESPACE", ")", ";", "}" ]
Returns true if the specified user supports the Multi-User Chat protocol. @param user the user to check. A fully qualified xmpp ID, e.g. jdoe@example.com. @return a boolean indicating whether the specified user supports the MUC protocol. @throws XMPPErrorException @throws NoResponseException @throws NotConnectedException @throws InterruptedException
[ "Returns", "true", "if", "the", "specified", "user", "supports", "the", "Multi", "-", "User", "Chat", "protocol", "." ]
870756997faec1e1bfabfac0cd6c2395b04da873
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-extensions/src/main/java/org/jivesoftware/smackx/muc/MultiUserChatManager.java#L283-L285
26,479
igniterealtime/Smack
smack-extensions/src/main/java/org/jivesoftware/smackx/muc/MultiUserChatManager.java
MultiUserChatManager.getRoomInfo
public RoomInfo getRoomInfo(EntityBareJid room) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { DiscoverInfo info = serviceDiscoveryManager.discoverInfo(room); return new RoomInfo(info); }
java
public RoomInfo getRoomInfo(EntityBareJid room) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { DiscoverInfo info = serviceDiscoveryManager.discoverInfo(room); return new RoomInfo(info); }
[ "public", "RoomInfo", "getRoomInfo", "(", "EntityBareJid", "room", ")", "throws", "NoResponseException", ",", "XMPPErrorException", ",", "NotConnectedException", ",", "InterruptedException", "{", "DiscoverInfo", "info", "=", "serviceDiscoveryManager", ".", "discoverInfo", "(", "room", ")", ";", "return", "new", "RoomInfo", "(", "info", ")", ";", "}" ]
Returns the discovered information of a given room without actually having to join the room. The server will provide information only for rooms that are public. @param room the name of the room in the form "roomName@service" of which we want to discover its information. @return the discovered information of a given room without actually having to join the room. @throws XMPPErrorException @throws NoResponseException @throws NotConnectedException @throws InterruptedException
[ "Returns", "the", "discovered", "information", "of", "a", "given", "room", "without", "actually", "having", "to", "join", "the", "room", ".", "The", "server", "will", "provide", "information", "only", "for", "rooms", "that", "are", "public", "." ]
870756997faec1e1bfabfac0cd6c2395b04da873
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-extensions/src/main/java/org/jivesoftware/smackx/muc/MultiUserChatManager.java#L337-L340
26,480
igniterealtime/Smack
smack-extensions/src/main/java/org/jivesoftware/smackx/muc/MultiUserChatManager.java
MultiUserChatManager.getMucServiceDomains
public List<DomainBareJid> getMucServiceDomains() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { return serviceDiscoveryManager.findServices(MUCInitialPresence.NAMESPACE, false, false); }
java
public List<DomainBareJid> getMucServiceDomains() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { return serviceDiscoveryManager.findServices(MUCInitialPresence.NAMESPACE, false, false); }
[ "public", "List", "<", "DomainBareJid", ">", "getMucServiceDomains", "(", ")", "throws", "NoResponseException", ",", "XMPPErrorException", ",", "NotConnectedException", ",", "InterruptedException", "{", "return", "serviceDiscoveryManager", ".", "findServices", "(", "MUCInitialPresence", ".", "NAMESPACE", ",", "false", ",", "false", ")", ";", "}" ]
Returns a collection with the XMPP addresses of the Multi-User Chat services. @return a collection with the XMPP addresses of the Multi-User Chat services. @throws XMPPErrorException @throws NoResponseException @throws NotConnectedException @throws InterruptedException
[ "Returns", "a", "collection", "with", "the", "XMPP", "addresses", "of", "the", "Multi", "-", "User", "Chat", "services", "." ]
870756997faec1e1bfabfac0cd6c2395b04da873
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-extensions/src/main/java/org/jivesoftware/smackx/muc/MultiUserChatManager.java#L351-L353
26,481
igniterealtime/Smack
smack-extensions/src/main/java/org/jivesoftware/smackx/muc/MultiUserChatManager.java
MultiUserChatManager.providesMucService
public boolean providesMucService(DomainBareJid domainBareJid) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { return serviceDiscoveryManager.supportsFeature(domainBareJid, MUCInitialPresence.NAMESPACE); }
java
public boolean providesMucService(DomainBareJid domainBareJid) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { return serviceDiscoveryManager.supportsFeature(domainBareJid, MUCInitialPresence.NAMESPACE); }
[ "public", "boolean", "providesMucService", "(", "DomainBareJid", "domainBareJid", ")", "throws", "NoResponseException", ",", "XMPPErrorException", ",", "NotConnectedException", ",", "InterruptedException", "{", "return", "serviceDiscoveryManager", ".", "supportsFeature", "(", "domainBareJid", ",", "MUCInitialPresence", ".", "NAMESPACE", ")", ";", "}" ]
Check if the provided domain bare JID provides a MUC service. @param domainBareJid the domain bare JID to check. @return <code>true</code> if the provided JID provides a MUC service, <code>false</code> otherwise. @throws NoResponseException @throws XMPPErrorException @throws NotConnectedException @throws InterruptedException @see <a href="http://xmpp.org/extensions/xep-0045.html#disco-service-features">XEP-45 § 6.2 Discovering the Features Supported by a MUC Service</a> @since 4.2
[ "Check", "if", "the", "provided", "domain", "bare", "JID", "provides", "a", "MUC", "service", "." ]
870756997faec1e1bfabfac0cd6c2395b04da873
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-extensions/src/main/java/org/jivesoftware/smackx/muc/MultiUserChatManager.java#L383-L387
26,482
igniterealtime/Smack
smack-extensions/src/main/java/org/jivesoftware/smackx/muc/MultiUserChatManager.java
MultiUserChatManager.getRoomsHostedBy
public Map<EntityBareJid, HostedRoom> getRoomsHostedBy(DomainBareJid serviceName) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException, NotAMucServiceException { if (!providesMucService(serviceName)) { throw new NotAMucServiceException(serviceName); } DiscoverItems discoverItems = serviceDiscoveryManager.discoverItems(serviceName); List<DiscoverItems.Item> items = discoverItems.getItems(); Map<EntityBareJid, HostedRoom> answer = new HashMap<>(items.size()); for (DiscoverItems.Item item : items) { HostedRoom hostedRoom = new HostedRoom(item); HostedRoom previousRoom = answer.put(hostedRoom.getJid(), hostedRoom); assert previousRoom == null; } return answer; }
java
public Map<EntityBareJid, HostedRoom> getRoomsHostedBy(DomainBareJid serviceName) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException, NotAMucServiceException { if (!providesMucService(serviceName)) { throw new NotAMucServiceException(serviceName); } DiscoverItems discoverItems = serviceDiscoveryManager.discoverItems(serviceName); List<DiscoverItems.Item> items = discoverItems.getItems(); Map<EntityBareJid, HostedRoom> answer = new HashMap<>(items.size()); for (DiscoverItems.Item item : items) { HostedRoom hostedRoom = new HostedRoom(item); HostedRoom previousRoom = answer.put(hostedRoom.getJid(), hostedRoom); assert previousRoom == null; } return answer; }
[ "public", "Map", "<", "EntityBareJid", ",", "HostedRoom", ">", "getRoomsHostedBy", "(", "DomainBareJid", "serviceName", ")", "throws", "NoResponseException", ",", "XMPPErrorException", ",", "NotConnectedException", ",", "InterruptedException", ",", "NotAMucServiceException", "{", "if", "(", "!", "providesMucService", "(", "serviceName", ")", ")", "{", "throw", "new", "NotAMucServiceException", "(", "serviceName", ")", ";", "}", "DiscoverItems", "discoverItems", "=", "serviceDiscoveryManager", ".", "discoverItems", "(", "serviceName", ")", ";", "List", "<", "DiscoverItems", ".", "Item", ">", "items", "=", "discoverItems", ".", "getItems", "(", ")", ";", "Map", "<", "EntityBareJid", ",", "HostedRoom", ">", "answer", "=", "new", "HashMap", "<>", "(", "items", ".", "size", "(", ")", ")", ";", "for", "(", "DiscoverItems", ".", "Item", "item", ":", "items", ")", "{", "HostedRoom", "hostedRoom", "=", "new", "HostedRoom", "(", "item", ")", ";", "HostedRoom", "previousRoom", "=", "answer", ".", "put", "(", "hostedRoom", ".", "getJid", "(", ")", ",", "hostedRoom", ")", ";", "assert", "previousRoom", "==", "null", ";", "}", "return", "answer", ";", "}" ]
Returns a Map of HostedRooms where each HostedRoom has the XMPP address of the room and the room's name. Once discovered the rooms hosted by a chat service it is possible to discover more detailed room information or join the room. @param serviceName the service that is hosting the rooms to discover. @return a map from the room's address to its HostedRoom information. @throws XMPPErrorException @throws NoResponseException @throws NotConnectedException @throws InterruptedException @throws NotAMucServiceException @since 4.3.1
[ "Returns", "a", "Map", "of", "HostedRooms", "where", "each", "HostedRoom", "has", "the", "XMPP", "address", "of", "the", "room", "and", "the", "room", "s", "name", ".", "Once", "discovered", "the", "rooms", "hosted", "by", "a", "chat", "service", "it", "is", "possible", "to", "discover", "more", "detailed", "room", "information", "or", "join", "the", "room", "." ]
870756997faec1e1bfabfac0cd6c2395b04da873
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-extensions/src/main/java/org/jivesoftware/smackx/muc/MultiUserChatManager.java#L403-L419
26,483
igniterealtime/Smack
smack-extensions/src/main/java/org/jivesoftware/smackx/muc/MultiUserChatManager.java
MultiUserChatManager.decline
public void decline(EntityBareJid room, EntityBareJid inviter, String reason) throws NotConnectedException, InterruptedException { Message message = new Message(room); // Create the MUCUser packet that will include the rejection MUCUser mucUser = new MUCUser(); MUCUser.Decline decline = new MUCUser.Decline(reason, inviter); mucUser.setDecline(decline); // Add the MUCUser packet that includes the rejection message.addExtension(mucUser); connection().sendStanza(message); }
java
public void decline(EntityBareJid room, EntityBareJid inviter, String reason) throws NotConnectedException, InterruptedException { Message message = new Message(room); // Create the MUCUser packet that will include the rejection MUCUser mucUser = new MUCUser(); MUCUser.Decline decline = new MUCUser.Decline(reason, inviter); mucUser.setDecline(decline); // Add the MUCUser packet that includes the rejection message.addExtension(mucUser); connection().sendStanza(message); }
[ "public", "void", "decline", "(", "EntityBareJid", "room", ",", "EntityBareJid", "inviter", ",", "String", "reason", ")", "throws", "NotConnectedException", ",", "InterruptedException", "{", "Message", "message", "=", "new", "Message", "(", "room", ")", ";", "// Create the MUCUser packet that will include the rejection", "MUCUser", "mucUser", "=", "new", "MUCUser", "(", ")", ";", "MUCUser", ".", "Decline", "decline", "=", "new", "MUCUser", ".", "Decline", "(", "reason", ",", "inviter", ")", ";", "mucUser", ".", "setDecline", "(", "decline", ")", ";", "// Add the MUCUser packet that includes the rejection", "message", ".", "addExtension", "(", "mucUser", ")", ";", "connection", "(", ")", ".", "sendStanza", "(", "message", ")", ";", "}" ]
Informs the sender of an invitation that the invitee declines the invitation. The rejection will be sent to the room which in turn will forward the rejection to the inviter. @param room the room that sent the original invitation. @param inviter the inviter of the declined invitation. @param reason the reason why the invitee is declining the invitation. @throws NotConnectedException @throws InterruptedException
[ "Informs", "the", "sender", "of", "an", "invitation", "that", "the", "invitee", "declines", "the", "invitation", ".", "The", "rejection", "will", "be", "sent", "to", "the", "room", "which", "in", "turn", "will", "forward", "the", "rejection", "to", "the", "inviter", "." ]
870756997faec1e1bfabfac0cd6c2395b04da873
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-extensions/src/main/java/org/jivesoftware/smackx/muc/MultiUserChatManager.java#L431-L442
26,484
igniterealtime/Smack
smack-core/src/main/java/org/jivesoftware/smack/sasl/SASLMechanism.java
SASLMechanism.challengeReceived
public final void challengeReceived(String challengeString, boolean finalChallenge) throws SmackSaslException, InterruptedException, NotConnectedException { byte[] challenge = Base64.decode((challengeString != null && challengeString.equals("=")) ? "" : challengeString); byte[] response = evaluateChallenge(challenge); if (finalChallenge) { return; } Response responseStanza; if (response == null) { responseStanza = new Response(); } else { responseStanza = new Response(Base64.encodeToString(response)); } // Send the authentication to the server connection.sendNonza(responseStanza); }
java
public final void challengeReceived(String challengeString, boolean finalChallenge) throws SmackSaslException, InterruptedException, NotConnectedException { byte[] challenge = Base64.decode((challengeString != null && challengeString.equals("=")) ? "" : challengeString); byte[] response = evaluateChallenge(challenge); if (finalChallenge) { return; } Response responseStanza; if (response == null) { responseStanza = new Response(); } else { responseStanza = new Response(Base64.encodeToString(response)); } // Send the authentication to the server connection.sendNonza(responseStanza); }
[ "public", "final", "void", "challengeReceived", "(", "String", "challengeString", ",", "boolean", "finalChallenge", ")", "throws", "SmackSaslException", ",", "InterruptedException", ",", "NotConnectedException", "{", "byte", "[", "]", "challenge", "=", "Base64", ".", "decode", "(", "(", "challengeString", "!=", "null", "&&", "challengeString", ".", "equals", "(", "\"=\"", ")", ")", "?", "\"\"", ":", "challengeString", ")", ";", "byte", "[", "]", "response", "=", "evaluateChallenge", "(", "challenge", ")", ";", "if", "(", "finalChallenge", ")", "{", "return", ";", "}", "Response", "responseStanza", ";", "if", "(", "response", "==", "null", ")", "{", "responseStanza", "=", "new", "Response", "(", ")", ";", "}", "else", "{", "responseStanza", "=", "new", "Response", "(", "Base64", ".", "encodeToString", "(", "response", ")", ")", ";", "}", "// Send the authentication to the server", "connection", ".", "sendNonza", "(", "responseStanza", ")", ";", "}" ]
The server is challenging the SASL mechanism for the stanza he just sent. Send a response to the server's challenge. @param challengeString a base64 encoded string representing the challenge. @param finalChallenge true if this is the last challenge send by the server within the success stanza @throws SmackSaslException if a SASL related error occurs. @throws InterruptedException if the connection is interrupted @throws NotConnectedException
[ "The", "server", "is", "challenging", "the", "SASL", "mechanism", "for", "the", "stanza", "he", "just", "sent", ".", "Send", "a", "response", "to", "the", "server", "s", "challenge", "." ]
870756997faec1e1bfabfac0cd6c2395b04da873
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-core/src/main/java/org/jivesoftware/smack/sasl/SASLMechanism.java#L227-L244
26,485
igniterealtime/Smack
smack-extensions/src/main/java/org/jivesoftware/smackx/vcardtemp/VCardManager.java
VCardManager.loadVCard
public VCard loadVCard(EntityBareJid bareJid) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { VCard vcardRequest = new VCard(); vcardRequest.setTo(bareJid); VCard result = connection().createStanzaCollectorAndSend(vcardRequest).nextResultOrThrow(); return result; }
java
public VCard loadVCard(EntityBareJid bareJid) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { VCard vcardRequest = new VCard(); vcardRequest.setTo(bareJid); VCard result = connection().createStanzaCollectorAndSend(vcardRequest).nextResultOrThrow(); return result; }
[ "public", "VCard", "loadVCard", "(", "EntityBareJid", "bareJid", ")", "throws", "NoResponseException", ",", "XMPPErrorException", ",", "NotConnectedException", ",", "InterruptedException", "{", "VCard", "vcardRequest", "=", "new", "VCard", "(", ")", ";", "vcardRequest", ".", "setTo", "(", "bareJid", ")", ";", "VCard", "result", "=", "connection", "(", ")", ".", "createStanzaCollectorAndSend", "(", "vcardRequest", ")", ".", "nextResultOrThrow", "(", ")", ";", "return", "result", ";", "}" ]
Load VCard information for a given user. @param bareJid bareJid of the user. @return VCard. @throws XMPPErrorException @throws NoResponseException if there was no response from the server. @throws NotConnectedException @throws InterruptedException
[ "Load", "VCard", "information", "for", "a", "given", "user", "." ]
870756997faec1e1bfabfac0cd6c2395b04da873
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-extensions/src/main/java/org/jivesoftware/smackx/vcardtemp/VCardManager.java#L136-L141
26,486
igniterealtime/Smack
smack-core/src/main/java/org/jivesoftware/smack/debugger/ReflectionDebuggerFactory.java
ReflectionDebuggerFactory.setDebuggerClass
public static void setDebuggerClass(Class<? extends SmackDebugger> debuggerClass) { if (debuggerClass == null) { System.clearProperty(DEBUGGER_CLASS_PROPERTY_NAME); } else { System.setProperty(DEBUGGER_CLASS_PROPERTY_NAME, debuggerClass.getCanonicalName()); } }
java
public static void setDebuggerClass(Class<? extends SmackDebugger> debuggerClass) { if (debuggerClass == null) { System.clearProperty(DEBUGGER_CLASS_PROPERTY_NAME); } else { System.setProperty(DEBUGGER_CLASS_PROPERTY_NAME, debuggerClass.getCanonicalName()); } }
[ "public", "static", "void", "setDebuggerClass", "(", "Class", "<", "?", "extends", "SmackDebugger", ">", "debuggerClass", ")", "{", "if", "(", "debuggerClass", "==", "null", ")", "{", "System", ".", "clearProperty", "(", "DEBUGGER_CLASS_PROPERTY_NAME", ")", ";", "}", "else", "{", "System", ".", "setProperty", "(", "DEBUGGER_CLASS_PROPERTY_NAME", ",", "debuggerClass", ".", "getCanonicalName", "(", ")", ")", ";", "}", "}" ]
Sets custom debugger class to be created by this factory. @param debuggerClass class to be used by this factory
[ "Sets", "custom", "debugger", "class", "to", "be", "created", "by", "this", "factory", "." ]
870756997faec1e1bfabfac0cd6c2395b04da873
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-core/src/main/java/org/jivesoftware/smack/debugger/ReflectionDebuggerFactory.java#L51-L57
26,487
igniterealtime/Smack
smack-core/src/main/java/org/jivesoftware/smack/debugger/ReflectionDebuggerFactory.java
ReflectionDebuggerFactory.getDebuggerClass
@SuppressWarnings("unchecked") public static Class<SmackDebugger> getDebuggerClass() { String customDebuggerClassName = getCustomDebuggerClassName(); if (customDebuggerClassName == null) { return getOneOfDefaultDebuggerClasses(); } else { try { return (Class<SmackDebugger>) Class.forName(customDebuggerClassName); } catch (Exception e) { LOGGER.log(Level.WARNING, "Unable to instantiate debugger class " + customDebuggerClassName, e); } } // no suitable debugger class found - give up return null; }
java
@SuppressWarnings("unchecked") public static Class<SmackDebugger> getDebuggerClass() { String customDebuggerClassName = getCustomDebuggerClassName(); if (customDebuggerClassName == null) { return getOneOfDefaultDebuggerClasses(); } else { try { return (Class<SmackDebugger>) Class.forName(customDebuggerClassName); } catch (Exception e) { LOGGER.log(Level.WARNING, "Unable to instantiate debugger class " + customDebuggerClassName, e); } } // no suitable debugger class found - give up return null; }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "static", "Class", "<", "SmackDebugger", ">", "getDebuggerClass", "(", ")", "{", "String", "customDebuggerClassName", "=", "getCustomDebuggerClassName", "(", ")", ";", "if", "(", "customDebuggerClassName", "==", "null", ")", "{", "return", "getOneOfDefaultDebuggerClasses", "(", ")", ";", "}", "else", "{", "try", "{", "return", "(", "Class", "<", "SmackDebugger", ">", ")", "Class", ".", "forName", "(", "customDebuggerClassName", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "LOGGER", ".", "log", "(", "Level", ".", "WARNING", ",", "\"Unable to instantiate debugger class \"", "+", "customDebuggerClassName", ",", "e", ")", ";", "}", "}", "// no suitable debugger class found - give up", "return", "null", ";", "}" ]
Returns debugger class used by this factory. @return debugger class that will be used for instantiation by this factory
[ "Returns", "debugger", "class", "used", "by", "this", "factory", "." ]
870756997faec1e1bfabfac0cd6c2395b04da873
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-core/src/main/java/org/jivesoftware/smack/debugger/ReflectionDebuggerFactory.java#L63-L77
26,488
igniterealtime/Smack
smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/ext/notes/ChatNotes.java
ChatNotes.replace
public static final String replace(String string, String oldString, String newString) { if (string == null) { return null; } // If the newString is null or zero length, just return the string since there's nothing // to replace. if (newString == null) { return string; } int i = 0; // Make sure that oldString appears at least once before doing any processing. if ((i = string.indexOf(oldString, i)) >= 0) { // Use char []'s, as they are more efficient to deal with. char[] string2 = string.toCharArray(); char[] newString2 = newString.toCharArray(); int oLength = oldString.length(); StringBuilder buf = new StringBuilder(string2.length); buf.append(string2, 0, i).append(newString2); i += oLength; int j = i; // Replace all remaining instances of oldString with newString. while ((i = string.indexOf(oldString, i)) > 0) { buf.append(string2, j, i - j).append(newString2); i += oLength; j = i; } buf.append(string2, j, string2.length - j); return buf.toString(); } return string; }
java
public static final String replace(String string, String oldString, String newString) { if (string == null) { return null; } // If the newString is null or zero length, just return the string since there's nothing // to replace. if (newString == null) { return string; } int i = 0; // Make sure that oldString appears at least once before doing any processing. if ((i = string.indexOf(oldString, i)) >= 0) { // Use char []'s, as they are more efficient to deal with. char[] string2 = string.toCharArray(); char[] newString2 = newString.toCharArray(); int oLength = oldString.length(); StringBuilder buf = new StringBuilder(string2.length); buf.append(string2, 0, i).append(newString2); i += oLength; int j = i; // Replace all remaining instances of oldString with newString. while ((i = string.indexOf(oldString, i)) > 0) { buf.append(string2, j, i - j).append(newString2); i += oLength; j = i; } buf.append(string2, j, string2.length - j); return buf.toString(); } return string; }
[ "public", "static", "final", "String", "replace", "(", "String", "string", ",", "String", "oldString", ",", "String", "newString", ")", "{", "if", "(", "string", "==", "null", ")", "{", "return", "null", ";", "}", "// If the newString is null or zero length, just return the string since there's nothing", "// to replace.", "if", "(", "newString", "==", "null", ")", "{", "return", "string", ";", "}", "int", "i", "=", "0", ";", "// Make sure that oldString appears at least once before doing any processing.", "if", "(", "(", "i", "=", "string", ".", "indexOf", "(", "oldString", ",", "i", ")", ")", ">=", "0", ")", "{", "// Use char []'s, as they are more efficient to deal with.", "char", "[", "]", "string2", "=", "string", ".", "toCharArray", "(", ")", ";", "char", "[", "]", "newString2", "=", "newString", ".", "toCharArray", "(", ")", ";", "int", "oLength", "=", "oldString", ".", "length", "(", ")", ";", "StringBuilder", "buf", "=", "new", "StringBuilder", "(", "string2", ".", "length", ")", ";", "buf", ".", "append", "(", "string2", ",", "0", ",", "i", ")", ".", "append", "(", "newString2", ")", ";", "i", "+=", "oLength", ";", "int", "j", "=", "i", ";", "// Replace all remaining instances of oldString with newString.", "while", "(", "(", "i", "=", "string", ".", "indexOf", "(", "oldString", ",", "i", ")", ")", ">", "0", ")", "{", "buf", ".", "append", "(", "string2", ",", "j", ",", "i", "-", "j", ")", ".", "append", "(", "newString2", ")", ";", "i", "+=", "oLength", ";", "j", "=", "i", ";", "}", "buf", ".", "append", "(", "string2", ",", "j", ",", "string2", ".", "length", "-", "j", ")", ";", "return", "buf", ".", "toString", "(", ")", ";", "}", "return", "string", ";", "}" ]
Replaces all instances of oldString with newString in string. @param string the String to search to perform replacements on @param oldString the String that should be replaced by newString @param newString the String that will replace all instances of oldString @return a String will all instances of oldString replaced by newString
[ "Replaces", "all", "instances", "of", "oldString", "with", "newString", "in", "string", "." ]
870756997faec1e1bfabfac0cd6c2395b04da873
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/ext/notes/ChatNotes.java#L123-L153
26,489
igniterealtime/Smack
smack-legacy/src/main/java/org/jivesoftware/smackx/xroster/RosterExchangeManager.java
RosterExchangeManager.send
public void send(Roster roster, Jid targetUserID) throws NotConnectedException, InterruptedException { // Create a new message to send the roster Message msg = new Message(targetUserID); // Create a RosterExchange Package and add it to the message RosterExchange rosterExchange = new RosterExchange(roster); msg.addExtension(rosterExchange); XMPPConnection connection = weakRefConnection.get(); // Send the message that contains the roster connection.sendStanza(msg); }
java
public void send(Roster roster, Jid targetUserID) throws NotConnectedException, InterruptedException { // Create a new message to send the roster Message msg = new Message(targetUserID); // Create a RosterExchange Package and add it to the message RosterExchange rosterExchange = new RosterExchange(roster); msg.addExtension(rosterExchange); XMPPConnection connection = weakRefConnection.get(); // Send the message that contains the roster connection.sendStanza(msg); }
[ "public", "void", "send", "(", "Roster", "roster", ",", "Jid", "targetUserID", ")", "throws", "NotConnectedException", ",", "InterruptedException", "{", "// Create a new message to send the roster", "Message", "msg", "=", "new", "Message", "(", "targetUserID", ")", ";", "// Create a RosterExchange Package and add it to the message", "RosterExchange", "rosterExchange", "=", "new", "RosterExchange", "(", "roster", ")", ";", "msg", ".", "addExtension", "(", "rosterExchange", ")", ";", "XMPPConnection", "connection", "=", "weakRefConnection", ".", "get", "(", ")", ";", "// Send the message that contains the roster", "connection", ".", "sendStanza", "(", "msg", ")", ";", "}" ]
Sends a roster to userID. All the entries of the roster will be sent to the target user. @param roster the roster to send @param targetUserID the user that will receive the roster entries @throws NotConnectedException @throws InterruptedException
[ "Sends", "a", "roster", "to", "userID", ".", "All", "the", "entries", "of", "the", "roster", "will", "be", "sent", "to", "the", "target", "user", "." ]
870756997faec1e1bfabfac0cd6c2395b04da873
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-legacy/src/main/java/org/jivesoftware/smackx/xroster/RosterExchangeManager.java#L123-L133
26,490
igniterealtime/Smack
smack-legacy/src/main/java/org/jivesoftware/smackx/xroster/RosterExchangeManager.java
RosterExchangeManager.send
public void send(RosterEntry rosterEntry, Jid targetUserID) throws NotConnectedException, InterruptedException { // Create a new message to send the roster Message msg = new Message(targetUserID); // Create a RosterExchange Package and add it to the message RosterExchange rosterExchange = new RosterExchange(); rosterExchange.addRosterEntry(rosterEntry); msg.addExtension(rosterExchange); XMPPConnection connection = weakRefConnection.get(); // Send the message that contains the roster connection.sendStanza(msg); }
java
public void send(RosterEntry rosterEntry, Jid targetUserID) throws NotConnectedException, InterruptedException { // Create a new message to send the roster Message msg = new Message(targetUserID); // Create a RosterExchange Package and add it to the message RosterExchange rosterExchange = new RosterExchange(); rosterExchange.addRosterEntry(rosterEntry); msg.addExtension(rosterExchange); XMPPConnection connection = weakRefConnection.get(); // Send the message that contains the roster connection.sendStanza(msg); }
[ "public", "void", "send", "(", "RosterEntry", "rosterEntry", ",", "Jid", "targetUserID", ")", "throws", "NotConnectedException", ",", "InterruptedException", "{", "// Create a new message to send the roster", "Message", "msg", "=", "new", "Message", "(", "targetUserID", ")", ";", "// Create a RosterExchange Package and add it to the message", "RosterExchange", "rosterExchange", "=", "new", "RosterExchange", "(", ")", ";", "rosterExchange", ".", "addRosterEntry", "(", "rosterEntry", ")", ";", "msg", ".", "addExtension", "(", "rosterExchange", ")", ";", "XMPPConnection", "connection", "=", "weakRefConnection", ".", "get", "(", ")", ";", "// Send the message that contains the roster", "connection", ".", "sendStanza", "(", "msg", ")", ";", "}" ]
Sends a roster entry to userID. @param rosterEntry the roster entry to send @param targetUserID the user that will receive the roster entries @throws NotConnectedException @throws InterruptedException
[ "Sends", "a", "roster", "entry", "to", "userID", "." ]
870756997faec1e1bfabfac0cd6c2395b04da873
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-legacy/src/main/java/org/jivesoftware/smackx/xroster/RosterExchangeManager.java#L143-L154
26,491
igniterealtime/Smack
smack-legacy/src/main/java/org/jivesoftware/smackx/xroster/RosterExchangeManager.java
RosterExchangeManager.send
public void send(RosterGroup rosterGroup, Jid targetUserID) throws NotConnectedException, InterruptedException { // Create a new message to send the roster Message msg = new Message(targetUserID); // Create a RosterExchange Package and add it to the message RosterExchange rosterExchange = new RosterExchange(); for (RosterEntry entry : rosterGroup.getEntries()) { rosterExchange.addRosterEntry(entry); } msg.addExtension(rosterExchange); XMPPConnection connection = weakRefConnection.get(); // Send the message that contains the roster connection.sendStanza(msg); }
java
public void send(RosterGroup rosterGroup, Jid targetUserID) throws NotConnectedException, InterruptedException { // Create a new message to send the roster Message msg = new Message(targetUserID); // Create a RosterExchange Package and add it to the message RosterExchange rosterExchange = new RosterExchange(); for (RosterEntry entry : rosterGroup.getEntries()) { rosterExchange.addRosterEntry(entry); } msg.addExtension(rosterExchange); XMPPConnection connection = weakRefConnection.get(); // Send the message that contains the roster connection.sendStanza(msg); }
[ "public", "void", "send", "(", "RosterGroup", "rosterGroup", ",", "Jid", "targetUserID", ")", "throws", "NotConnectedException", ",", "InterruptedException", "{", "// Create a new message to send the roster", "Message", "msg", "=", "new", "Message", "(", "targetUserID", ")", ";", "// Create a RosterExchange Package and add it to the message", "RosterExchange", "rosterExchange", "=", "new", "RosterExchange", "(", ")", ";", "for", "(", "RosterEntry", "entry", ":", "rosterGroup", ".", "getEntries", "(", ")", ")", "{", "rosterExchange", ".", "addRosterEntry", "(", "entry", ")", ";", "}", "msg", ".", "addExtension", "(", "rosterExchange", ")", ";", "XMPPConnection", "connection", "=", "weakRefConnection", ".", "get", "(", ")", ";", "// Send the message that contains the roster", "connection", ".", "sendStanza", "(", "msg", ")", ";", "}" ]
Sends a roster group to userID. All the entries of the group will be sent to the target user. @param rosterGroup the roster group to send @param targetUserID the user that will receive the roster entries @throws NotConnectedException @throws InterruptedException
[ "Sends", "a", "roster", "group", "to", "userID", ".", "All", "the", "entries", "of", "the", "group", "will", "be", "sent", "to", "the", "target", "user", "." ]
870756997faec1e1bfabfac0cd6c2395b04da873
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-legacy/src/main/java/org/jivesoftware/smackx/xroster/RosterExchangeManager.java#L165-L178
26,492
igniterealtime/Smack
smack-legacy/src/main/java/org/jivesoftware/smackx/xroster/RosterExchangeManager.java
RosterExchangeManager.fireRosterExchangeListeners
private void fireRosterExchangeListeners(Jid from, Iterator<RemoteRosterEntry> remoteRosterEntries) { RosterExchangeListener[] listeners; synchronized (rosterExchangeListeners) { listeners = new RosterExchangeListener[rosterExchangeListeners.size()]; rosterExchangeListeners.toArray(listeners); } for (RosterExchangeListener listener : listeners) { listener.entriesReceived(from, remoteRosterEntries); } }
java
private void fireRosterExchangeListeners(Jid from, Iterator<RemoteRosterEntry> remoteRosterEntries) { RosterExchangeListener[] listeners; synchronized (rosterExchangeListeners) { listeners = new RosterExchangeListener[rosterExchangeListeners.size()]; rosterExchangeListeners.toArray(listeners); } for (RosterExchangeListener listener : listeners) { listener.entriesReceived(from, remoteRosterEntries); } }
[ "private", "void", "fireRosterExchangeListeners", "(", "Jid", "from", ",", "Iterator", "<", "RemoteRosterEntry", ">", "remoteRosterEntries", ")", "{", "RosterExchangeListener", "[", "]", "listeners", ";", "synchronized", "(", "rosterExchangeListeners", ")", "{", "listeners", "=", "new", "RosterExchangeListener", "[", "rosterExchangeListeners", ".", "size", "(", ")", "]", ";", "rosterExchangeListeners", ".", "toArray", "(", "listeners", ")", ";", "}", "for", "(", "RosterExchangeListener", "listener", ":", "listeners", ")", "{", "listener", ".", "entriesReceived", "(", "from", ",", "remoteRosterEntries", ")", ";", "}", "}" ]
Fires roster exchange listeners.
[ "Fires", "roster", "exchange", "listeners", "." ]
870756997faec1e1bfabfac0cd6c2395b04da873
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-legacy/src/main/java/org/jivesoftware/smackx/xroster/RosterExchangeManager.java#L183-L192
26,493
igniterealtime/Smack
smack-extensions/src/main/java/org/jivesoftware/smackx/search/UserSearch.java
UserSearch.getSearchForm
public Form getSearchForm(XMPPConnection con, DomainBareJid searchService) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { UserSearch search = new UserSearch(); search.setType(IQ.Type.get); search.setTo(searchService); IQ response = con.createStanzaCollectorAndSend(search).nextResultOrThrow(); return Form.getFormFrom(response); }
java
public Form getSearchForm(XMPPConnection con, DomainBareJid searchService) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { UserSearch search = new UserSearch(); search.setType(IQ.Type.get); search.setTo(searchService); IQ response = con.createStanzaCollectorAndSend(search).nextResultOrThrow(); return Form.getFormFrom(response); }
[ "public", "Form", "getSearchForm", "(", "XMPPConnection", "con", ",", "DomainBareJid", "searchService", ")", "throws", "NoResponseException", ",", "XMPPErrorException", ",", "NotConnectedException", ",", "InterruptedException", "{", "UserSearch", "search", "=", "new", "UserSearch", "(", ")", ";", "search", ".", "setType", "(", "IQ", ".", "Type", ".", "get", ")", ";", "search", ".", "setTo", "(", "searchService", ")", ";", "IQ", "response", "=", "con", ".", "createStanzaCollectorAndSend", "(", "search", ")", ".", "nextResultOrThrow", "(", ")", ";", "return", "Form", ".", "getFormFrom", "(", "response", ")", ";", "}" ]
Returns the form for all search fields supported by the search service. @param con the current XMPPConnection. @param searchService the search service to use. (ex. search.jivesoftware.com) @return the search form received by the server. @throws XMPPErrorException @throws NoResponseException @throws NotConnectedException @throws InterruptedException
[ "Returns", "the", "form", "for", "all", "search", "fields", "supported", "by", "the", "search", "service", "." ]
870756997faec1e1bfabfac0cd6c2395b04da873
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-extensions/src/main/java/org/jivesoftware/smackx/search/UserSearch.java#L73-L80
26,494
igniterealtime/Smack
smack-extensions/src/main/java/org/jivesoftware/smackx/receipts/DeliveryReceiptRequest.java
DeliveryReceiptRequest.addTo
public static String addTo(Message message) { if (message.getStanzaId() == null) { message.setStanzaId(StanzaIdUtil.newStanzaId()); } message.addExtension(new DeliveryReceiptRequest()); return message.getStanzaId(); }
java
public static String addTo(Message message) { if (message.getStanzaId() == null) { message.setStanzaId(StanzaIdUtil.newStanzaId()); } message.addExtension(new DeliveryReceiptRequest()); return message.getStanzaId(); }
[ "public", "static", "String", "addTo", "(", "Message", "message", ")", "{", "if", "(", "message", ".", "getStanzaId", "(", ")", "==", "null", ")", "{", "message", ".", "setStanzaId", "(", "StanzaIdUtil", ".", "newStanzaId", "(", ")", ")", ";", "}", "message", ".", "addExtension", "(", "new", "DeliveryReceiptRequest", "(", ")", ")", ";", "return", "message", ".", "getStanzaId", "(", ")", ";", "}" ]
Add a delivery receipt request to an outgoing packet. Only message packets may contain receipt requests as of XEP-0184, therefore only allow Message as the parameter type. @param message Message object to add a request to @return the Message ID which will be used as receipt ID
[ "Add", "a", "delivery", "receipt", "request", "to", "an", "outgoing", "packet", "." ]
870756997faec1e1bfabfac0cd6c2395b04da873
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-extensions/src/main/java/org/jivesoftware/smackx/receipts/DeliveryReceiptRequest.java#L86-L92
26,495
igniterealtime/Smack
smack-openpgp/src/main/java/org/jivesoftware/smackx/ox/util/OpenPgpPubSubUtil.java
OpenPgpPubSubUtil.publishPublicKey
public static void publishPublicKey(PepManager pepManager, PubkeyElement pubkeyElement, OpenPgpV4Fingerprint fingerprint) throws InterruptedException, PubSubException.NotALeafNodeException, XMPPException.XMPPErrorException, SmackException.NotConnectedException, SmackException.NoResponseException { String keyNodeName = PEP_NODE_PUBLIC_KEY(fingerprint); PubSubManager pm = pepManager.getPepPubSubManager(); // Check if key available at data node // If not, publish key to data node LeafNode keyNode = pm.getOrCreateLeafNode(keyNodeName); changeAccessModelIfNecessary(keyNode, AccessModel.open); List<Item> items = keyNode.getItems(1); if (items.isEmpty()) { LOGGER.log(Level.FINE, "Node " + keyNodeName + " is empty. Publish."); keyNode.publish(new PayloadItem<>(pubkeyElement)); } else { LOGGER.log(Level.FINE, "Node " + keyNodeName + " already contains key. Skip."); } // Fetch IDs from metadata node LeafNode metadataNode = pm.getOrCreateLeafNode(PEP_NODE_PUBLIC_KEYS); changeAccessModelIfNecessary(metadataNode, AccessModel.open); List<PayloadItem<PublicKeysListElement>> metadataItems = metadataNode.getItems(1); PublicKeysListElement.Builder builder = PublicKeysListElement.builder(); if (!metadataItems.isEmpty() && metadataItems.get(0).getPayload() != null) { // Add old entries back to list. PublicKeysListElement publishedList = metadataItems.get(0).getPayload(); for (PublicKeysListElement.PubkeyMetadataElement meta : publishedList.getMetadata().values()) { builder.addMetadata(meta); } } builder.addMetadata(new PublicKeysListElement.PubkeyMetadataElement(fingerprint, new Date())); // Publish IDs to metadata node metadataNode.publish(new PayloadItem<>(builder.build())); }
java
public static void publishPublicKey(PepManager pepManager, PubkeyElement pubkeyElement, OpenPgpV4Fingerprint fingerprint) throws InterruptedException, PubSubException.NotALeafNodeException, XMPPException.XMPPErrorException, SmackException.NotConnectedException, SmackException.NoResponseException { String keyNodeName = PEP_NODE_PUBLIC_KEY(fingerprint); PubSubManager pm = pepManager.getPepPubSubManager(); // Check if key available at data node // If not, publish key to data node LeafNode keyNode = pm.getOrCreateLeafNode(keyNodeName); changeAccessModelIfNecessary(keyNode, AccessModel.open); List<Item> items = keyNode.getItems(1); if (items.isEmpty()) { LOGGER.log(Level.FINE, "Node " + keyNodeName + " is empty. Publish."); keyNode.publish(new PayloadItem<>(pubkeyElement)); } else { LOGGER.log(Level.FINE, "Node " + keyNodeName + " already contains key. Skip."); } // Fetch IDs from metadata node LeafNode metadataNode = pm.getOrCreateLeafNode(PEP_NODE_PUBLIC_KEYS); changeAccessModelIfNecessary(metadataNode, AccessModel.open); List<PayloadItem<PublicKeysListElement>> metadataItems = metadataNode.getItems(1); PublicKeysListElement.Builder builder = PublicKeysListElement.builder(); if (!metadataItems.isEmpty() && metadataItems.get(0).getPayload() != null) { // Add old entries back to list. PublicKeysListElement publishedList = metadataItems.get(0).getPayload(); for (PublicKeysListElement.PubkeyMetadataElement meta : publishedList.getMetadata().values()) { builder.addMetadata(meta); } } builder.addMetadata(new PublicKeysListElement.PubkeyMetadataElement(fingerprint, new Date())); // Publish IDs to metadata node metadataNode.publish(new PayloadItem<>(builder.build())); }
[ "public", "static", "void", "publishPublicKey", "(", "PepManager", "pepManager", ",", "PubkeyElement", "pubkeyElement", ",", "OpenPgpV4Fingerprint", "fingerprint", ")", "throws", "InterruptedException", ",", "PubSubException", ".", "NotALeafNodeException", ",", "XMPPException", ".", "XMPPErrorException", ",", "SmackException", ".", "NotConnectedException", ",", "SmackException", ".", "NoResponseException", "{", "String", "keyNodeName", "=", "PEP_NODE_PUBLIC_KEY", "(", "fingerprint", ")", ";", "PubSubManager", "pm", "=", "pepManager", ".", "getPepPubSubManager", "(", ")", ";", "// Check if key available at data node", "// If not, publish key to data node", "LeafNode", "keyNode", "=", "pm", ".", "getOrCreateLeafNode", "(", "keyNodeName", ")", ";", "changeAccessModelIfNecessary", "(", "keyNode", ",", "AccessModel", ".", "open", ")", ";", "List", "<", "Item", ">", "items", "=", "keyNode", ".", "getItems", "(", "1", ")", ";", "if", "(", "items", ".", "isEmpty", "(", ")", ")", "{", "LOGGER", ".", "log", "(", "Level", ".", "FINE", ",", "\"Node \"", "+", "keyNodeName", "+", "\" is empty. Publish.\"", ")", ";", "keyNode", ".", "publish", "(", "new", "PayloadItem", "<>", "(", "pubkeyElement", ")", ")", ";", "}", "else", "{", "LOGGER", ".", "log", "(", "Level", ".", "FINE", ",", "\"Node \"", "+", "keyNodeName", "+", "\" already contains key. Skip.\"", ")", ";", "}", "// Fetch IDs from metadata node", "LeafNode", "metadataNode", "=", "pm", ".", "getOrCreateLeafNode", "(", "PEP_NODE_PUBLIC_KEYS", ")", ";", "changeAccessModelIfNecessary", "(", "metadataNode", ",", "AccessModel", ".", "open", ")", ";", "List", "<", "PayloadItem", "<", "PublicKeysListElement", ">", ">", "metadataItems", "=", "metadataNode", ".", "getItems", "(", "1", ")", ";", "PublicKeysListElement", ".", "Builder", "builder", "=", "PublicKeysListElement", ".", "builder", "(", ")", ";", "if", "(", "!", "metadataItems", ".", "isEmpty", "(", ")", "&&", "metadataItems", ".", "get", "(", "0", ")", ".", "getPayload", "(", ")", "!=", "null", ")", "{", "// Add old entries back to list.", "PublicKeysListElement", "publishedList", "=", "metadataItems", ".", "get", "(", "0", ")", ".", "getPayload", "(", ")", ";", "for", "(", "PublicKeysListElement", ".", "PubkeyMetadataElement", "meta", ":", "publishedList", ".", "getMetadata", "(", ")", ".", "values", "(", ")", ")", "{", "builder", ".", "addMetadata", "(", "meta", ")", ";", "}", "}", "builder", ".", "addMetadata", "(", "new", "PublicKeysListElement", ".", "PubkeyMetadataElement", "(", "fingerprint", ",", "new", "Date", "(", ")", ")", ")", ";", "// Publish IDs to metadata node", "metadataNode", ".", "publish", "(", "new", "PayloadItem", "<>", "(", "builder", ".", "build", "(", ")", ")", ")", ";", "}" ]
Publish the users OpenPGP public key to the public key node if necessary. Also announce the key to other users by updating the metadata node. @see <a href="https://xmpp.org/extensions/xep-0373.html#annoucning-pubkey">XEP-0373 §4.1</a> @param pepManager The PEP manager. @param pubkeyElement {@link PubkeyElement} containing the public key @param fingerprint fingerprint of the public key @throws InterruptedException if the thread gets interrupted. @throws PubSubException.NotALeafNodeException if either the metadata node or the public key node is not a {@link LeafNode}. @throws XMPPException.XMPPErrorException in case of an XMPP protocol error. @throws SmackException.NotConnectedException if we are not connected. @throws SmackException.NoResponseException if the server doesn't respond.
[ "Publish", "the", "users", "OpenPGP", "public", "key", "to", "the", "public", "key", "node", "if", "necessary", ".", "Also", "announce", "the", "key", "to", "other", "users", "by", "updating", "the", "metadata", "node", "." ]
870756997faec1e1bfabfac0cd6c2395b04da873
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-openpgp/src/main/java/org/jivesoftware/smackx/ox/util/OpenPgpPubSubUtil.java#L126-L162
26,496
igniterealtime/Smack
smack-openpgp/src/main/java/org/jivesoftware/smackx/ox/util/OpenPgpPubSubUtil.java
OpenPgpPubSubUtil.fetchPubkeysList
public static PublicKeysListElement fetchPubkeysList(XMPPConnection connection) throws InterruptedException, XMPPException.XMPPErrorException, PubSubException.NotAPubSubNodeException, PubSubException.NotALeafNodeException, SmackException.NotConnectedException, SmackException.NoResponseException { return fetchPubkeysList(connection, null); }
java
public static PublicKeysListElement fetchPubkeysList(XMPPConnection connection) throws InterruptedException, XMPPException.XMPPErrorException, PubSubException.NotAPubSubNodeException, PubSubException.NotALeafNodeException, SmackException.NotConnectedException, SmackException.NoResponseException { return fetchPubkeysList(connection, null); }
[ "public", "static", "PublicKeysListElement", "fetchPubkeysList", "(", "XMPPConnection", "connection", ")", "throws", "InterruptedException", ",", "XMPPException", ".", "XMPPErrorException", ",", "PubSubException", ".", "NotAPubSubNodeException", ",", "PubSubException", ".", "NotALeafNodeException", ",", "SmackException", ".", "NotConnectedException", ",", "SmackException", ".", "NoResponseException", "{", "return", "fetchPubkeysList", "(", "connection", ",", "null", ")", ";", "}" ]
Consult the public key metadata node and fetch a list of all of our published OpenPGP public keys. @see <a href="https://xmpp.org/extensions/xep-0373.html#discover-pubkey-list"> XEP-0373 §4.3: Discovering Public Keys of a User</a> @param connection XMPP connection @return content of our metadata node. @throws InterruptedException if the thread gets interrupted. @throws XMPPException.XMPPErrorException in case of an XMPP protocol exception. @throws PubSubException.NotAPubSubNodeException in case the queried entity is not a PubSub node @throws PubSubException.NotALeafNodeException in case the queried node is not a {@link LeafNode} @throws SmackException.NotConnectedException in case we are not connected @throws SmackException.NoResponseException in case the server doesn't respond
[ "Consult", "the", "public", "key", "metadata", "node", "and", "fetch", "a", "list", "of", "all", "of", "our", "published", "OpenPGP", "public", "keys", "." ]
870756997faec1e1bfabfac0cd6c2395b04da873
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-openpgp/src/main/java/org/jivesoftware/smackx/ox/util/OpenPgpPubSubUtil.java#L180-L184
26,497
igniterealtime/Smack
smack-openpgp/src/main/java/org/jivesoftware/smackx/ox/util/OpenPgpPubSubUtil.java
OpenPgpPubSubUtil.deletePubkeysListNode
public static boolean deletePubkeysListNode(PepManager pepManager) throws XMPPException.XMPPErrorException, SmackException.NotConnectedException, InterruptedException, SmackException.NoResponseException { PubSubManager pm = pepManager.getPepPubSubManager(); return pm.deleteNode(PEP_NODE_PUBLIC_KEYS); }
java
public static boolean deletePubkeysListNode(PepManager pepManager) throws XMPPException.XMPPErrorException, SmackException.NotConnectedException, InterruptedException, SmackException.NoResponseException { PubSubManager pm = pepManager.getPepPubSubManager(); return pm.deleteNode(PEP_NODE_PUBLIC_KEYS); }
[ "public", "static", "boolean", "deletePubkeysListNode", "(", "PepManager", "pepManager", ")", "throws", "XMPPException", ".", "XMPPErrorException", ",", "SmackException", ".", "NotConnectedException", ",", "InterruptedException", ",", "SmackException", ".", "NoResponseException", "{", "PubSubManager", "pm", "=", "pepManager", ".", "getPepPubSubManager", "(", ")", ";", "return", "pm", ".", "deleteNode", "(", "PEP_NODE_PUBLIC_KEYS", ")", ";", "}" ]
Delete our metadata node. @param pepManager The PEP manager. @throws XMPPException.XMPPErrorException in case of an XMPP protocol error. @throws SmackException.NotConnectedException if we are not connected. @throws InterruptedException if the thread is interrupted. @throws SmackException.NoResponseException if the server doesn't respond. @return <code>true</code> if the node existed and was deleted, <code>false</code> if the node did not exist.
[ "Delete", "our", "metadata", "node", "." ]
870756997faec1e1bfabfac0cd6c2395b04da873
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-openpgp/src/main/java/org/jivesoftware/smackx/ox/util/OpenPgpPubSubUtil.java#L230-L235
26,498
igniterealtime/Smack
smack-openpgp/src/main/java/org/jivesoftware/smackx/ox/util/OpenPgpPubSubUtil.java
OpenPgpPubSubUtil.deleteSecretKeyNode
public static boolean deleteSecretKeyNode(PepManager pepManager) throws XMPPException.XMPPErrorException, SmackException.NotConnectedException, InterruptedException, SmackException.NoResponseException { PubSubManager pm = pepManager.getPepPubSubManager(); return pm.deleteNode(PEP_NODE_SECRET_KEY); }
java
public static boolean deleteSecretKeyNode(PepManager pepManager) throws XMPPException.XMPPErrorException, SmackException.NotConnectedException, InterruptedException, SmackException.NoResponseException { PubSubManager pm = pepManager.getPepPubSubManager(); return pm.deleteNode(PEP_NODE_SECRET_KEY); }
[ "public", "static", "boolean", "deleteSecretKeyNode", "(", "PepManager", "pepManager", ")", "throws", "XMPPException", ".", "XMPPErrorException", ",", "SmackException", ".", "NotConnectedException", ",", "InterruptedException", ",", "SmackException", ".", "NoResponseException", "{", "PubSubManager", "pm", "=", "pepManager", ".", "getPepPubSubManager", "(", ")", ";", "return", "pm", ".", "deleteNode", "(", "PEP_NODE_SECRET_KEY", ")", ";", "}" ]
Delete the private backup node. @param pepManager the PEP manager. @throws XMPPException.XMPPErrorException if there is an XMPP protocol related issue @throws SmackException.NotConnectedException if we are not connected @throws InterruptedException if the thread gets interrupted @throws SmackException.NoResponseException if the server sends no response @return <code>true</code> if the node existed and was deleted, <code>false</code> if the node did not exist.
[ "Delete", "the", "private", "backup", "node", "." ]
870756997faec1e1bfabfac0cd6c2395b04da873
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-openpgp/src/main/java/org/jivesoftware/smackx/ox/util/OpenPgpPubSubUtil.java#L396-L401
26,499
igniterealtime/Smack
smack-experimental/src/main/java/org/jivesoftware/smackx/iot/discovery/IoTDiscoveryManager.java
IoTDiscoveryManager.findRegistry
public Jid findRegistry() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { if (preconfiguredRegistry != null) { return preconfiguredRegistry; } final XMPPConnection connection = connection(); ServiceDiscoveryManager sdm = ServiceDiscoveryManager.getInstanceFor(connection); List<DiscoverInfo> discoverInfos = sdm.findServicesDiscoverInfo(Constants.IOT_DISCOVERY_NAMESPACE, true, true); if (!discoverInfos.isEmpty()) { return discoverInfos.get(0).getFrom(); } return null; }
java
public Jid findRegistry() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { if (preconfiguredRegistry != null) { return preconfiguredRegistry; } final XMPPConnection connection = connection(); ServiceDiscoveryManager sdm = ServiceDiscoveryManager.getInstanceFor(connection); List<DiscoverInfo> discoverInfos = sdm.findServicesDiscoverInfo(Constants.IOT_DISCOVERY_NAMESPACE, true, true); if (!discoverInfos.isEmpty()) { return discoverInfos.get(0).getFrom(); } return null; }
[ "public", "Jid", "findRegistry", "(", ")", "throws", "NoResponseException", ",", "XMPPErrorException", ",", "NotConnectedException", ",", "InterruptedException", "{", "if", "(", "preconfiguredRegistry", "!=", "null", ")", "{", "return", "preconfiguredRegistry", ";", "}", "final", "XMPPConnection", "connection", "=", "connection", "(", ")", ";", "ServiceDiscoveryManager", "sdm", "=", "ServiceDiscoveryManager", ".", "getInstanceFor", "(", "connection", ")", ";", "List", "<", "DiscoverInfo", ">", "discoverInfos", "=", "sdm", ".", "findServicesDiscoverInfo", "(", "Constants", ".", "IOT_DISCOVERY_NAMESPACE", ",", "true", ",", "true", ")", ";", "if", "(", "!", "discoverInfos", ".", "isEmpty", "(", ")", ")", "{", "return", "discoverInfos", ".", "get", "(", "0", ")", ".", "getFrom", "(", ")", ";", "}", "return", "null", ";", "}" ]
Try to find an XMPP IoT registry. @return the JID of a Thing Registry if one could be found, <code>null</code> otherwise. @throws InterruptedException @throws NotConnectedException @throws XMPPErrorException @throws NoResponseException @see <a href="http://xmpp.org/extensions/xep-0347.html#findingregistry">XEP-0347 § 3.5 Finding Thing Registry</a>
[ "Try", "to", "find", "an", "XMPP", "IoT", "registry", "." ]
870756997faec1e1bfabfac0cd6c2395b04da873
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-experimental/src/main/java/org/jivesoftware/smackx/iot/discovery/IoTDiscoveryManager.java#L220-L234