/** * 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 int compare(Method a, Method b) { if (a == b) return 0; else if (a == null) return -1; else if (b == null) return 1; else if (a.equals(b)) return 0; int cmp = a.getName().compareTo(b.getName()); if (cmp != 0) return cmp; Class[] paramA = a.getParameterTypes(); Class[] paramB = b.getParameterTypes(); if (paramA.length < paramB.length) return -1; else if (paramB.length < paramA.length) return 1; for (int i = 0; i < paramA.length; i++) { cmp = paramA[i].getName().compareTo(paramB[i].getName()); if (cmp != 0) return cmp; } cmp = a.getDeclaringClass().getName().compareTo(b.getDeclaringClass().getName()); if (cmp != 0) return cmp; return a.getReturnType().getName().compareTo(b.getReturnType().getName()); }
/** * Handles a received {@link MBeanServerConnection} invocation * * @param channel The channel the request was received on * @param remoteAddress The remote address of the caller * @param buffer THe buffer received */ public static void handleJMXRequest( Channel channel, SocketAddress remoteAddress, ChannelBuffer buffer) { buffer.resetReaderIndex(); /* The request write */ // 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 Object result = null; MBeanServerConnection server = null; buffer.skipBytes(1); byte domainIndicator = buffer.readByte(); if (domainIndicator == 0) { server = JMXHelper.getHeliosMBeanServer(); } else { byte[] domainBytes = new byte[domainIndicator]; buffer.readBytes(domainBytes); String domain = new String(domainBytes); server = JMXHelper.getLocalMBeanServer(true, domain); if (server == null) { result = new SmallException("Failed to locate MBeanServer for domain [" + domain + "]"); } } int reqId = buffer.readInt(); byte methodId = buffer.readByte(); if (result == null) { int payloadSize = buffer.readInt(); byte[] payload = new byte[payloadSize]; buffer.readBytes(payload); Object[] params = getInput(payload); Method targetMethod = null; try { targetMethod = keyToMethod.get(methodId); if (targetMethod == null) { result = new SmallException( "Failed to handle MBeanServerConnection invocation because method Op Code [" + methodId + "] was not recognized"); } else { if ("addNotificationListener".equals(targetMethod.getName()) && !targetMethod.getParameterTypes()[1].equals(ObjectName.class)) { } else if ("removeNotificationListener".equals(targetMethod.getName()) && !targetMethod.getParameterTypes()[1].equals(ObjectName.class)) { } else { result = targetMethod.invoke(server, params); } } } catch (Throwable t) { SimpleLogger.warn("Failed to invoke [", targetMethod, "]", t); result = new SmallException(t.toString()); } } writeJMXResponse(reqId, methodId, channel, remoteAddress, result); }
private boolean isPropertyMethod(String name, Method method) { if (name.startsWith("get") || name.startsWith("is")) { return method.getParameterTypes().length == 0; } else if (name.startsWith("set")) { return method.getParameterTypes().length == 1; } else { return false; } }
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; }
/** * 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; }
public Object invoke(Object target, Method method, Object[] params) throws Throwable { if (EQUALS_METHOD.equals(method)) { Object param = params[0]; if (param == null || !Proxy.isProxyClass(param.getClass())) { return false; } InvocationHandler other = Proxy.getInvocationHandler(param); return equals(other); } else if (HASHCODE_METHOD.equals(method)) { return hashCode(); } MethodInvocation invocation = new MethodInvocation( method.getName(), method.getReturnType(), method.getGenericReturnType(), method.getParameterTypes(), delegate, params); invoker.invoke(invocation); if (!invocation.found()) { String methodName = method.getDeclaringClass().getSimpleName() + "." + method.getName() + "()"; throw Exceptions.unsupportedMethod(methodName); } return invocation.getResult(); }
private boolean invokeMethod(String line, PrintWriter out, Method method, String[] fields) throws IllegalAccessException, InvocationTargetException { ArrayList<Object> methodArguments = new ArrayList<Object>(); Class<?>[] parameterTypes = method.getParameterTypes(); if (parameterTypes.length == 2 && parameterTypes[0] == PrintWriter.class && parameterTypes[1] == String.class) { // FIXME: there must be a better way to say "I want to parse the line myself." methodArguments.add(out); methodArguments.add(line); } else { int nextField = 1; for (Class<?> parameterType : parameterTypes) { if (parameterType == PrintWriter.class) { methodArguments.add(out); } else if (parameterType == String.class) { methodArguments.add(fields[nextField++]); } // FIXME: support other common types. "int" seems a likely first candidate. } } method.invoke(handler, methodArguments.toArray()); return true; }
public ProxiedMethod(Method method) { this.method = method; this.name = // method instanceof Constructor ? "<init>" : method.getName(); this.owner = method.getDeclaringClass(); StringBuffer jni_sig = new StringBuffer("("), c_sig = new StringBuffer(); retCapitalized = jni_capitalized(method.getReturnType()); String[] sigArg = c_signature(method.getReturnType(), "?"); c_sig.append(retType = sigArg[0]).append(" ").append(name).append("("); int i = 0; for (Class c : method.getParameterTypes()) { jni_sig.append(jni_signature(c)); if (i > 0) c_sig.append(", "); String argName = "arg" + (i + 1); sigArg = c_signature(c, argName); String argType = sigArg[0]; argTypes.add(argType); argNames.add(argName); argValues.add(sigArg[1]); c_sig.append(argType).append(" ").append(argName); i++; } c_sig.append(")"); jni_sig.append(")").append(jni_signature(method.getReturnType())); this.jni_signature = jni_sig.toString(); this.c_signature = c_sig.toString(); }
/** * 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); } } }); }
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; } } }
private void addClass(Class<?> c) { if (classes.add(c)) { if (c.getSuperclass() != null) { addClass(c.getSuperclass()); } for (Class<?> sc : c.getInterfaces()) { addClass(sc); } for (Class<?> dc : c.getDeclaredClasses()) { addClass(dc); } for (Method m : c.getDeclaredMethods()) { addClass(m.getReturnType()); for (Class<?> p : m.getParameterTypes()) { addClass(p); } } if (c != void.class && dimensions(c) < 2) { Class<?> arrayClass = Array.newInstance(c, 0).getClass(); arrayClasses.put(c, arrayClass); addClass(arrayClass); } } }
/** * 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); }
// // Examine a single method to see if it raises SQLFeatureNotSupportedException. // private void vetMethod( Object candidate, Class iface, Method method, HashSet<String> unsupportedList, HashSet<String> notUnderstoodList) throws Exception { try { method.invoke(candidate, getNullArguments(method.getParameterTypes())); // it's ok for the method to succeed } catch (Throwable e) { if (!(e instanceof InvocationTargetException)) { recordUnexpectedError(candidate, iface, method, notUnderstoodList, e); } else { Throwable cause = e.getCause(); if (cause instanceof SQLFeatureNotSupportedException) { boolean isExcludable = isExcludable(method); if (!isExcludable) { StackTraceElement[] stack = cause.getStackTrace(); int i = 0; while (i < stack.length && !stack[i].getMethodName().equals("notImplemented")) { ++i; } while (i < stack.length && stack[i].getMethodName().equals("notImplemented")) { ++i; } if (i == stack.length) { // cause.printStackTrace(); } unsupportedList.add( candidate.getClass().getName() + ": " + method + "@" + (i == stack.length ? "no source" : cause.getStackTrace()[i])); } else { } } else if (cause instanceof SQLException) { // swallow other SQLExceptions, caused by bogus args } else if (cause instanceof NullPointerException) { // swallow other NPEs, caused by bogus args } else if (cause instanceof ArrayIndexOutOfBoundsException) { // swallow these, caused by bogus args } else { recordUnexpectedError(candidate, iface, method, notUnderstoodList, cause); } } } }
/** * Computes the set of emit methods in the Assembler for a given IA32 opcode. * * @param emitters the set of all emit methods * @param opcode the opcode being examined */ private static EmitterSet buildSetForOpcode(Method[] emitters, String opcode) { EmitterSet s = new EmitterSet(); for (int i = 0; i < emitters.length; i++) { Method m = emitters[i]; if (m.getName().startsWith("emit" + opcode + "_") || m.getName().equals("emit" + opcode)) { s.add(new EmitterDescriptor(m.getName(), m.getParameterTypes())); } } return s; }
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; }
/** * Checks if the invocation of the method throws a SQLExceptio as expected. * * @param LOB the Object that implements the Blob interface * @param method the method that needs to be tested to ensure that it throws the correct exception * @return true If the method throws the SQLException required after the free method has been * called on the LOB object */ boolean checkIfMethodThrowsSQLException(Object LOB, Method method) throws IllegalAccessException, InvocationTargetException { try { method.invoke(LOB, getNullValues(method.getParameterTypes())); } catch (InvocationTargetException ite) { Throwable cause = ite.getCause(); if (cause instanceof SQLException) { return ((SQLException) cause).getSQLState().equals("XJ215"); } throw ite; } return false; }
private static String prepareExceptionMessage(Method method, Object[] args) { StringBuffer message = new StringBuffer("Illegal object type for the method '" + method.getName() + "'. \n "); message.append("Expected types: \n"); for (Class<?> type : method.getParameterTypes()) { message.append(type.getName()); } message.append("\n Actual types: \n"); for (Object param : args) { message.append(param.getClass().getName()); } return message.toString(); }
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; }
@SuppressWarnings({"unchecked", "rawtypes"}) public static Object invoke(Object target, Method method, boolean strict, Object... args) { try { Object[] params; Class<?>[] paramTypes = method.getParameterTypes(); if (paramTypes.length == 0) { params = null; } else if (args.length == paramTypes.length) { // map one to one if (strict) { params = args; } else { params = new Object[paramTypes.length]; for (int i = 0; i < paramTypes.length; i++) { Object arg = args[i]; if (arg == null) params[i] = null; else { Converter converter = ConverterManager.getInstance().createConverter(arg.getClass(), paramTypes[i]); params[i] = converter.convert(arg); } } } } else { // map varargs params = new Object[paramTypes.length]; for (int i = 0; i < paramTypes.length - 1; i++) params[i] = (strict ? args[i] : AnyConverter.convert(args[i], paramTypes[i])); Class<?> varargsComponentType = paramTypes[paramTypes.length - 1].getComponentType(); Object varargs = Array.newInstance(varargsComponentType, args.length - paramTypes.length + 1); for (int i = 0; i < args.length - paramTypes.length + 1; i++) { Object param = args[paramTypes.length - 1 + i]; if (strict) param = AnyConverter.convert(param, varargsComponentType); Array.set(varargs, i, param); } params[params.length - 1] = varargs; } return method.invoke(target, params); } catch (IllegalAccessException e) { throw ExceptionMapper.configurationException(e, method); } catch (InvocationTargetException e) { throw ExceptionMapper.configurationException(e, method); } }
/** * 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(");"); } }
void doTest(String name) throws Exception { Method m = tests.get(name); Method m_check = tests.get(name + "_check"); Class[] paramTypes = m.getParameterTypes(); Object[] params = new Object[paramTypes.length]; Class retType = m.getReturnType(); boolean isIntArray = (retType.isPrimitive() && !retType.equals(Void.TYPE)) || (retType.equals(Void.TYPE) && paramTypes[0].getComponentType().isPrimitive()) || (retType.isArray() && retType.getComponentType().isPrimitive()); Args args = m.getAnnotation(Args.class); Object src = null; switch (args.src()) { case SMALL: { if (isIntArray) { src = small_int_src; } else { src = small_a_src; } break; } case LARGE: { if (isIntArray) { src = large_int_src; } else { src = large_a_src; } break; } case ZERO: { if (isIntArray) { src = zero_int_src; } else { src = zero_a_src; } break; } } for (int i = 0; i < 20000; i++) { boolean failure = false; int p = 0; if (params.length > 0) { if (isIntArray) { params[0] = ((int[]) src).clone(); } else { params[0] = ((A[]) src).clone(); } p++; } if (params.length > 1) { switch (args.dst()) { case NEW: { if (isIntArray) { params[1] = new int[((int[]) params[0]).length]; } else { params[1] = new A[((A[]) params[0]).length]; } p++; break; } case SRC: { params[1] = params[0]; p++; break; } case NONE: break; } } for (int j = 0; j < args.extra_args().length; j++) { params[p + j] = args.extra_args()[j]; } Object res = m.invoke(null, params); if (retType.isPrimitive() && !retType.equals(Void.TYPE)) { int s = (int) res; int sum = 0; int[] int_res = (int[]) src; for (int j = 0; j < int_res.length; j++) { sum += int_res[j]; } failure = (s != sum); if (failure) { System.out.println("Test " + name + " failed: result = " + s + " != " + sum); } } else { Object dest = null; if (!retType.equals(Void.TYPE)) { dest = res; } else { dest = params[1]; } if (m_check != null) { failure = (boolean) m_check.invoke(null, new Object[] {src, dest}); } else { if (isIntArray) { int[] int_res = (int[]) src; int[] int_dest = (int[]) dest; for (int j = 0; j < int_res.length; j++) { if (int_res[j] != int_dest[j]) { System.out.println( "Test " + name + " failed for " + j + " src[" + j + "]=" + int_res[j] + ", dest[" + j + "]=" + int_dest[j]); failure = true; } } } else { Object[] object_res = (Object[]) src; Object[] object_dest = (Object[]) dest; for (int j = 0; j < object_res.length; j++) { if (object_res[j] != object_dest[j]) { System.out.println( "Test " + name + " failed for " + j + " src[" + j + "]=" + object_res[j] + ", dest[" + j + "]=" + object_dest[j]); failure = true; } } } } } if (failure) { success = false; break; } } }
/** * Reads an XML element into a bean property by first locating the XML element corresponding to * this property. * * @param ob The bean whose property is being set * @param desc The property that will be set * @param nodes The list of XML items that may contain the property * @throws IOException If there is an error reading the document */ public void readProperty(Object ob, PropertyDescriptor desc, NodeList nodes, NamedNodeMap attrs) throws IOException { int numAttrs = attrs.getLength(); for (int i = 0; i < numAttrs; i++) { // See if the attribute name matches the property name if (namesMatch(desc.getName(), attrs.item(i).getNodeName())) { // Get the method used to set this property Method setter = desc.getWriteMethod(); // If this object has no setter, don't bother writing it if (setter == null) continue; // Get the value of the property Object obValue = getObjectValue(desc, attrs.item(i).getNodeValue()); if (obValue != null) { try { // Set the property value setter.invoke(ob, new Object[] {obValue}); } catch (InvocationTargetException exc) { throw new IOException( "Error setting property " + desc.getName() + ": " + exc.toString()); } catch (IllegalAccessException exc) { throw new IOException( "Error setting property " + desc.getName() + ": " + exc.toString()); } } return; } } int numNodes = nodes.getLength(); Vector arrayBuild = null; for (int i = 0; i < numNodes; i++) { Node node = nodes.item(i); // If this node isn't an element, skip it if (!(node instanceof Element)) continue; Element element = (Element) node; // See if the tag name matches the property name if (namesMatch(desc.getName(), element.getTagName())) { // Get the method used to set this property Method setter = desc.getWriteMethod(); // If this object has no setter, don't bother writing it if (setter == null) continue; // Get the value of the property Object obValue = getObjectValue(desc, element); // 070201 MAW: Modified from change submitted by Steve Poulson if (setter.getParameterTypes()[0].isArray()) { if (arrayBuild == null) { arrayBuild = new Vector(); } arrayBuild.addElement(obValue); // 070201 MAW: Go ahead and read through the rest of the nodes in case // another one matches the array. This has the effect of skipping // over the "return" statement down below continue; } if (obValue != null) { try { // Set the property value setter.invoke(ob, new Object[] {obValue}); } catch (InvocationTargetException exc) { throw new IOException( "Error setting property " + desc.getName() + ": " + exc.toString()); } catch (IllegalAccessException exc) { throw new IOException( "Error setting property " + desc.getName() + ": " + exc.toString()); } } return; } } // If we build a vector of array members, convert the vector into // an array and save it in the property if (arrayBuild != null) { // Get the method used to set this property Method setter = desc.getWriteMethod(); if (setter == null) return; Object[] obValues = (Object[]) Array.newInstance(desc.getPropertyType(), arrayBuild.size()); arrayBuild.copyInto(obValues); try { setter.invoke(ob, new Object[] {obValues}); } catch (InvocationTargetException exc) { throw new IOException("Error setting property " + desc.getName() + ": " + exc.toString()); } catch (IllegalAccessException exc) { throw new IOException("Error setting property " + desc.getName() + ": " + exc.toString()); } return; } }
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 boolean isIntegerIndexer(String name, Method method) { return ("item".equals(name) && method.getParameterTypes().length == 1) || ("setItem".equals(name) && method.getParameterTypes().length == 2); }
/** * 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); } } } } }
MethodSignature(Method method) { this(method.getName(), method.getParameterTypes()); }
/** 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 ""; } }
/** * {@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; }
public String getPublicMethodsForClasses(String classNames[]) { StringBuilder result = new StringBuilder(); String className = null; 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); 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()); Method methods[] = c.getMethods(); Method method = null; result.append("<methods>"); if (methods != null) { for (int j = 0; j < methods.length; j++) { method = methods[j]; if (method != null && !methodsExclude.contains(method.getName())) { result.append("<method>"); result.append( (new StringBuilder("<methodSignature>")) .append(method.toString()) .append("</methodSignature>") .toString()); result.append( (new StringBuilder("<methodName>")) .append(method.getName()) .append("</methodName>") .toString()); result.append( (new StringBuilder("<returnType>")) .append(method.getReturnType().getName()) .append("</returnType>") .toString()); Class paramClasses[] = method.getParameterTypes(); result.append("<params>"); if (paramClasses != null) { for (int l = 0; l < paramClasses.length; l++) if (paramClasses[l] != null) result.append( (new StringBuilder("<param>")) .append(paramClasses[l].getName()) .append("</param>") .toString()); } result.append("</params>"); result.append("</method>"); } } } result.append("</methods>"); } 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(); }