protected PsmMethodAction(Class c, String m, Class[] argArray) { // This prevents IllegalAccessExceptions when attempting to // invoke methods on a class that is in another package and not // defined 'public'. if (!Modifier.isPublic(c.getModifiers())) { throw new IllegalPsmMethodActionException("Action class must be public."); } try { method = c.getMethod(m, argArray); } catch (NoSuchMethodException ex) { throw new IllegalPsmMethodActionException(ex.toString() + ": method " + m); } // Check each exception this method declares thrown. If it declares // exceptions, and any of them are not runtime exceptions, abort. Class[] exceptionTypes = method.getExceptionTypes(); for (int i = 0; i < exceptionTypes.length; i++) { Class exceptionClass = exceptionTypes[i]; if (!RuntimeException.class.isAssignableFrom(exceptionClass)) { throw new IllegalPsmMethodActionException( "Method must not declare non-Runtime " + "exceptions."); } } // Ensure that the method returns PsmEvent if (PsmEvent.class != method.getReturnType()) { throw new IllegalPsmMethodActionException("Method return type must be PsmEvent"); } // Ensure that both the method is both public and static. if (!Modifier.isStatic(method.getModifiers()) || !Modifier.isPublic(method.getModifiers())) { throw new IllegalPsmMethodActionException("Method " + m + " must be static and public."); } }
/** * Calls all public methods declared in the class corresponding to the given object. Does not * include methods from superclasses. * * @param object object to call the public methods on * @param comparator method comparator, allows running the methods in a specific order * @return list of methods invoked, including the parameters used for calling them */ private static List<MethodInvocation> callPublicMethodsInOrder( Object object, Comparator<Method> comparator) { try { List<MethodInvocation> invocations = new ArrayList<>(); Method[] methods = object.getClass().getDeclaredMethods(); if (comparator != null) Arrays.sort(methods, comparator); for (Method method : methods) { if (Modifier.isStatic(method.getModifiers()) || !Modifier.isPublic(method.getModifiers())) continue; Object[] params = new Object[method.getParameterTypes().length]; for (int i = 0; i < method.getParameterTypes().length; i++) { params[i] = instantiateType(method.getParameterTypes()[i]); } method.invoke(object, params); invocations.add(new MethodInvocation(method.getName(), params)); } return invocations; } catch (Exception ex) { ex.printStackTrace(); assertTrue( "Error calling public methods on object " + object + " (" + object.getClass().getSimpleName() + ")", false); return new ArrayList<>(); } }
private void validateNonRuleMethod(Method method, ValidationProblemCollector problems) { if (!Modifier.isPrivate(method.getModifiers()) && !Modifier.isStatic(method.getModifiers()) && !method.isSynthetic() && !ModelSchemaUtils.isObjectMethod(method)) { problems.add(method, "A method that is not annotated as a rule must be private"); } }
private void validateRuleMethod( MethodRuleDefinition<?, ?> ruleDefinition, Method ruleMethod, ValidationProblemCollector problems) { if (Modifier.isPrivate(ruleMethod.getModifiers())) { problems.add(ruleMethod, "A rule method cannot be private"); } if (Modifier.isAbstract(ruleMethod.getModifiers())) { problems.add(ruleMethod, "A rule method cannot be abstract"); } if (ruleMethod.getTypeParameters().length > 0) { problems.add(ruleMethod, "Cannot have type variables (i.e. cannot be a generic method)"); } // TODO validations on method: synthetic, bridge methods, varargs, abstract, native ModelType<?> returnType = ModelType.returnType(ruleMethod); if (returnType.isRawClassOfParameterizedType()) { problems.add( ruleMethod, "Raw type " + returnType + " used for return type (all type parameters must be specified of parameterized type)"); } for (int i = 0; i < ruleDefinition.getReferences().size(); i++) { ModelReference<?> reference = ruleDefinition.getReferences().get(i); if (reference.getType().isRawClassOfParameterizedType()) { problems.add( ruleMethod, "Raw type " + reference.getType() + " used for parameter " + (i + 1) + " (all type parameters must be specified of parameterized type)"); } if (reference.getPath() != null) { try { ModelPath.validatePath(reference.getPath().toString()); } catch (Exception e) { problems.add( ruleDefinition, "The declared model element path '" + reference.getPath() + "' used for parameter " + (i + 1) + " is not a valid path", e); } } } }
/** * Gets the ObjectLoader for the specified class. * * @param classtype the class * @return the ObjectLoader */ public static XML.ObjectLoader getLoader(Class classtype) { // look for registered loader first ObjectLoader loader = (ObjectLoader) loaders.get(classtype); // if no registered loader, look for static getLoader() method in class if (loader == null) { try { Method method = classtype.getMethod("getLoader", (Class[]) null); // $NON-NLS-1$ if (method != null && Modifier.isStatic(method.getModifiers())) { loader = (ObjectLoader) method.invoke(null, (Object[]) null); if (loader != null) { // register loader for future calls setLoader(classtype, loader); } } } catch (Exception ex) { /** empty block */ } } // if still no loader found, use the default loader if (loader == null) { if (defaultLoader == null) { defaultLoader = new XMLLoader(); } loader = defaultLoader; } return loader; }
protected void _addFactoryMixIns(Class<?> mixin) { MemberKey[] methodKeys = null; int methodCount = _creatorMethods.size(); for (Method m : mixin.getDeclaredMethods()) { if (!Modifier.isStatic(m.getModifiers())) { continue; } if (m.getParameterTypes().length == 0) { continue; } if (methodKeys == null) { methodKeys = new MemberKey[methodCount]; for (int i = 0; i < methodCount; ++i) { methodKeys[i] = new MemberKey(_creatorMethods.get(i).getAnnotated()); } } MemberKey key = new MemberKey(m); for (int i = 0; i < methodCount; ++i) { if (!key.equals(methodKeys[i])) { continue; } _addMixOvers(m, _creatorMethods.get(i), true); break; } } }
/** * Registers method if it: a. is public, and b. is named "convertXxx", and c. has a return type of * "RexNode" or a subtype d. has a 2 parameters with types ConvertletContext and SqlNode (or a * subtype) respectively. */ private void registerNodeTypeMethod(final Method method) { if (!Modifier.isPublic(method.getModifiers())) { return; } if (!method.getName().startsWith("convert")) { return; } if (!RexNode.class.isAssignableFrom(method.getReturnType())) { return; } final Class[] parameterTypes = method.getParameterTypes(); if (parameterTypes.length != 2) { return; } if (parameterTypes[0] != SqlRexContext.class) { return; } final Class parameterType = parameterTypes[1]; if (!SqlNode.class.isAssignableFrom(parameterType)) { return; } map.put( parameterType, new SqlRexConvertlet() { public RexNode convertCall(SqlRexContext cx, SqlCall call) { try { return (RexNode) method.invoke(ReflectiveConvertletTable.this, cx, call); } catch (IllegalAccessException e) { throw Util.newInternal(e, "while converting " + call); } catch (InvocationTargetException e) { throw Util.newInternal(e, "while converting " + call); } } }); }
{ for (Method m : this.getClass().getDeclaredMethods()) { if (m.getName().matches("m[0-9]+(_check)?")) { assert (Modifier.isStatic(m.getModifiers())) : m; tests.put(m.getName(), m); } } }
/** * Checks that a callback method is present and correctly defined. * * <p>Having checked it, you can call it using callback(). * * @param sCallback Name of callback method * @throws OmDeveloperException If the method doesn't exist or is defined incorrectly */ public void checkCallback(String sCallback) throws OmDeveloperException { try { Method m = getClass().getMethod(sCallback, new Class[0]); if (m.getReturnType() != void.class) throw new OmDeveloperException("Callback method " + sCallback + "() must return void"); if (!Modifier.isPublic(m.getModifiers())) throw new OmDeveloperException("Callback method " + sCallback + "() must be public"); if (Modifier.isStatic(m.getModifiers())) throw new OmDeveloperException("Callback method " + sCallback + "() may not be static"); if (Modifier.isAbstract(m.getModifiers())) throw new OmDeveloperException("Callback method " + sCallback + "() may not be abstract"); sCheckedCallbacks.add(sCallback); } catch (NoSuchMethodException e) { throw new OmDeveloperException("Callback method " + sCallback + "() does not exist"); } }
private static Method checkForCreatorMethod(Method m) { if (m.getAnnotation(TestObjectCreate.class) == null) return null; if (!m.getReturnType().equals(testClass)) throw new RuntimeException( "@TestObjectCreate " + "must return instance of Class to be tested"); if ((m.getModifiers() & java.lang.reflect.Modifier.STATIC) < 1) throw new RuntimeException("@TestObjectCreate " + "must be static."); m.setAccessible(true); return m; }
/** * attempt to invoke a Method with the given Object arguments, performing static method * auto-detection and automatic array compression */ public static Object invokeMethod(Method m, Object[] o) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException { Object obj; Object[] args; Class[] c = m.getParameterTypes(); int num = (o == null) ? 0 : o.length; int len = -1; int a = -1; if (c != null) { len = c.length; for (int i = 0; i < len; i++) { if (c[i].isArray()) a = i; } } if (Modifier.isStatic(m.getModifiers())) { // static method obj = null; if (num > 0) { if (a < 0) { args = new Object[num]; System.arraycopy(o, 0, args, 0, num); } else { // compress some of the arguments into array form args = new Object[len]; if (a > 0) System.arraycopy(o, 0, args, 0, a); Object array = Array.newInstance(c[a].getComponentType(), num - len + 1); System.arraycopy(o, a, array, 0, num - len + 1); args[a] = array; if (a < len - 1) System.arraycopy(o, num - len + a + 1, args, a + 1, len - a - 1); } } else args = null; } else { // object method if (num > 0) obj = o[0]; else { // invalid object method return null; } if (num > 1) { if (a < 0) { args = new Object[num - 1]; System.arraycopy(o, 1, args, 0, num - 1); } else { // compress some of the arguments into array form args = new Object[len]; if (a > 0) System.arraycopy(o, 1, args, 0, a); Object array = Array.newInstance(c[a].getComponentType(), num - len); System.arraycopy(o, a + 1, array, 0, num - len); args[a + 1] = array; if (a < len - 1) System.arraycopy(o, num - len + a + 1, args, a + 1, len - a - 1); } } else args = null; } return m.invoke(obj, args); }
private Method findPublicVoidMethod(Class<?> aClass, String methodName) { for (Method method : aClass.getDeclaredMethods()) { if (isPublic(method.getModifiers()) && method.getReturnType() == void.class && methodName.equals(method.getName())) { return method; } } return null; }
/** * Check that all methods declared in the given interface were called. Does *not* include * methods from super interfaces. * * @return this for fluent api */ public MethodCallTester<MonitoredClass> assertAllInterfaceMethodsCalled() { List<MethodInvocation> currentInvocation = new ArrayList<>(invocations); // Debugger calling toString can mess with this for (Method method : mockClass.getDeclaredMethods()) { if (Modifier.isStatic(method.getModifiers()) || !Modifier.isPublic(method.getModifiers())) continue; boolean called = false; for (MethodInvocation invocation : currentInvocation) { if (invocation.method.equals(method.getName())) { called = true; break; } } assertTrue( "Method " + mockClass.getSimpleName() + "." + method.getName() + " was not called", called); } return this; }
private static Method checkForCleanupMethod(Method m) { if (m.getAnnotation(TestObjectCleanup.class) == null) return null; if (!m.getReturnType().equals(void.class)) throw new RuntimeException("@TestObjectCleanup " + "must return void"); if ((m.getModifiers() & java.lang.reflect.Modifier.STATIC) < 1) throw new RuntimeException("@TestObjectCleanup " + "must be static."); if (m.getParameterTypes().length == 0 || m.getParameterTypes()[0] != testClass) throw new RuntimeException( "@TestObjectCleanup " + "must take an argument of the tested type."); m.setAccessible(true); return m; }
public static boolean hasGetterSignature(Method m) { // First: static methods can't be getters if (Modifier.isStatic(m.getModifiers())) { return false; } // Must take no args Class<?>[] pts = m.getParameterTypes(); if (pts != null && pts.length != 0) { return false; } // Can't be a void method if (Void.TYPE == m.getReturnType()) { return false; } // Otherwise looks ok: return true; }
private ArrayList<Object> gatherParamsFromAllMethodsFrom(Class<?> sourceClass) { ArrayList<Object> result = new ArrayList<Object>(); Method[] methods = sourceClass.getDeclaredMethods(); for (Method method : methods) { if (method.getName().startsWith("provide")) { if (!Modifier.isStatic(method.getModifiers())) throw new RuntimeException( "Parameters source method " + method.getName() + " is not declared as static. Modify it to a static method."); try { result.addAll(Arrays.asList(processParamsIfSingle((Object[]) method.invoke(null)))); } catch (Exception e) { throw new RuntimeException( "Cannot invoke parameters source method: " + method.getName(), e); } } } return result; }
/** * Prints all methods of a class * * @param cl a class */ public static void printMethods(Class cl) { Method[] methods = cl.getDeclaredMethods(); for (Method m : methods) { Class retType = m.getReturnType(); String name = m.getName(); System.out.print(" "); // print modifiers, return type and method name String modifiers = Modifier.toString(m.getModifiers()); if (modifiers.length() > 0) System.out.print(modifiers + " "); System.out.print(retType.getName() + " " + name + "("); // print parameter types Class[] paramTypes = m.getParameterTypes(); for (int j = 0; j < paramTypes.length; j++) { if (j > 0) System.out.print(", "); System.out.print(paramTypes[j].getName()); } System.out.println(");"); } }
public Factory make(Class<?> cl) throws InstantiationException, IllegalAccessException { if (Factory.class.isAssignableFrom(cl)) return (cl.asSubclass(Factory.class).newInstance()); try { final Method mkm = cl.getDeclaredMethod("mkwidget", Widget.class, Object[].class); int mod = mkm.getModifiers(); if (Widget.class.isAssignableFrom(mkm.getReturnType()) && ((mod & Modifier.STATIC) != 0) && ((mod & Modifier.PUBLIC) != 0)) { return (new Factory() { public Widget create(Widget parent, Object[] args) { try { return ((Widget) mkm.invoke(null, parent, args)); } catch (Exception e) { if (e instanceof RuntimeException) throw ((RuntimeException) e); throw (new RuntimeException(e)); } } }); } } catch (NoSuchMethodException e) { } return (null); }
public static byte[] createAdapterCode( ObjToIntMap functionNames, String adapterName, Class<?> superClass, Class<?>[] interfaces, String scriptClassName) { ClassFileWriter cfw = new ClassFileWriter(adapterName, superClass.getName(), "<adapter>"); cfw.addField( "factory", "Laurora/javascript/ContextFactory;", (short) (ClassFileWriter.ACC_PUBLIC | ClassFileWriter.ACC_FINAL)); cfw.addField( "delegee", "Laurora/javascript/Scriptable;", (short) (ClassFileWriter.ACC_PUBLIC | ClassFileWriter.ACC_FINAL)); cfw.addField( "self", "Laurora/javascript/Scriptable;", (short) (ClassFileWriter.ACC_PUBLIC | ClassFileWriter.ACC_FINAL)); int interfacesCount = interfaces == null ? 0 : interfaces.length; for (int i = 0; i < interfacesCount; i++) { if (interfaces[i] != null) cfw.addInterface(interfaces[i].getName()); } String superName = superClass.getName().replace('.', '/'); Constructor<?>[] ctors = superClass.getConstructors(); for (Constructor<?> ctor : ctors) { generateCtor(cfw, adapterName, superName, ctor); } generateSerialCtor(cfw, adapterName, superName); if (scriptClassName != null) { generateEmptyCtor(cfw, adapterName, superName, scriptClassName); } ObjToIntMap generatedOverrides = new ObjToIntMap(); ObjToIntMap generatedMethods = new ObjToIntMap(); // generate methods to satisfy all specified interfaces. for (int i = 0; i < interfacesCount; i++) { Method[] methods = interfaces[i].getMethods(); for (int j = 0; j < methods.length; j++) { Method method = methods[j]; int mods = method.getModifiers(); if (Modifier.isStatic(mods) || Modifier.isFinal(mods)) { continue; } String methodName = method.getName(); Class<?>[] argTypes = method.getParameterTypes(); if (!functionNames.has(methodName)) { try { superClass.getMethod(methodName, argTypes); // The class we're extending implements this method and // the JavaScript object doesn't have an override. See // bug 61226. continue; } catch (NoSuchMethodException e) { // Not implemented by superclass; fall through } } // make sure to generate only one instance of a particular // method/signature. String methodSignature = getMethodSignature(method, argTypes); String methodKey = methodName + methodSignature; if (!generatedOverrides.has(methodKey)) { generateMethod(cfw, adapterName, methodName, argTypes, method.getReturnType(), true); generatedOverrides.put(methodKey, 0); generatedMethods.put(methodName, 0); } } } // Now, go through the superclass's methods, checking for abstract // methods or additional methods to override. // generate any additional overrides that the object might contain. Method[] methods = getOverridableMethods(superClass); for (int j = 0; j < methods.length; j++) { Method method = methods[j]; int mods = method.getModifiers(); // if a method is marked abstract, must implement it or the // resulting class won't be instantiable. otherwise, if the object // has a property of the same name, then an override is intended. boolean isAbstractMethod = Modifier.isAbstract(mods); String methodName = method.getName(); if (isAbstractMethod || functionNames.has(methodName)) { // make sure to generate only one instance of a particular // method/signature. Class<?>[] argTypes = method.getParameterTypes(); String methodSignature = getMethodSignature(method, argTypes); String methodKey = methodName + methodSignature; if (!generatedOverrides.has(methodKey)) { generateMethod(cfw, adapterName, methodName, argTypes, method.getReturnType(), true); generatedOverrides.put(methodKey, 0); generatedMethods.put(methodName, 0); // if a method was overridden, generate a "super$method" // which lets the delegate call the superclass' version. if (!isAbstractMethod) { generateSuper( cfw, adapterName, superName, methodName, methodSignature, argTypes, method.getReturnType()); } } } } // Generate Java methods for remaining properties that are not // overrides. ObjToIntMap.Iterator iter = new ObjToIntMap.Iterator(functionNames); for (iter.start(); !iter.done(); iter.next()) { String functionName = (String) iter.getKey(); if (generatedMethods.has(functionName)) continue; int length = iter.getValue(); Class<?>[] parms = new Class[length]; for (int k = 0; k < length; k++) parms[k] = ScriptRuntime.ObjectClass; generateMethod(cfw, adapterName, functionName, parms, ScriptRuntime.ObjectClass, false); } return cfw.toByteArray(); }
private void reflect(Scriptable scope, boolean includeProtected) { // We reflect methods first, because we want overloaded field/method // names to be allocated to the NativeJavaMethod before the field // gets in the way. Method[] methods = discoverAccessibleMethods(cl, includeProtected, includePrivate); for (int i = 0; i < methods.length; i++) { Method method = methods[i]; int mods = method.getModifiers(); boolean isStatic = Modifier.isStatic(mods); Map<String, Object> ht = isStatic ? staticMembers : members; String name = method.getName(); Object value = ht.get(name); if (value == null) { ht.put(name, method); } else { ObjArray overloadedMethods; if (value instanceof ObjArray) { overloadedMethods = (ObjArray) value; } else { if (!(value instanceof Method)) Kit.codeBug(); // value should be instance of Method as at this stage // staticMembers and members can only contain methods overloadedMethods = new ObjArray(); overloadedMethods.add(value); ht.put(name, overloadedMethods); } overloadedMethods.add(method); } } // replace Method instances by wrapped NativeJavaMethod objects // first in staticMembers and then in members for (int tableCursor = 0; tableCursor != 2; ++tableCursor) { boolean isStatic = (tableCursor == 0); Map<String, Object> ht = isStatic ? staticMembers : members; for (String name : ht.keySet()) { MemberBox[] methodBoxes; Object value = ht.get(name); if (value instanceof Method) { methodBoxes = new MemberBox[1]; methodBoxes[0] = new MemberBox((Method) value); } else { ObjArray overloadedMethods = (ObjArray) value; int N = overloadedMethods.size(); if (N < 2) Kit.codeBug(); methodBoxes = new MemberBox[N]; for (int i = 0; i != N; ++i) { Method method = (Method) overloadedMethods.get(i); methodBoxes[i] = new MemberBox(method); } } NativeJavaMethod fun = new NativeJavaMethod(methodBoxes); if (scope != null) { ScriptRuntime.setFunctionProtoAndParent(fun, scope); } ht.put(name, fun); } } // Reflect fields. Field[] fields = getAccessibleFields(); for (int i = 0; i < fields.length; i++) { Field field = fields[i]; String name = field.getName(); int mods = field.getModifiers(); if (!includePrivate && !Modifier.isPublic(mods)) { continue; } try { boolean isStatic = Modifier.isStatic(mods); Map<String, Object> ht = isStatic ? staticMembers : members; Object member = ht.get(name); if (member == null) { ht.put(name, field); } else if (member instanceof NativeJavaMethod) { NativeJavaMethod method = (NativeJavaMethod) member; FieldAndMethods fam = new FieldAndMethods(scope, method.methods, field); Map<String, FieldAndMethods> fmht = isStatic ? staticFieldAndMethods : fieldAndMethods; if (fmht == null) { fmht = new HashMap<String, FieldAndMethods>(); if (isStatic) { staticFieldAndMethods = fmht; } else { fieldAndMethods = fmht; } } fmht.put(name, fam); ht.put(name, fam); } else if (member instanceof Field) { Field oldField = (Field) member; // If this newly reflected field shadows an inherited field, // then replace it. Otherwise, since access to the field // would be ambiguous from Java, no field should be // reflected. // For now, the first field found wins, unless another field // explicitly shadows it. if (oldField.getDeclaringClass().isAssignableFrom(field.getDeclaringClass())) { ht.put(name, field); } } else { // "unknown member type" Kit.codeBug(); } } catch (SecurityException e) { // skip this field Context.reportWarning( "Could not access field " + name + " of class " + cl.getName() + " due to lack of privileges."); } } // Create bean properties from corresponding get/set methods first for // static members and then for instance members for (int tableCursor = 0; tableCursor != 2; ++tableCursor) { boolean isStatic = (tableCursor == 0); Map<String, Object> ht = isStatic ? staticMembers : members; Map<String, BeanProperty> toAdd = new HashMap<String, BeanProperty>(); // Now, For each member, make "bean" properties. for (String name : ht.keySet()) { // Is this a getter? boolean memberIsGetMethod = name.startsWith("get"); boolean memberIsSetMethod = name.startsWith("set"); boolean memberIsIsMethod = name.startsWith("is"); if (memberIsGetMethod || memberIsIsMethod || memberIsSetMethod) { // Double check name component. String nameComponent = name.substring(memberIsIsMethod ? 2 : 3); if (nameComponent.length() == 0) continue; // Make the bean property name. String beanPropertyName = nameComponent; char ch0 = nameComponent.charAt(0); if (Character.isUpperCase(ch0)) { if (nameComponent.length() == 1) { beanPropertyName = nameComponent.toLowerCase(); } else { char ch1 = nameComponent.charAt(1); if (!Character.isUpperCase(ch1)) { beanPropertyName = Character.toLowerCase(ch0) + nameComponent.substring(1); } } } // If we already have a member by this name, don't do this // property. if (ht.containsKey(beanPropertyName) || toAdd.containsKey(beanPropertyName)) { continue; } // Find the getter method, or if there is none, the is- // method. MemberBox getter = null; getter = findGetter(isStatic, ht, "get", nameComponent); // If there was no valid getter, check for an is- method. if (getter == null) { getter = findGetter(isStatic, ht, "is", nameComponent); } // setter MemberBox setter = null; NativeJavaMethod setters = null; String setterName = "set".concat(nameComponent); if (ht.containsKey(setterName)) { // Is this value a method? Object member = ht.get(setterName); if (member instanceof NativeJavaMethod) { NativeJavaMethod njmSet = (NativeJavaMethod) member; if (getter != null) { // We have a getter. Now, do we have a matching // setter? Class<?> type = getter.method().getReturnType(); setter = extractSetMethod(type, njmSet.methods, isStatic); } else { // No getter, find any set method setter = extractSetMethod(njmSet.methods, isStatic); } if (njmSet.methods.length > 1) { setters = njmSet; } } } // Make the property. BeanProperty bp = new BeanProperty(getter, setter, setters); toAdd.put(beanPropertyName, bp); } } // Add the new bean properties. for (String key : toAdd.keySet()) { Object value = toAdd.get(key); ht.put(key, value); } } // Reflect constructors Constructor<?>[] constructors = getAccessibleConstructors(); ctors = new MemberBox[constructors.length]; for (int i = 0; i != constructors.length; ++i) { ctors[i] = new MemberBox(constructors[i]); } }
private static void discoverAccessibleMethods( Class<?> clazz, Map<MethodSignature, Method> map, boolean includeProtected, boolean includePrivate) { if (Modifier.isPublic(clazz.getModifiers()) || includePrivate) { try { if (includeProtected || includePrivate) { while (clazz != null) { try { Method[] methods = clazz.getDeclaredMethods(); for (int i = 0; i < methods.length; i++) { Method method = methods[i]; int mods = method.getModifiers(); if (Modifier.isPublic(mods) || Modifier.isProtected(mods) || includePrivate) { if (includePrivate) method.setAccessible(true); map.put(new MethodSignature(method), method); } } clazz = clazz.getSuperclass(); } catch (SecurityException e) { // Some security settings (i.e., applets) disallow // access to Class.getDeclaredMethods. Fall back to // Class.getMethods. Method[] methods = clazz.getMethods(); for (int i = 0; i < methods.length; i++) { Method method = methods[i]; MethodSignature sig = new MethodSignature(method); if (map.get(sig) == null) map.put(sig, method); } break; // getMethods gets superclass methods, no // need to loop any more } } } else { Method[] methods = clazz.getMethods(); for (int i = 0; i < methods.length; i++) { Method method = methods[i]; MethodSignature sig = new MethodSignature(method); map.put(sig, method); } } return; } catch (SecurityException e) { Context.reportWarning( "Could not discover accessible methods of class " + clazz.getName() + " due to lack of privileges, " + "attemping superclasses/interfaces."); // Fall through and attempt to discover superclass/interface // methods } } Class<?>[] interfaces = clazz.getInterfaces(); for (int i = 0; i < interfaces.length; i++) { discoverAccessibleMethods(interfaces[i], map, includeProtected, includePrivate); } Class<?> superclass = clazz.getSuperclass(); if (superclass != null) { discoverAccessibleMethods(superclass, map, includeProtected, includePrivate); } }
/** Calculates a MD5 digest of the class. */ public String getDigest() { try { if (_className == null || "".equals(_className)) return ""; DynamicClassLoader loader = (DynamicClassLoader) Thread.currentThread().getContextClassLoader(); ClassLoader tmpLoader = loader.getNewTempClassLoader(); Class cl = Class.forName(_className, false, tmpLoader); if (cl == null) return ""; MessageDigest digest = MessageDigest.getInstance("MD5"); addDigest(digest, cl.getName()); addDigest(digest, cl.getModifiers()); Class superClass = cl.getSuperclass(); if (superClass != null) addDigest(digest, superClass.getName()); Class[] interfaces = cl.getInterfaces(); for (int i = 0; i < interfaces.length; i++) addDigest(digest, interfaces[i].getName()); Field[] fields = cl.getDeclaredFields(); Arrays.sort(fields, new FieldComparator()); if (_checkFields) { for (Field field : fields) { if (Modifier.isPrivate(field.getModifiers()) && !_checkPrivate) continue; if (Modifier.isProtected(field.getModifiers()) && !_checkProtected) continue; addDigest(digest, field.getName()); addDigest(digest, field.getModifiers()); addDigest(digest, field.getType().getName()); addDigest(digest, field.getAnnotations()); } } Method[] methods = cl.getDeclaredMethods(); Arrays.sort(methods, new MethodComparator()); for (int i = 0; i < methods.length; i++) { Method method = methods[i]; if (Modifier.isPrivate(method.getModifiers()) && !_checkPrivate) continue; if (Modifier.isProtected(method.getModifiers()) && !_checkProtected) continue; if (Modifier.isStatic(method.getModifiers()) && !_checkStatic) continue; addDigest(digest, method.getName()); addDigest(digest, method.getModifiers()); addDigest(digest, method.getName()); Class[] param = method.getParameterTypes(); for (int j = 0; j < param.length; j++) addDigest(digest, param[j].getName()); addDigest(digest, method.getReturnType().getName()); Class[] exn = method.getExceptionTypes(); for (int j = 0; j < exn.length; j++) addDigest(digest, exn[j].getName()); addDigest(digest, method.getAnnotations()); } byte[] digestBytes = new byte[256]; int len = digest.digest(digestBytes, 0, digestBytes.length); return digestToBase64(digestBytes, len); } catch (Exception e) { log.log(Level.FINER, e.toString(), e); return ""; } }
public String getPublicPropertiesForClasses(String classNames[]) { StringBuilder result = new StringBuilder(); String className = null; ArrayList publicFields = new ArrayList(); result.append("<classDefinitions>"); if (classNames != null && classNames.length > 0) { for (int i = 0; i < classNames.length; i++) { className = classNames[i]; if (className != null) { result.append("<classDefinition>"); try { Class c = Class.forName(className); Field fields[] = c.getFields(); Field field = null; if (fields != null) { for (int k = 0; k < fields.length; k++) { field = fields[k]; if (field != null) publicFields.add( (new StringBuilder(String.valueOf(field.getName()))) .append(",") .append(field.getType().getName()) .toString()); } } try { BeanInfo b = Introspector.getBeanInfo(c); result.append( (new StringBuilder("<classSimpleName>")) .append(c.getSimpleName()) .append("</classSimpleName>") .toString()); result.append( (new StringBuilder("<classFullName>")) .append(c.getName()) .append("</classFullName>") .toString()); Package pack = c.getPackage(); String packStr = ""; if (pack != null) packStr = pack.getName(); result.append( (new StringBuilder("<packageName>")) .append(packStr) .append("</packageName>") .toString()); PropertyDescriptor pds[] = b.getPropertyDescriptors(); if (pds != null) { for (int propCount = 0; propCount < pds.length; propCount++) { PropertyDescriptor pd = pds[propCount]; String propertyName = pd.getName(); Method readMethod = pd.getReadMethod(); Method writeMethod = pd.getWriteMethod(); if (readMethod != null && isPublicAccessor(readMethod.getModifiers()) && writeMethod != null && isPublicAccessor(writeMethod.getModifiers())) publicFields.add( (new StringBuilder(String.valueOf(propertyName))) .append(",") .append(pd.getPropertyType().getName()) .toString()); } } } catch (Exception e) { e.printStackTrace(); } if (publicFields != null && publicFields.size() > 0) { String temp = null; result.append("<publicFields>"); for (int counter = 0; counter < publicFields.size(); counter++) { temp = (String) publicFields.get(counter); if (temp != null) { String pubTemp[] = temp.split(","); if (pubTemp.length == 2) { result.append("<publicField>"); result.append( (new StringBuilder("<publicFieldName>")) .append(pubTemp[0]) .append("</publicFieldName>") .toString()); result.append( (new StringBuilder("<publicFieldType>")) .append(pubTemp[1]) .append("</publicFieldType>") .toString()); result.append("</publicField>"); } } } result.append("</publicFields>"); } } catch (ClassNotFoundException e) { result.append( (new StringBuilder("<classFullName>")) .append(className) .append("</classFullName>") .toString()); result.append( (new StringBuilder("<error>Problem retrieving ")) .append(className) .append(" information</error>") .toString()); System.out.println(e.getMessage()); } result.append("</classDefinition>"); } } } result.append("</classDefinitions>"); return result.toString(); }
/** * {@inheritDoc} * * @see java.lang.reflect.InvocationHandler#invoke(java.lang.Object, java.lang.reflect.Method, * java.lang.Object[]) */ @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (MBeanServerConnection.class != method.getDeclaringClass()) { return method.invoke(Modifier.isStatic(method.getModifiers()) ? null : this, args); } if (channel.getPipeline().get(getClass().getSimpleName()) == null) { throw new IOException("This MBeanServerConnection has been closed", new Throwable()); } // SimpleLogger.debug("MBeanServerConnection [", method.getName(), "] Payload Size [", // sargs.length+6+4, "]"); final int reqId = requestId.incrementAndGet(); if ("addNotificationListener".equals(method.getName()) && !method.getParameterTypes()[1].equals(ObjectName.class)) { NotificationListener listener = (NotificationListener) args[1]; args[1] = reqId; addRegisteredListener(reqId, listener); } else if ("removeNotificationListener".equals(method.getName()) && !method.getParameterTypes()[1].equals(ObjectName.class)) { removeRegisteredListener((NotificationListener) args[1]); args = new Object[0]; } byte[] sargs = getOutput(args); ChannelBuffer cb = ChannelBuffers.directBuffer(1 + domainInfoData.length + 4 + 1 + 4 + sargs.length); cb.writeByte(OpCode.JMX_REQUEST.op()); // 1 cb.writeBytes(domainInfoData); // domain data cb.writeInt(reqId); // 4 cb.writeByte(methodToKey.get(method)); // 1 cb.writeInt(sargs.length); // 4 cb.writeBytes(sargs); // sargs.length if (listener == null) { synchTimeoutMap.addListener( new TimeoutListener<Integer, CountDownLatch>() { @Override public void onTimeout(Integer key, CountDownLatch value) { if (reqId == key) { synchTimeoutMap.remove(key); synchTimeoutMap.removeListener(this); onSynchronousResponse( reqId, new IOException( "Operation timed out after [" + timeout + "] ms.", new Throwable())); } } }); } else { asynchTimeoutMap.put(reqId, listener, timeout); asynchTimeoutMap.addListener( new TimeoutListener<Integer, AsynchJMXResponseListener>() { @Override public void onTimeout(Integer key, AsynchJMXResponseListener value) { if (reqId == key) { asynchTimeoutMap.remove(key); listener.onTimeout(reqId, timeout); asynchTimeoutMap.removeListener(this); } } }); } channel .write(cb, remoteAddress) .addListener( new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { SimpleLogger.debug("Sent JMX Request to [", remoteAddress, "]"); } else { SimpleLogger.error( "Failed to send JMX Request to [", remoteAddress, "]", future.getCause()); } } }); if (listener == null) { waitForSynchronousResponse(reqId, timeout); Object result = synchResultMap.get(reqId); if (result != null && result instanceof Throwable) { throw (Throwable) result; } return result; } return null; }
/** * Initialization method that will find out all constructors and potential static factory methods * the class has. * * <p>Starting with 1.2, it will also apply mix-in annotations, as per [JACKSON-76] * * @param includeAll If true, includes all creator methods; if false, will only include the * no-arguments "default" constructor */ public void resolveCreators(boolean includeAll) { // Then see which constructors we have _constructors = null; for (Constructor<?> ctor : _class.getDeclaredConstructors()) { switch (ctor.getParameterTypes().length) { case 0: _defaultConstructor = _constructConstructor(ctor, true); break; default: if (includeAll) { if (_constructors == null) { _constructors = new ArrayList<AnnotatedConstructor>(); } _constructors.add(_constructConstructor(ctor, false)); } } } // and if need be, augment with mix-ins if (_primaryMixIn != null) { if (_defaultConstructor != null || _constructors != null) { _addConstructorMixIns(_primaryMixIn); } } /* And then... let's remove all constructors that are * deemed to be ignorable after all annotations have been * properly collapsed. */ if (_defaultConstructor != null) { if (_annotationIntrospector.isIgnorableConstructor(_defaultConstructor)) { _defaultConstructor = null; } } if (_constructors != null) { // count down to allow safe removal for (int i = _constructors.size(); --i >= 0; ) { if (_annotationIntrospector.isIgnorableConstructor(_constructors.get(i))) { _constructors.remove(i); } } } _creatorMethods = null; if (includeAll) { /* Then static methods which are potential factory * methods */ for (Method m : _class.getDeclaredMethods()) { if (!Modifier.isStatic(m.getModifiers())) { continue; } int argCount = m.getParameterTypes().length; // factory methods take at least one arg: if (argCount < 1) { continue; } if (_creatorMethods == null) { _creatorMethods = new ArrayList<AnnotatedMethod>(); } _creatorMethods.add(_constructCreatorMethod(m)); } // mix-ins to mix in? if (_primaryMixIn != null && _creatorMethods != null) { _addFactoryMixIns(_primaryMixIn); } // anything to ignore at this point? if (_creatorMethods != null) { // count down to allow safe removal for (int i = _creatorMethods.size(); --i >= 0; ) { if (_annotationIntrospector.isIgnorableMethod(_creatorMethods.get(i))) { _creatorMethods.remove(i); } } } } }