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."); } }
private void validateClass(Class<?> source, ValidationProblemCollector problems) { int modifiers = source.getModifiers(); if (Modifier.isInterface(modifiers)) { problems.add("Must be a class, not an interface"); } if (source.getEnclosingClass() != null) { if (Modifier.isStatic(modifiers)) { if (Modifier.isPrivate(modifiers)) { problems.add("Class cannot be private"); } } else { problems.add("Enclosed classes must be static and non private"); } } Constructor<?>[] constructors = source.getDeclaredConstructors(); for (Constructor<?> constructor : constructors) { if (constructor.getParameterTypes().length > 0) { problems.add("Cannot declare a constructor that takes arguments"); break; } } Field[] fields = source.getDeclaredFields(); for (Field field : fields) { int fieldModifiers = field.getModifiers(); if (!field.isSynthetic() && !(Modifier.isStatic(fieldModifiers) && Modifier.isFinal(fieldModifiers))) { problems.add(field, "Fields must be static final."); } } }
/** * 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; } } }
public static String isLocalType(Class<?> type) { /* As per [JACKSON-187], GAE seems to throw SecurityExceptions * here and there... and GAE itself has a bug, too * (see []). Bah. */ try { // one more: method locals, anonymous, are not good: if (type.getEnclosingMethod() != null) { return "local/anonymous"; } /* But how about non-static inner classes? Can't construct * easily (theoretically, we could try to check if parent * happens to be enclosing... but that gets convoluted) */ if (type.getEnclosingClass() != null) { if (!Modifier.isStatic(type.getModifiers())) { return "non-static member class"; } } } catch (SecurityException e) { } catch (NullPointerException e) { } return null; }
static Method[] getOverridableMethods(Class c) { ArrayList<Method> list = new ArrayList<Method>(); HashSet<String> skip = new HashSet<String>(); while (c != null) { Method[] methods = c.getDeclaredMethods(); for (int i = 0; i < methods.length; i++) { String methodKey = methods[i].getName() + getMethodSignature(methods[i], methods[i].getParameterTypes()); if (skip.contains(methodKey)) continue; // skip this method int mods = methods[i].getModifiers(); if (Modifier.isStatic(mods)) continue; if (Modifier.isFinal(mods)) { // Make sure we don't add a final method to the list // of overridable methods. skip.add(methodKey); continue; } if (Modifier.isPublic(mods) || Modifier.isProtected(mods)) { list.add(methods[i]); skip.add(methodKey); } } c = c.getSuperclass(); } return list.toArray(new Method[list.size()]); }
/** * 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<>(); } }
public JavaType findType(String name) { if (_bindings == null) { _resolve(); } JavaType t = _bindings.get(name); if (t != null) { return t; } if (_placeholders != null && _placeholders.contains(name)) { return UNBOUND; } // New with 1.7: check parent context if (_parentBindings != null) { return _parentBindings.findType(name); } // nothing found, so... // Should we throw an exception or just return null? /* [JACKSON-499] 18-Feb-2011, tatu: There are some tricky type bindings within * java.util, such as HashMap$KeySet; so let's punt the problem * (honestly not sure what to do -- they are unbound for good, I think) */ if (_contextClass != null) { Class<?> enclosing = _contextClass.getEnclosingClass(); if (enclosing != null) { // [JACKSON-572]: Actually, let's skip this for all non-static inner classes // (which will also cover 'java.util' type cases... if (!Modifier.isStatic(_contextClass.getModifiers())) { return UNBOUND; } // ... so this piece of code should not be needed any more /* Package pkg = enclosing.getPackage(); if (pkg != null) { // as per [JACKSON-533], also include "java.util.concurrent": if (pkg.getName().startsWith("java.util")) { return UNBOUND; } } */ } } String className; if (_contextClass != null) { className = _contextClass.getName(); } else if (_contextType != null) { className = _contextType.toString(); } else { className = "UNKNOWN"; } throw new IllegalArgumentException( "Type variable '" + name + "' can not be resolved (with context of class " + className + ")"); // t = UNBOUND; }
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"); } }
{ 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); } } }
/** * 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); }
static Method[] getOverridableMethods(Class c) { ArrayList list = new ArrayList(); while (c != null) { Method[] methods = c.getDeclaredMethods(); for (int i = 0; i < methods.length; i++) { int mods = methods[i].getModifiers(); if (Modifier.isStatic(mods) || Modifier.isFinal(mods)) continue; if (Modifier.isPublic(mods) || Modifier.isProtected(mods)) list.add(methods[i]); } c = c.getSuperclass(); } return (Method[]) list.toArray(new Method[list.size()]); }
private static LinkedHashMap<String, Prop> createProps() { Field[] fs = Configuration.class.getDeclaredFields(); LinkedHashMap<String, Prop> res = new LinkedHashMap<String, Prop>(); for (Field f : fs) if (!Modifier.isStatic(f.getModifiers())) { Description annotation = f.getAnnotation(Description.class); if (annotation != null) { String name = f.getName().replace('_', '.'); res.put(name, new Prop(name, annotation.value(), f)); } } return res; }
private boolean _isIncludableField(Field f) { /* I'm pretty sure synthetic fields are to be skipped... * (methods definitely are) */ if (f.isSynthetic()) { return false; } // Static fields are never included, nor transient int mods = f.getModifiers(); if (Modifier.isStatic(mods) || Modifier.isTransient(mods)) { return false; } return true; }
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 void checkString(T instance) { assertThat( instance.toString(), CoreMatchers.startsWith( type.getCanonicalName().substring(type.getPackage().getName().length() + 1) + "{")); assertThat(instance.toString(), endsWith("}")); Class<?> currentType = type; do { for (Field field : type.getDeclaredFields()) { if (!field.isSynthetic() && !Modifier.isStatic(field.getModifiers()) && !ignoredFields.contains(field.getName())) { assertThat(instance.toString(), containsString(field.getName())); } } } while ((currentType = currentType.getSuperclass()) != Object.class); }
/** * 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"); } }
/** * Returns the shallow instance size in bytes an instance of the given class would occupy. This * works with all conventional classes and primitive types, but not with arrays (the size then * depends on the number of elements and varies from object to object). * * @see #shallowSizeOf(Object) * @throws IllegalArgumentException if {@code clazz} is an array class. */ public static long shallowSizeOfInstance(Class<?> clazz) { if (clazz.isArray()) throw new IllegalArgumentException("This method does not work with array classes."); if (clazz.isPrimitive()) return primitiveSizes.get(clazz); long size = NUM_BYTES_OBJECT_HEADER; // Walk type hierarchy for (; clazz != null; clazz = clazz.getSuperclass()) { final Field[] fields = clazz.getDeclaredFields(); for (Field f : fields) { if (!Modifier.isStatic(f.getModifiers())) { size = adjustForField(size, f); } } } return alignObjectSize(size); }
private MutableTreeNode populateAttributes(CavityDBObject obj) { DefaultMutableTreeNode tree = new DefaultMutableTreeNode("attrs"); Class cls = obj.getClass(); for (Field f : cls.getFields()) { int mod = f.getModifiers(); if (Modifier.isPublic(mod) && !Modifier.isStatic(mod)) { String fieldName = f.getName(); try { Object value = f.get(obj); tree.add( new DefaultMutableTreeNode(String.format("%s=%s", fieldName, String.valueOf(value)))); } catch (IllegalAccessException e) { // do nothing. } } } return tree; }
public ASTMethodNode inline(SootMethod maybeInline) { // check if this method should be inlined if (sootClass != null) { // 1, method should belong to the same class as the clinit method if (sootClass.declaresMethod(maybeInline.getSubSignature())) { // System.out.println("The method invoked is from the same class"); // 2, method should be static if (Modifier.isStatic(maybeInline.getModifiers())) { // decided to inline // send the ASTMethod node of the TO BE INLINED METHOD // retireve the active body if (!maybeInline.hasActiveBody()) throw new RuntimeException("method " + maybeInline.getName() + " has no active body!"); Body bod = maybeInline.getActiveBody(); Chain units = ((DavaBody) bod).getUnits(); if (units.size() != 1) { throw new RuntimeException("DavaBody AST doesn't have single root."); } ASTNode ASTtemp = (ASTNode) units.getFirst(); if (!(ASTtemp instanceof ASTMethodNode)) throw new RuntimeException("Starting node of DavaBody AST is not an ASTMethodNode"); // restricting to methods which do not have any variables declared ASTMethodNode toReturn = (ASTMethodNode) ASTtemp; ASTStatementSequenceNode declarations = toReturn.getDeclarations(); if (declarations.getStatements().size() == 0) { // inline only if there are no declarations in the method inlined System.out.println("No declarations in the method. we can inline this method"); return toReturn; } } } } return null; // meaning dont inline }
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; }
private static void appendOverridableMethods( Class<?> c, ArrayList<Method> list, HashSet<String> skip) { Method[] methods = c.getDeclaredMethods(); for (int i = 0; i < methods.length; i++) { String methodKey = methods[i].getName() + getMethodSignature(methods[i], methods[i].getParameterTypes()); if (skip.contains(methodKey)) continue; // skip this method int mods = methods[i].getModifiers(); if (Modifier.isStatic(mods)) continue; if (Modifier.isFinal(mods)) { // Make sure we don't add a final method to the list // of overridable methods. skip.add(methodKey); continue; } if (Modifier.isPublic(mods) || Modifier.isProtected(mods)) { list.add(methods[i]); skip.add(methodKey); } } }
/** * 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; }
/** Create a cached information about shallow size and reference fields for a given class. */ private static ClassCache createCacheEntry(final Class<?> clazz) { ClassCache cachedInfo; long shallowInstanceSize = NUM_BYTES_OBJECT_HEADER; final ArrayList<Field> referenceFields = new ArrayList<Field>(32); for (Class<?> c = clazz; c != null; c = c.getSuperclass()) { final Field[] fields = c.getDeclaredFields(); for (final Field f : fields) { if (!Modifier.isStatic(f.getModifiers())) { shallowInstanceSize = adjustForField(shallowInstanceSize, f); if (!f.getType().isPrimitive()) { f.setAccessible(true); referenceFields.add(f); } } } } cachedInfo = new ClassCache( alignObjectSize(shallowInstanceSize), referenceFields.toArray(new Field[referenceFields.size()])); return cachedInfo; }
public boolean storeableField(Class a_class, Field a_field) { return (!Modifier.isStatic(a_field.getModifiers())) && (!Modifier.isTransient(a_field.getModifiers()) & !(a_field.getName().indexOf("$") > -1)); }
public static String generateProxy(Class interfaceClass) throws Exception { StringBuilder b = new StringBuilder(); b.append("#include <jni.h>\n"); b.append("#ifdef _WIN32\n"); b.append("#define PROXY_EXPORT __declspec(dllexport)\n"); b.append("#else\n"); b.append("#define PROXY_EXPORT\n"); b.append("#endif\n"); b.append( "#define FIND_GLOBAL_CLASS(name) (*env)->NewGlobalRef(env, (*env)->FindClass(env, name))\n"); List<ProxiedMethod> methods = new ArrayList<ProxiedMethod>(); int iClassName = 0, iMethodName = 0; Map<Class, String> classVarNames = new HashMap<Class, String>(); for (Method m : interfaceClass.getDeclaredMethods()) { try { ProxiedMethod pm = getProxiedMethod(m); String classVarName = classVarNames.get(pm.owner); if (classVarName == null) classVarNames.put(pm.owner, classVarName = "gClass" + (++iClassName)); pm.classVarName = classVarName; pm.methodVarName = "gMethod" + (++iMethodName); methods.add(pm); } catch (Throwable th) { // th.printStackTrace(); } } b.append("jboolean inited = JNI_FALSE;\n"); String instanceVarName = "gProxiedInstance"; b.append("JNIEnv* env = NULL;\n"); b.append("JavaVM* jvm = NULL;\n"); b.append("jobject ").append(instanceVarName).append(" = NULL;\n"); for (String n : classVarNames.values()) b.append("jclass ").append(n).append(" = NULL;\n"); for (ProxiedMethod pm : methods) b.append("jmethodID ").append(pm.methodVarName).append(" = NULL;\n"); String jniInit = "jni_init"; b.append("void ").append(jniInit).append("(JNIEnv* env) {\n"); b.append("\tif (inited) return; else inited = JNI_TRUE;\n"); for (Map.Entry<Class, String> e : classVarNames.entrySet()) { String n = e.getValue(); Class c = e.getKey(); b.append("\t") .append(n) .append(" = ") .append("FIND_GLOBAL_CLASS(\"") .append(name(c)) .append("\");\n"); } for (ProxiedMethod pm : methods) { int mods = pm.method.getModifiers(); b.append("\t") .append(pm.methodVarName) .append(" = ") .append("(*env)->") .append(Modifier.isStatic(mods) ? "GetStaticMethodID" : "GetMethodID") .append("(env, ") .append(pm.classVarName) .append(", \"") .append(pm.name) .append("\", \"") .append(pm.jni_signature) .append("\");\n"); } b.append("}\n"); for (ProxiedMethod pm : methods) { b.append("PROXY_EXPORT ").append(pm.c_signature).append(" {\n"); int mods = pm.method.getModifiers(); b.append("\t").append(jniInit).append("();\n"); b.append("\t"); if (pm.method.getReturnType() != null && !pm.method.getReturnType().equals(void.class)) b.append("return "); StringBuilder r = new StringBuilder(); boolean stat = Modifier.isStatic(mods); r.append("(*env)->") .append("Call" + (stat ? "Static" : "") + pm.retCapitalized + "Method") .append("(env, "); if (stat) r.append(pm.classVarName); else r.append(instanceVarName); for (String argValue : pm.argValues) { r.append(", \n\t\t"); r.append(argValue); } // TODO... r.append("\n\t)"); b.append(c_signature(pm.method.getReturnType(), r.toString())[2]); b.append(";\n"); b.append("}\n"); } return b.toString(); }
/** * Entity Bean's ejbPostCreate(...) methods test. Each entity Bean class may define zero or more * ejbPostCreate(...) methods. The number and signatures of a entity Bean's create methods are * specific to each EJB class. The method signatures must follow these rules: * * <p>The method name must be ejbPostCreate. * * <p>The method must not be declared as static. * * @param descriptor the Enterprise Java Bean deployment descriptor * @return <code>Result</code> the results for this assertion */ public Result check(EjbDescriptor descriptor) { Result result = getInitializedResult(); ComponentNameConstructor compName = getVerifierContext().getComponentNameConstructor(); if (descriptor instanceof EjbEntityDescriptor) { boolean oneFailed = false; int foundAtLeastOne = 0; try { Context context = getVerifierContext(); ClassLoader jcl = context.getClassLoader(); Class c = Class.forName( descriptor.getEjbClassName(), false, getVerifierContext().getClassLoader()); boolean ejbPostCreateFound = false; boolean isStatic = false; // start do while loop here.... do { Method[] methods = c.getDeclaredMethods(); for (int i = 0; i < methods.length; i++) { // reset flags from last time thru loop ejbPostCreateFound = false; isStatic = false; // The method name must be ejbPostCreate. if (methods[i].getName().startsWith("ejbPostCreate")) { foundAtLeastOne++; ejbPostCreateFound = true; // The method must not be declared as final or static. int modifiers = methods[i].getModifiers(); if (Modifier.isStatic(modifiers)) { isStatic = true; } // now display the appropriate results for this particular // ejbPostCreate method if (ejbPostCreateFound && (!isStatic)) { result.addGoodDetails( smh.getLocalString( "tests.componentNameConstructor", "For [ {0} ]", new Object[] {compName.toString()})); result.addGoodDetails( smh.getLocalString( getClass().getName() + ".debug1", "For EJB Class [ {0} ] method [ {1} ]", new Object[] {descriptor.getEjbClassName(), methods[i].getName()})); result.addGoodDetails( smh.getLocalString( getClass().getName() + ".passed", "[ {0} ] properly declares non-static [ {1} ] method.", new Object[] {descriptor.getEjbClassName(), methods[i].getName()})); } else if (ejbPostCreateFound && isStatic) { oneFailed = true; result.addErrorDetails( smh.getLocalString( "tests.componentNameConstructor", "For [ {0} ]", new Object[] {compName.toString()})); result.addErrorDetails( smh.getLocalString( getClass().getName() + ".debug1", "For EJB Class [ {0} ] ejbPostCreate(...) Method [ {1} ]", new Object[] {descriptor.getEjbClassName(), methods[i].getName()})); result.addErrorDetails( smh.getLocalString( getClass().getName() + ".failed", "Error: A static [ {0} ] method was found, but [ {1} ] cannot be declared as static.", new Object[] {methods[i].getName(), methods[i].getName()})); } } } } while (((c = c.getSuperclass()) != null) && (foundAtLeastOne == 0)); if (foundAtLeastOne == 0) { result.addNaDetails( smh.getLocalString( "tests.componentNameConstructor", "For [ {0} ]", new Object[] {compName.toString()})); result.notApplicable( smh.getLocalString( getClass().getName() + ".notApplicable1", "[ {0} ] does not declare any ejbPostCreate(...) methods.", new Object[] {descriptor.getEjbClassName()})); } } catch (ClassNotFoundException e) { Verifier.debug(e); result.addErrorDetails( smh.getLocalString( "tests.componentNameConstructor", "For [ {0} ]", new Object[] {compName.toString()})); result.failed( smh.getLocalString( getClass().getName() + ".failedException", "Error: [ {0} ] class not found.", new Object[] {descriptor.getEjbClassName()})); oneFailed = true; } if (oneFailed) { result.setStatus(result.FAILED); } else if (foundAtLeastOne == 0) { result.setStatus(result.NOT_APPLICABLE); } else { result.setStatus(result.PASSED); } return result; } else { result.addNaDetails( smh.getLocalString( "tests.componentNameConstructor", "For [ {0} ]", new Object[] {compName.toString()})); result.notApplicable( smh.getLocalString( getClass().getName() + ".notApplicable", "[ {0} ] expected {1} bean, but called with {2} bean.", new Object[] {getClass(), "Entity", "Session"})); return result; } }
/** * 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); } } } } }
@SuppressWarnings("unchecked") LDAPObjectHandler(final Class<T> type) throws LDAPPersistException { this.type = type; final Class<? super T> superclassType = type.getSuperclass(); if (superclassType == null) { superclassHandler = null; } else { final LDAPObject superclassAnnotation = superclassType.getAnnotation(LDAPObject.class); if (superclassAnnotation == null) { superclassHandler = null; } else { superclassHandler = new LDAPObjectHandler(superclassType); } } final TreeMap<String, FieldInfo> fields = new TreeMap<String, FieldInfo>(); final TreeMap<String, GetterInfo> getters = new TreeMap<String, GetterInfo>(); final TreeMap<String, SetterInfo> setters = new TreeMap<String, SetterInfo>(); ldapObject = type.getAnnotation(LDAPObject.class); if (ldapObject == null) { throw new LDAPPersistException(ERR_OBJECT_HANDLER_OBJECT_NOT_ANNOTATED.get(type.getName())); } final LinkedHashMap<String, String> objectClasses = new LinkedHashMap<String, String>(10); final String oc = ldapObject.structuralClass(); if (oc.length() == 0) { structuralClass = getUnqualifiedClassName(type); } else { structuralClass = oc; } final StringBuilder invalidReason = new StringBuilder(); if (PersistUtils.isValidLDAPName(structuralClass, invalidReason)) { objectClasses.put(toLowerCase(structuralClass), structuralClass); } else { throw new LDAPPersistException( ERR_OBJECT_HANDLER_INVALID_STRUCTURAL_CLASS.get( type.getName(), structuralClass, invalidReason.toString())); } auxiliaryClasses = ldapObject.auxiliaryClass(); for (final String auxiliaryClass : auxiliaryClasses) { if (PersistUtils.isValidLDAPName(auxiliaryClass, invalidReason)) { objectClasses.put(toLowerCase(auxiliaryClass), auxiliaryClass); } else { throw new LDAPPersistException( ERR_OBJECT_HANDLER_INVALID_AUXILIARY_CLASS.get( type.getName(), auxiliaryClass, invalidReason.toString())); } } superiorClasses = ldapObject.superiorClass(); for (final String superiorClass : superiorClasses) { if (PersistUtils.isValidLDAPName(superiorClass, invalidReason)) { objectClasses.put(toLowerCase(superiorClass), superiorClass); } else { throw new LDAPPersistException( ERR_OBJECT_HANDLER_INVALID_SUPERIOR_CLASS.get( type.getName(), superiorClass, invalidReason.toString())); } } if (superclassHandler != null) { for (final String s : superclassHandler.objectClassAttribute.getValues()) { objectClasses.put(toLowerCase(s), s); } } objectClassAttribute = new Attribute("objectClass", objectClasses.values()); final String parentDNStr = ldapObject.defaultParentDN(); try { defaultParentDN = new DN(parentDNStr); } catch (LDAPException le) { throw new LDAPPersistException( ERR_OBJECT_HANDLER_INVALID_DEFAULT_PARENT.get( type.getName(), parentDNStr, le.getMessage()), le); } final String postDecodeMethodName = ldapObject.postDecodeMethod(); if (postDecodeMethodName.length() > 0) { try { postDecodeMethod = type.getDeclaredMethod(postDecodeMethodName); postDecodeMethod.setAccessible(true); } catch (Exception e) { debugException(e); throw new LDAPPersistException( ERR_OBJECT_HANDLER_INVALID_POST_DECODE_METHOD.get( type.getName(), postDecodeMethodName, getExceptionMessage(e)), e); } } else { postDecodeMethod = null; } final String postEncodeMethodName = ldapObject.postEncodeMethod(); if (postEncodeMethodName.length() > 0) { try { postEncodeMethod = type.getDeclaredMethod(postEncodeMethodName, Entry.class); postEncodeMethod.setAccessible(true); } catch (Exception e) { debugException(e); throw new LDAPPersistException( ERR_OBJECT_HANDLER_INVALID_POST_ENCODE_METHOD.get( type.getName(), postEncodeMethodName, getExceptionMessage(e)), e); } } else { postEncodeMethod = null; } try { constructor = type.getDeclaredConstructor(); constructor.setAccessible(true); } catch (Exception e) { debugException(e); throw new LDAPPersistException( ERR_OBJECT_HANDLER_NO_DEFAULT_CONSTRUCTOR.get(type.getName()), e); } Field tmpDNField = null; Field tmpEntryField = null; final LinkedList<FieldInfo> tmpRFilterFields = new LinkedList<FieldInfo>(); final LinkedList<FieldInfo> tmpAAFilterFields = new LinkedList<FieldInfo>(); final LinkedList<FieldInfo> tmpCAFilterFields = new LinkedList<FieldInfo>(); final LinkedList<FieldInfo> tmpRDNFields = new LinkedList<FieldInfo>(); for (final Field f : type.getDeclaredFields()) { final LDAPField fieldAnnotation = f.getAnnotation(LDAPField.class); final LDAPDNField dnFieldAnnotation = f.getAnnotation(LDAPDNField.class); final LDAPEntryField entryFieldAnnotation = f.getAnnotation(LDAPEntryField.class); if (fieldAnnotation != null) { f.setAccessible(true); final FieldInfo fieldInfo = new FieldInfo(f, type); final String attrName = toLowerCase(fieldInfo.getAttributeName()); if (fields.containsKey(attrName)) { throw new LDAPPersistException( ERR_OBJECT_HANDLER_ATTR_CONFLICT.get(type.getName(), fieldInfo.getAttributeName())); } else { fields.put(attrName, fieldInfo); } switch (fieldInfo.getFilterUsage()) { case REQUIRED: tmpRFilterFields.add(fieldInfo); break; case ALWAYS_ALLOWED: tmpAAFilterFields.add(fieldInfo); break; case CONDITIONALLY_ALLOWED: tmpCAFilterFields.add(fieldInfo); break; case EXCLUDED: default: break; } if (fieldInfo.includeInRDN()) { tmpRDNFields.add(fieldInfo); } } if (dnFieldAnnotation != null) { f.setAccessible(true); if (fieldAnnotation != null) { throw new LDAPPersistException( ERR_OBJECT_HANDLER_CONFLICTING_FIELD_ANNOTATIONS.get( type.getName(), "LDAPField", "LDAPDNField", f.getName())); } if (tmpDNField != null) { throw new LDAPPersistException(ERR_OBJECT_HANDLER_MULTIPLE_DN_FIELDS.get(type.getName())); } final int modifiers = f.getModifiers(); if (Modifier.isFinal(modifiers)) { throw new LDAPPersistException( ERR_OBJECT_HANDLER_DN_FIELD_FINAL.get(f.getName(), type.getName())); } else if (Modifier.isStatic(modifiers)) { throw new LDAPPersistException( ERR_OBJECT_HANDLER_DN_FIELD_STATIC.get(f.getName(), type.getName())); } final Class<?> fieldType = f.getType(); if (fieldType.equals(String.class)) { tmpDNField = f; } else { throw new LDAPPersistException( ERR_OBJECT_HANDLER_INVALID_DN_FIELD_TYPE.get( type.getName(), f.getName(), fieldType.getName())); } } if (entryFieldAnnotation != null) { f.setAccessible(true); if (fieldAnnotation != null) { throw new LDAPPersistException( ERR_OBJECT_HANDLER_CONFLICTING_FIELD_ANNOTATIONS.get( type.getName(), "LDAPField", "LDAPEntryField", f.getName())); } if (tmpEntryField != null) { throw new LDAPPersistException( ERR_OBJECT_HANDLER_MULTIPLE_ENTRY_FIELDS.get(type.getName())); } final int modifiers = f.getModifiers(); if (Modifier.isFinal(modifiers)) { throw new LDAPPersistException( ERR_OBJECT_HANDLER_ENTRY_FIELD_FINAL.get(f.getName(), type.getName())); } else if (Modifier.isStatic(modifiers)) { throw new LDAPPersistException( ERR_OBJECT_HANDLER_ENTRY_FIELD_STATIC.get(f.getName(), type.getName())); } final Class<?> fieldType = f.getType(); if (fieldType.equals(ReadOnlyEntry.class)) { tmpEntryField = f; } else { throw new LDAPPersistException( ERR_OBJECT_HANDLER_INVALID_ENTRY_FIELD_TYPE.get( type.getName(), f.getName(), fieldType.getName())); } } } dnField = tmpDNField; entryField = tmpEntryField; requiredFilterFields = Collections.unmodifiableList(tmpRFilterFields); alwaysAllowedFilterFields = Collections.unmodifiableList(tmpAAFilterFields); conditionallyAllowedFilterFields = Collections.unmodifiableList(tmpCAFilterFields); rdnFields = Collections.unmodifiableList(tmpRDNFields); final LinkedList<GetterInfo> tmpRFilterGetters = new LinkedList<GetterInfo>(); final LinkedList<GetterInfo> tmpAAFilterGetters = new LinkedList<GetterInfo>(); final LinkedList<GetterInfo> tmpCAFilterGetters = new LinkedList<GetterInfo>(); final LinkedList<GetterInfo> tmpRDNGetters = new LinkedList<GetterInfo>(); for (final Method m : type.getDeclaredMethods()) { final LDAPGetter getter = m.getAnnotation(LDAPGetter.class); final LDAPSetter setter = m.getAnnotation(LDAPSetter.class); if (getter != null) { m.setAccessible(true); if (setter != null) { throw new LDAPPersistException( ERR_OBJECT_HANDLER_CONFLICTING_METHOD_ANNOTATIONS.get( type.getName(), "LDAPGetter", "LDAPSetter", m.getName())); } final GetterInfo methodInfo = new GetterInfo(m, type); final String attrName = toLowerCase(methodInfo.getAttributeName()); if (fields.containsKey(attrName) || getters.containsKey(attrName)) { throw new LDAPPersistException( ERR_OBJECT_HANDLER_ATTR_CONFLICT.get(type.getName(), methodInfo.getAttributeName())); } else { getters.put(attrName, methodInfo); } switch (methodInfo.getFilterUsage()) { case REQUIRED: tmpRFilterGetters.add(methodInfo); break; case ALWAYS_ALLOWED: tmpAAFilterGetters.add(methodInfo); break; case CONDITIONALLY_ALLOWED: tmpCAFilterGetters.add(methodInfo); break; case EXCLUDED: default: // No action required. break; } if (methodInfo.includeInRDN()) { tmpRDNGetters.add(methodInfo); } } if (setter != null) { m.setAccessible(true); final SetterInfo methodInfo = new SetterInfo(m, type); final String attrName = toLowerCase(methodInfo.getAttributeName()); if (fields.containsKey(attrName) || setters.containsKey(attrName)) { throw new LDAPPersistException( ERR_OBJECT_HANDLER_ATTR_CONFLICT.get(type.getName(), methodInfo.getAttributeName())); } else { setters.put(attrName, methodInfo); } } } requiredFilterGetters = Collections.unmodifiableList(tmpRFilterGetters); alwaysAllowedFilterGetters = Collections.unmodifiableList(tmpAAFilterGetters); conditionallyAllowedFilterGetters = Collections.unmodifiableList(tmpCAFilterGetters); rdnGetters = Collections.unmodifiableList(tmpRDNGetters); if (rdnFields.isEmpty() && rdnGetters.isEmpty()) { throw new LDAPPersistException(ERR_OBJECT_HANDLER_NO_RDN_DEFINED.get(type.getName())); } fieldMap = Collections.unmodifiableMap(fields); getterMap = Collections.unmodifiableMap(getters); setterMap = Collections.unmodifiableMap(setters); final TreeSet<String> attrSet = new TreeSet<String>(); final TreeSet<String> lazySet = new TreeSet<String>(); if (ldapObject.requestAllAttributes()) { attrSet.add("*"); attrSet.add("+"); } else { for (final FieldInfo i : fields.values()) { if (i.lazilyLoad()) { lazySet.add(i.getAttributeName()); } else { attrSet.add(i.getAttributeName()); } } for (final SetterInfo i : setters.values()) { attrSet.add(i.getAttributeName()); } } attributesToRequest = new String[attrSet.size()]; attrSet.toArray(attributesToRequest); lazilyLoadedAttributes = new String[lazySet.size()]; lazySet.toArray(lazilyLoadedAttributes); }
/** * {@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; }