/** * Goes through the class hierarchy and find the authorization annotations attached to a certain * method. * * @param clazz class to be scanned * @param authorizationActionMap the map to be populated */ private void findAuthorizationActions( Class<?> clazz, Map<String, String> authorizationActionMap) { if (clazz == null || clazz == Object.class) { return; } String classAuthorizationActionsAllowed = getAuthorizationActions(clazz.getAnnotations(), AUTHORIZATION_ANNOTATION_CLASS_NAME); for (Method m : clazz.getMethods()) { if (SKIP_METHODS.contains(m.getName())) { continue; } String methodAuthorizationActionsAllowed = getAuthorizationActions(m.getAnnotations(), AUTHORIZATION_ANNOTATION_CLASS_NAME); String authorizationActions = methodAuthorizationActionsAllowed != null ? methodAuthorizationActionsAllowed : classAuthorizationActionsAllowed; if (authorizationActions != null) { authorizationActionMap.put(m.getName(), authorizationActions); } } if (!authorizationActionMap.isEmpty()) { return; } findAuthorizationActions(clazz.getSuperclass(), authorizationActionMap); if (!authorizationActionMap.isEmpty()) { return; } for (Class<?> interfaceCls : clazz.getInterfaces()) { findAuthorizationActions(interfaceCls, authorizationActionMap); } }
private MetaClass skipTokens(LinkedList<String> tokens, MetaClass metaClass) { while (tokens.size() > 1) { Class theClass = metaClass.getTheClass(); String token = tokens.pollFirst(); Class selectedClass = null; if (propertyPattern.matcher(token).matches()) { String getterName = "get" + StringGroovyMethods.capitalize((CharSequence) token); for (MetaMethod metaMethod : metaClass.getMetaMethods()) { if (metaMethod.getName().equals(getterName)) { selectedClass = metaMethod.getReturnType(); break; } } if (selectedClass == null) for (Method method : theClass.getMethods()) { if (method.getParameterTypes().length != 0) continue; if (method.getName().equals(getterName)) { selectedClass = method.getReturnType(); break; } } if (selectedClass == null) { MetaProperty metaProperty = metaClass.getMetaProperty(token); if (metaProperty == null) return null; selectedClass = metaProperty.getType(); } } else if (methodPattern.matcher(token).matches()) { String curMethodName = token.substring(0, token.indexOf('(')); for (MetaMethod metaMethod : metaClass.getMetaMethods()) { String name = metaMethod.getName(); if (name.equals(curMethodName)) { selectedClass = metaMethod.getReturnType(); break; } } if (selectedClass == null) for (Method method : theClass.getMethods()) { String name = method.getName(); if (name.equals(curMethodName)) { selectedClass = method.getReturnType(); break; } } } if (selectedClass == null) return null; metaClass = InvokerHelper.getMetaClass(selectedClass); } return metaClass; }
public synchronized void registerListener(EventListener listener) { Class<? extends EventListener> listenerClass = listener.getClass(); for (Method method : listenerClass.getMethods()) { if (!method.isAnnotationPresent(EventHandler.class)) continue; if (method.getParameterTypes().length != 1) throw new IllegalArgumentException( "Method " + method.toString() + " in class " + method.getDeclaringClass().getName() + " has incorrect amount of parameters"); Class<? extends Event> eventClass = method.getParameterTypes()[0].asSubclass(Event.class); boolean senderExists = false; for (EventSender sender : eventSenders) { if (eventClass.isAssignableFrom(sender.getListenerEventClass())) sender.addHandler(listener, method); if (eventClass == sender.getListenerEventClass()) senderExists = true; } if (!senderExists) { EventSender sender = new EventSender(eventClass); eventSenders.add(sender); sender.addHandler(listener, method); } } }
public Method[] getAllMethodsFromClass(Class c) { Method[] mList; mList = c.getMethods(); return mList; }
/** * Goes through the class hierarchy and figure out the supertenant annotations coupled with * operations/methods. * * @param clazz * @param superTenantServiceSet */ private void findSuperTenantServices(Class<?> clazz, Set<String> superTenantServiceSet) { if (clazz == null || clazz == Object.class) { return; } for (Method m : clazz.getMethods()) { if (SKIP_METHODS.contains(m.getName())) { continue; } boolean isSuperTenantService = getSuperTenantServices(m.getAnnotations(), TENANT_ANNOTATION_CLASS_NAME); if (isSuperTenantService) { superTenantServiceSet.add(m.getName()); } } if (!superTenantServiceSet.isEmpty()) { return; } findSuperTenantServices(clazz.getSuperclass(), superTenantServiceSet); if (!superTenantServiceSet.isEmpty()) { return; } for (Class<?> interfaceCls : clazz.getInterfaces()) { findSuperTenantServices(interfaceCls, superTenantServiceSet); } }
/** * @return a reference to the public static serializableInstance() method of clazz, if there is * one; otherwise, returns null. */ private Method serializableInstanceMethod(Class clazz) { Method[] methods = clazz.getMethods(); for (Method method : methods) { if ("serializableInstance".equals(method.getName())) { Class[] parameterTypes = method.getParameterTypes(); if (!(parameterTypes.length == 0)) { continue; } if (!(Modifier.isStatic(method.getModifiers()))) { continue; } if (Modifier.isAbstract(method.getModifiers())) { continue; } return method; } } return null; }
public static Method[] findMethodsByName(Class<?> type, String methodName) { ArrayBuilder<Method> builder = new ArrayBuilder<Method>(Method.class); for (Method method : type.getMethods()) { if (methodName.equals(method.getName())) builder.add(method); } return builder.toArray(); }
@SuppressWarnings("unchecked") private void putEntityListeners(AnnotationInfo ai, EntityListeners entityListeners) { Class[] entityListenerClasses = entityListeners.value(); if (entityListenerClasses == null) return; Map<Class, List<ClassMethodEntry>> listeners = ai.getEntityListeners(); List<Class<? extends Annotation>> annotations = Arrays.asList( PrePersist.class, PreUpdate.class, PreRemove.class, PostLoad.class, PostPersist.class, PostUpdate.class, PostRemove.class); // TODO: More than one listener per event cannot be handled like this... for (Class clazz : entityListenerClasses) { // System.out.println("class=" + clazz); for (Method method : clazz.getMethods()) { // System.out.println("method=" + method.getName()); for (Class<? extends Annotation> annotationClass : annotations) { Annotation annotation = method.getAnnotation(annotationClass); addListener(listeners, clazz, method, annotation, annotationClass); } } } }
private Map<String, SpringResource> generateResourceMap(Set<Class<?>> validClasses) throws GenerateException { Map<String, SpringResource> resourceMap = new HashMap<String, SpringResource>(); for (Class<?> c : validClasses) { RequestMapping requestMapping = c.getAnnotation(RequestMapping.class); String description = ""; // This try/catch block is to stop a bamboo build from failing due to NoClassDefFoundError // This occurs when a class or method loaded by reflections contains a type that has no // dependency try { resourceMap = analyzeController(c, resourceMap, description); List<Method> mList = new ArrayList<Method>(Arrays.asList(c.getMethods())); if (c.getSuperclass() != null) { mList.addAll(Arrays.asList(c.getSuperclass().getMethods())); } } catch (NoClassDefFoundError e) { LOG.error(e.getMessage()); LOG.info(c.getName()); // exception occurs when a method type or annotation is not recognized by the plugin } catch (ClassNotFoundException e) { LOG.error(e.getMessage()); LOG.info(c.getName()); } } return resourceMap; }
/** * There are some nasty bugs for introspection with generics. This method addresses those nasty * bugs and tries to find proper methods if available * http://bugs.sun.com/view_bug.do?bug_id=6788525 http://bugs.sun.com/view_bug.do?bug_id=6528714 * * @param descriptor * @return */ private static PropertyDescriptor fixGenericDescriptor( Class<?> clazz, PropertyDescriptor descriptor) { Method readMethod = descriptor.getReadMethod(); Method writeMethod = descriptor.getWriteMethod(); if (readMethod != null && (readMethod.isBridge() || readMethod.isSynthetic())) { String propertyName = descriptor.getName(); // capitalize the first letter of the string; String baseName = Character.toUpperCase(propertyName.charAt(0)) + propertyName.substring(1); String setMethodName = "set" + baseName; String getMethodName = "get" + baseName; Method[] methods = clazz.getMethods(); for (Method method : methods) { if (method.getName().equals(getMethodName) && !method.isBridge() && !method.isSynthetic()) { try { descriptor.setReadMethod(method); } catch (IntrospectionException e) { // move on } } if (method.getName().equals(setMethodName) && !method.isBridge() && !method.isSynthetic()) { try { descriptor.setWriteMethod(method); } catch (IntrospectionException e) { // move on } } } } return descriptor; }
/** * Define an attribute on the managed object. The meta data is defined by looking for standard * getter and setter methods. Descriptions are obtained with a call to findDescription with the * attribute name. * * @param name The name of the attribute. Normal java bean capitlization is enforced on this name. * @param writable If false, do not look for a setter. * @param onMBean . */ public synchronized void defineAttribute(String name, boolean writable, boolean onMBean) { _dirty = true; String uName = name.substring(0, 1).toUpperCase() + name.substring(1); name = java.beans.Introspector.decapitalize(name); Class oClass = onMBean ? this.getClass() : _object.getClass(); Class type = null; Method getter = null; Method setter = null; Method[] methods = oClass.getMethods(); for (int m = 0; m < methods.length; m++) { if ((methods[m].getModifiers() & Modifier.PUBLIC) == 0) continue; // Look for a getter if (methods[m].getName().equals("get" + uName) && methods[m].getParameterTypes().length == 0) { if (getter != null) throw new IllegalArgumentException("Multiple getters for attr " + name); getter = methods[m]; if (type != null && !type.equals(methods[m].getReturnType())) throw new IllegalArgumentException("Type conflict for attr " + name); type = methods[m].getReturnType(); } // Look for an is getter if (methods[m].getName().equals("is" + uName) && methods[m].getParameterTypes().length == 0) { if (getter != null) throw new IllegalArgumentException("Multiple getters for attr " + name); getter = methods[m]; if (type != null && !type.equals(methods[m].getReturnType())) throw new IllegalArgumentException("Type conflict for attr " + name); type = methods[m].getReturnType(); } // look for a setter if (writable && methods[m].getName().equals("set" + uName) && methods[m].getParameterTypes().length == 1) { if (setter != null) throw new IllegalArgumentException("Multiple setters for attr " + name); setter = methods[m]; if (type != null && !type.equals(methods[m].getParameterTypes()[0])) throw new IllegalArgumentException("Type conflict for attr " + name); type = methods[m].getParameterTypes()[0]; } } if (getter == null && setter == null) throw new IllegalArgumentException("No getter or setters found for " + name); try { // Remember the methods _getter.put(name, getter); _setter.put(name, setter); // create and add the info _attributes.add(new ModelMBeanAttributeInfo(name, findDescription(name), getter, setter)); } catch (Exception e) { log.warn(LogSupport.EXCEPTION, e); throw new IllegalArgumentException(e.toString()); } }
public static Method[] findMethodsByAnnotation( Class<?> owner, Class<? extends Annotation> annotationClass) { Method[] methods = owner.getMethods(); ArrayBuilder<Method> builder = new ArrayBuilder<Method>(Method.class); for (Method method : methods) if (method.getAnnotation(annotationClass) != null) builder.add(method); return builder.toArray(); }
private void writeDelegateMethods( final ClassVisitor visitor, final Type generatedType, StructSchema<?> delegateSchema, Set<Class<?>> typesToDelegate) { Class<?> delegateClass = delegateSchema.getType().getConcreteClass(); Type delegateType = Type.getType(delegateClass); Map<Equivalence.Wrapper<Method>, Map<Class<?>, Method>> methodsToDelegate = Maps.newHashMap(); for (Class<?> typeToDelegate : typesToDelegate) { for (Method methodToDelegate : typeToDelegate.getMethods()) { if (ModelSchemaUtils.isIgnoredMethod(methodToDelegate)) { continue; } Equivalence.Wrapper<Method> methodKey = METHOD_EQUIVALENCE.wrap(methodToDelegate); Map<Class<?>, Method> methodsByReturnType = methodsToDelegate.get(methodKey); if (methodsByReturnType == null) { methodsByReturnType = Maps.newHashMap(); methodsToDelegate.put(methodKey, methodsByReturnType); } methodsByReturnType.put(methodToDelegate.getReturnType(), methodToDelegate); } } Set<Equivalence.Wrapper<Method>> delegateMethodKeys = ImmutableSet.copyOf( Iterables.transform( Arrays.asList(delegateClass.getMethods()), new Function<Method, Equivalence.Wrapper<Method>>() { @Override public Equivalence.Wrapper<Method> apply(Method method) { return METHOD_EQUIVALENCE.wrap(method); } })); for (Map.Entry<Equivalence.Wrapper<Method>, Map<Class<?>, Method>> entry : methodsToDelegate.entrySet()) { Equivalence.Wrapper<Method> methodKey = entry.getKey(); if (!delegateMethodKeys.contains(methodKey)) { continue; } Map<Class<?>, Method> methodsByReturnType = entry.getValue(); for (Method methodToDelegate : methodsByReturnType.values()) { writeDelegatedMethod(visitor, generatedType, delegateType, methodToDelegate); } } }
static <T> T set(Class<T> interf, Object value) { Properties p = new Properties(); Method ms[] = interf.getMethods(); for (Method m : ms) { p.put(m.getName(), value); } return Configurable.createConfigurable(interf, (Map<Object, Object>) p); }
private static Method findMethod(Class<?> clazz, String methodName) { Method[] methods = clazz.getMethods(); Method result = null; for (Method method : methods) { if (method.getName().equals(methodName)) { result = method; } } return result; }
Method getMethod(Class cls, String methodName) throws IntrospectionException { Method methods[] = cls.getMethods(); for (int i = 0; i < methods.length; i++) { if (methods[i].getName().equals(methodName)) { return methods[i]; } } throw new IntrospectionException("No method \"" + methodName); }
private static boolean isTest(Class c) { for( Annotation a : c.getAnnotations() ) if( a instanceof Ignore ) return false; for( Method m : c.getMethods() ) for( Annotation a : m.getAnnotations() ) if( a instanceof Test ) return true; return false; }
public static Method getNonVoidSetter(Class<?> clazz, String fieldName) { String methodName = "set" + StringUtils.capitalize(fieldName); for (Method method : clazz.getMethods()) { if (method.getName().equals(methodName) && method.getParameterTypes().length == 1 && method.getReturnType() != Void.TYPE) { return method; } } return null; }
private Method getMethodByName(String methodName, Class<?> entityClazz) { Method[] methods = entityClazz.getMethods(); Method method = null; for (Method i : methods) { if (methodName.equals(i.getName())) { method = i; break; } } return method; }
private void populateInternalMap(Object bean, boolean includeSuperClass) { Class klass = bean.getClass(); // If klass.getSuperClass is System class then includeSuperClass = false; if (klass.getClassLoader() == null) { includeSuperClass = false; } Method[] methods = (includeSuperClass) ? klass.getMethods() : klass.getDeclaredMethods(); for (int i = 0; i < methods.length; i += 1) { try { Method method = methods[i]; String name = method.getName(); String key = ""; if (name.startsWith("get")) { key = name.substring(3); } else if (name.startsWith("is")) { key = name.substring(2); } if (key.length() > 0 && Character.isUpperCase(key.charAt(0)) && method.getParameterTypes().length == 0) { if (key.length() == 1) { key = key.toLowerCase(); } else if (!Character.isUpperCase(key.charAt(1))) { key = key.substring(0, 1).toLowerCase() + key.substring(1); } Object result = method.invoke(bean, (Object[]) null); if (result == null) { map.put(key, NULL); } else if (result.getClass().isArray()) { map.put(key, new JSONArray(result, includeSuperClass)); } else if (result instanceof Collection) { // List or Set map.put(key, new JSONArray((Collection) result, includeSuperClass)); } else if (result instanceof Map) { map.put(key, new JSONObject((Map) result, includeSuperClass)); } else if (isStandardProperty(result.getClass())) { // Primitives, String and Wrapper map.put(key, result); } else { if (result.getClass().getPackage().getName().startsWith("java") || result.getClass().getClassLoader() == null) { map.put(key, result.toString()); } else { // User defined Objects map.put(key, new JSONObject(result, includeSuperClass)); } } } } catch (Exception e) { throw new RuntimeException(e); } } }
/** * Prints information about a class' parents and methods to a PrintWriter * * @param object * @param printer */ public static void printClassInfo(Object object, PrintWriter printer) { if (object == null) { printer.println("null"); return; } Class<?> type = object.getClass(); printer.println(type); if (type.getSuperclass() != null) printer.println("extends " + type.getSuperclass()); for (Class<?> interf : type.getInterfaces()) printer.println("implements " + interf); for (Method method : type.getMethods()) { printer.println(method); } }
/** * Adds to the given list of property descriptors the mapped properties, ie. properties that have * a getter method taking a single String value as a parameter. * * @param clazz to introspect * @param result is the list to add to */ protected static void addMappedProperties(Class clazz, List<InternalEventPropDescriptor> result) { Set<String> uniquePropertyNames = new HashSet<String>(); Method[] methods = clazz.getMethods(); for (int i = 0; i < methods.length; i++) { String methodName = methods[i].getName(); if (!methodName.startsWith("get")) { continue; } String inferredName = methodName.substring(3, methodName.length()); if (inferredName.length() == 0) { continue; } Class<?> parameterTypes[] = methods[i].getParameterTypes(); if (parameterTypes.length != 1) { continue; } if (parameterTypes[0] != String.class) { continue; } String newInferredName = null; // Leave uppercase inferred names such as URL if (inferredName.length() >= 2) { if ((Character.isUpperCase(inferredName.charAt(0))) && (Character.isUpperCase(inferredName.charAt(1)))) { newInferredName = inferredName; } } // camelCase the inferred name if (newInferredName == null) { newInferredName = Character.toString(Character.toLowerCase(inferredName.charAt(0))); if (inferredName.length() > 1) { newInferredName += inferredName.substring(1, inferredName.length()); } } inferredName = newInferredName; // if the property inferred name already exists, don't supply it if (uniquePropertyNames.contains(inferredName)) { continue; } result.add( new InternalEventPropDescriptor(inferredName, methods[i], EventPropertyType.MAPPED)); uniquePropertyNames.add(inferredName); } }
Method findAddNew(String attributeName, Class xmlClass) { Method[] methods = xmlClass.getMethods(); String name = "addNew" + attributeName.substring(0, 1).toUpperCase() + attributeName.substring(1); log.debug("search method of name '" + name + "'"); for (Method method : methods) { if (method.getName().equals(name)) { return method; } } return null; }
private static List<Method> getInheritedMethods(Class baseClass, List<Method> methods) { Collections.addAll(methods, baseClass.getMethods()); Class currentClass = baseClass; while (currentClass != null) { Method[] protectedMethods = currentClass.getDeclaredMethods(); for (Method method : protectedMethods) { if (method.getName().indexOf('$') != -1) continue; if (Modifier.isProtected(method.getModifiers()) && !containsEquivalentMethod(methods, method)) methods.add(method); } currentClass = currentClass.getSuperclass(); } return methods; }
/** * Finds a method by reflection. This iterates all methods of the class, comparing names and * parameter types. Unlike the method Class.getMethod(String, Class ...), this method is able to * match primitive and wrapper types. If no appropriate method is found, 'null' is returned * * @param type * @param methodName * @param paramTypes * @return a method with matching names and parameters */ public static Method findMethod(Class<?> type, String methodName, Class<?>... paramTypes) { Method result = null; for (Method method : type.getMethods()) { if (!methodName.equals(method.getName())) continue; if (typesMatch(paramTypes, method.getParameterTypes())) { result = method; if ((ArrayUtil.isEmpty(paramTypes) && ArrayUtil.isEmpty(method.getParameterTypes())) || paramTypes.length == method.getParameterTypes().length) return method; // optimal match - return it immediately else result = method; // sub optimal match - store it, but keep on searching for better matches } } return result; }
private static Set<MethodInfo> getGetterMethodInfo(Class<?> clazz) { Set<MethodInfo> methodInfos = METHOD_MAP.get(clazz); if (methodInfos == null) { methodInfos = new HashSet<MethodInfo>(); boolean includeSuperClass = clazz.getClassLoader() != null; Method[] methods = includeSuperClass ? clazz.getMethods() : clazz.getDeclaredMethods(); for (Method method : methods) { try { if (Modifier.isPublic(method.getModifiers())) { String name = method.getName(); String key = ""; if (name.startsWith("get")) { if ("getClass".equals(name) || "getDeclaringClass".equals(name)) { key = ""; } else { key = name.substring(3); } } else if (name.startsWith("is")) { key = name.substring(2); } if (key.length() > 0 && Character.isUpperCase(key.charAt(0)) && method.getParameterTypes().length == 0) { if (key.length() == 1) { key = key.toLowerCase(); } else if (!Character.isUpperCase(key.charAt(1))) { key = key.substring(0, 1).toLowerCase() + key.substring(1); } methodInfos.add(new MethodInfo(key, method)); } } } catch (Exception ignored) { } } METHOD_MAP.putIfAbsent(clazz, methodInfos); } return methodInfos; }
/** {@inheritDoc} */ public Object setObjectValue( StringToObjectConverter pConverter, Object pInner, String pAttribute, Object pValue) throws IllegalAccessException, InvocationTargetException { // Move this to plain object handler String rest = new StringBuffer(pAttribute.substring(0, 1).toUpperCase()) .append(pAttribute.substring(1)) .toString(); String setter = new StringBuffer("set").append(rest).toString(); String getter = new StringBuffer("get").append(rest).toString(); Class clazz = pInner.getClass(); Method found = null; for (Method method : clazz.getMethods()) { if (method.getName().equals(setter)) { found = method; break; } } if (found == null) { throw new IllegalArgumentException( "No Method " + setter + " known for object of type " + clazz.getName()); } Class params[] = found.getParameterTypes(); if (params.length != 1) { throw new IllegalArgumentException( "Invalid parameter signature for " + setter + " known for object of type " + clazz.getName() + ". Setter must take exactly one parameter."); } Object oldValue; try { final Method getMethod = clazz.getMethod(getter); AccessController.doPrivileged(new SetMethodAccessibleAction(getMethod)); oldValue = getMethod.invoke(pInner); } catch (NoSuchMethodException exp) { // Ignored, we simply dont return an old value oldValue = null; } AccessController.doPrivileged(new SetMethodAccessibleAction(found)); found.invoke(pInner, pConverter.prepareValue(params[0].getName(), pValue)); return oldValue; }
public static void removeModule(Class<? extends Module> c) { for (Method m : c.getMethods()) { Command command; command = m.getAnnotation(Command.class); if (command != null) { System.out.println("unregistered " + command.name()); commandData.remove(command.name()); allCommands.remove(command.name()); if (command.alias() != null && command.alias().length > 0) { for (String s : command.alias()) { allCommands.remove(s); } } } } }
// // Return the methods of an interface in a deterministic // order. Class.getMethods() does not do us this favor. // private Method[] sortMethods(Class iface) throws Exception { Method[] raw = iface.getMethods(); int count = raw.length; Method[] cooked = new Method[count]; MethodSortable[] sortables = new MethodSortable[count]; for (int i = 0; i < count; i++) { sortables[i] = new MethodSortable(raw[i]); } Arrays.sort(sortables); for (int i = 0; i < count; i++) { cooked[i] = sortables[i].getMethod(); } return cooked; }
private DependencyAnnotations createDependencyAnnotations(Class ruleClass) { DependencyAnnotations da = new DependencyAnnotations(); for (Method m : ruleClass.getMethods()) { Consumes consumes = m.getAnnotation(Consumes.class); if (consumes != null) { // System.out.println("Adding consumes "+m.getName()); da.addConsumesMethod(consumes.value(), m); } else { Provides provides = m.getAnnotation(Provides.class); if (provides != null) { // System.out.println("Adding provides "+m.getName()); da.addProvidesMethod(provides.value(), m); } } } return da; }