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()); }
private void generateView( Map<String, DesignDocument.View> views, Method me, Class<?> handledType) { String name = me.getName(); if (!name.startsWith("findBy") && !name.equals("getAll")) { throw new ViewGenerationException( String.format( "The method: %s in %s annotated with GenerateView does not conform to the naming convention of 'findByXxxx'", name, me.getDeclaringClass())); } Class<?> type = resolveReturnType(me); if (type == null) { if (handledType != null) { type = handledType; } else { throw new ViewGenerationException( "Could not resolve return type for method: %s in %s", me.getName(), me.getDeclaringClass()); } } String typeDiscriminator = resolveTypeDiscriminator(type); if (name.equals("getAll")) { if (typeDiscriminator.length() < 1) { throw new ViewGenerationException( String.format( "Cannot generate 'all' view for %s. No type discriminator could be resolved. Try annotate unique field(s) with @TypeDiscriminator", type.getDeclaringClass())); } views.put("all", generateAllView(typeDiscriminator)); return; } String finderName = name.substring(6); String fieldName = resolveFieldName(me, finderName); Method getter = findMethod(type, "get" + fieldName); if (getter == null) { // try pluralis fieldName += "s"; getter = findMethod(type, "get" + fieldName); } if (getter == null) { throw new ViewGenerationException( "Could not generate view for method %s. No get method found for property %s in %s", name, name.substring(6), type); } fieldName = firstCharToLowerCase(fieldName); DesignDocument.View view; if (isIterable(getter.getReturnType())) { view = generateFindByIterableView(fieldName, typeDiscriminator); } else { view = generateFindByView(fieldName, typeDiscriminator); } views.put("by_" + firstCharToLowerCase(finderName), view); }
public void printAll(Class c) { Constructor[] cs = this.getAllConstructorsFromClass(c); System.out.println(" Constructors:"); for (Constructor constructor : cs) { System.out.print(" " + constructor); if (constructor.getDeclaringClass() != c) System.out.println(" (inherited from " + constructor.getDeclaringClass().getName() + ")"); else System.out.println(); } System.out.println(" Methods:"); Method[] ms = this.getAllMethodsFromClass(c); for (Method method : ms) { System.out.print(" " + method); if (method.getDeclaringClass() != c) System.out.println(" (inherited from " + method.getDeclaringClass().getName() + ")"); else System.out.println(); } System.out.println(" Classes:"); Class[] cls = this.getClassesFromClass(c); for (Class class1 : cls) { System.out.println(" " + class1); } System.out.println(" Fields:"); Field[] fs = this.getFieldsFromClass(c); for (Field field : fs) { System.out.print(" " + field); if (field.getDeclaringClass() != c) System.out.println(" (inherited from " + field.getDeclaringClass().getName() + ")"); else System.out.println(); } System.out.println(" Interfaces:"); Class[] is = this.getInterfacesFromClass(c); for (Class class2 : is) { System.out.println(" " + class2); } System.out.println(" Local Methods:"); Method[] mls = this.getLocalMethodsFromClass(c); for (Method method2 : mls) { System.out.print(" " + method2); if (method2.getDeclaringClass() != c) System.out.println(" (inherited from " + method2.getDeclaringClass().getName() + ")"); else System.out.println(); } }
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(); }
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(); }
// // Returns true if this method is allowed to raise SQLFeatureNotSupportedException. // private boolean isExcludable(Method method) throws Exception { Class iface = method.getDeclaringClass(); HashSet<Method> excludableMethods = excludableMap.get(iface); if (excludableMethods == null) { return false; } return excludableMethods.contains(method); }
/* Processing assignments of allocation statements. Left hand side is either a variable or the field of a variable. The right hand side is the allocation site, represented by the allocation instruction. */ public void assignAlloc(Var x, Field f, New a) { Node nodeL = getNode(x, f); nodeL.hasallocs = true; nodeL.istouched = true; setTouched(x); if (IRHelper.isLibrary(method.getDeclaringClass())) nodeL.hasliballocs = true; Node nodeR = allocmap.get(a); assert (nodeR == null) : "Allocation site already entered"; allocmap.put(a, nodeL); }
protected void generateView( Map<String, org.ektorp.support.DesignDocument.View> views, Method me) { DocumentReferences referenceMetaData = me.getAnnotation(DocumentReferences.class); if (referenceMetaData == null) { LOG.warn("No DocumentReferences annotation found in method: ", me.getName()); return; } if (!me.getName().startsWith("get")) { throw new ViewGenerationException( String.format( "The method: %s in %s annotated with DocumentReferences does not conform to the naming convention of 'getXxxx'", me.getName(), me.getDeclaringClass())); } if (Set.class.isAssignableFrom(me.getReturnType())) { generateSetBasedDocRefView(views, me, referenceMetaData); } else { throw new ViewGenerationException( String.format( "The return type of: %s in %s annotated with DocumentReferences is not supported. (Must be assignable from java.util.Set)", me.getName(), me.getDeclaringClass())); } }
protected void _addMemberMethods( Class<?> cls, MethodFilter methodFilter, AnnotatedMethodMap methods, Class<?> mixInCls, AnnotatedMethodMap mixIns) { // first, mixIns, since they have higher priority then class methods if (mixInCls != null) { _addMethodMixIns(methodFilter, methods, mixInCls, mixIns); } if (cls == null) { // just so caller need not check when passing super-class return; } // then methods from the class itself for (Method m : cls.getDeclaredMethods()) { if (!_isIncludableMethod(m, methodFilter)) { continue; } AnnotatedMethod old = methods.find(m); if (old == null) { AnnotatedMethod newM = _constructMethod(m); methods.add(newM); // Ok, but is there a mix-in to connect now? old = mixIns.remove(m); if (old != null) { _addMixOvers(old.getAnnotated(), newM, false); } } else { /* If sub-class already has the method, we only want to augment * annotations with entries that are not masked by sub-class. */ _addMixUnders(m, old); /* 06-Jan-2010, tatu: [JACKSON-450] Except that if method we saw first is * from an interface, and we now find a non-interface definition, we should * use this method, but with combination of annotations. * This helps (or rather, is essential) with JAXB annotations and * may also result in faster method calls (interface calls are slightly * costlier than regular method calls) */ if (old.getDeclaringClass().isInterface() && !m.getDeclaringClass().isInterface()) { methods.add(old.withMethod(m)); } } } }
/** * {@link InvocationHandler} implementation that allows strongly-typed access to the * configuration. * * <p>TODO: it might be a great performance improvement to have APT generate code that does this * during the development time by looking at the interface. */ public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // serve java.lang.Object methods by ourselves Class<?> clazz = method.getDeclaringClass(); if (clazz == Object.class) { try { return method.invoke(this, args); } catch (InvocationTargetException e) { throw e.getTargetException(); } } if (method.getAnnotation(DuckTyped.class) != null) { return invokeDuckMethod(method, proxy, args); } if (method.getAnnotation(ConfigExtensionMethod.class) != null) { ConfigExtensionMethod cem = method.getAnnotation(ConfigExtensionMethod.class); ConfigExtensionHandler handler = (ConfigExtensionHandler) ((cem.value() != null) ? getServiceLocator().getService(ConfigExtensionHandler.class, cem.value()) : getServiceLocator().getService(ConfigExtensionHandler.class)); return invokeConfigExtensionMethod(handler, this, model.getProxyType(), args); } ConfigModel.Property p = model.toProperty(method); if (p == null) throw new IllegalArgumentException("No corresponding property found for method: " + method); if (args == null || args.length == 0) { // getter return getter(p, method.getGenericReturnType()); } else { throw new PropertyVetoException( "Instance of " + getImplementation() + " named '" + getKey() + "' is not locked for writing when invoking method " + method.getName() + " you must use transaction semantics to access it.", null); } }
/** * {@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; }
private JSONArray getClassProperties(Class<?> clazz, int level) throws IntrospectionException { JSONArray arr = new JSONArray(); TypeDiscoverer td = new TypeDiscoverer(); try { for (PropertyDescriptor pd : Introspector.getBeanInfo(clazz).getPropertyDescriptors()) { Method readMethod = pd.getReadMethod(); if (readMethod != null) { if (readMethod.getDeclaringClass() == java.lang.Enum.class) { // skip getDeclaringClass continue; } else if ("class".equals(pd.getName())) { // skip getClass continue; } } else { // yields com.datatorrent.api.Context on JDK6 and // com.datatorrent.api.Context.OperatorContext with JDK7 if ("up".equals(pd.getName()) && com.datatorrent.api.Context.class.isAssignableFrom(pd.getPropertyType())) { continue; } } // LOG.info("name: " + pd.getName() + " type: " + pd.getPropertyType()); Class<?> propertyType = pd.getPropertyType(); if (propertyType != null) { JSONObject propertyObj = new JSONObject(); propertyObj.put("name", pd.getName()); propertyObj.put("canGet", readMethod != null); propertyObj.put("canSet", pd.getWriteMethod() != null); if (readMethod != null) { for (Class<?> c = clazz; c != null; c = c.getSuperclass()) { OperatorClassInfo oci = classInfo.get(c.getName()); if (oci != null) { MethodInfo getMethodInfo = oci.getMethods.get(readMethod.getName()); if (getMethodInfo != null) { addTagsToProperties(getMethodInfo, propertyObj); break; } } } // type can be a type symbol or parameterized type td.setTypeArguments(clazz, readMethod.getGenericReturnType(), propertyObj); } else { if (pd.getWriteMethod() != null) { td.setTypeArguments( clazz, pd.getWriteMethod().getGenericParameterTypes()[0], propertyObj); } } // if (!propertyType.isPrimitive() && !propertyType.isEnum() && !propertyType.isArray() && // !propertyType.getName().startsWith("java.lang") && level < MAX_PROPERTY_LEVELS) { // propertyObj.put("properties", getClassProperties(propertyType, level + 1)); // } arr.put(propertyObj); } } } catch (JSONException ex) { throw new RuntimeException(ex); } return arr; }
private void reportTestAsNotApplicableInCurrentTestRun(Method method) { Class<?> testClass = method.getDeclaringClass(); Description testDescription = Description.createTestDescription(testClass, method.getName()); runNotifier.fireTestAssumptionFailed(new Failure(testDescription, NOT_APPLICABLE)); }
private void printComponentTree( PrintWriter out, String errorId, FacesContext context, UIComponent comp, int depth) { for (int i = 0; i < depth; i++) out.print(' '); boolean isError = false; if (errorId != null && errorId.equals(comp.getClientId(context))) { isError = true; out.print("<span style='color:red'>"); } out.print("<" + comp.getClass().getSimpleName()); if (comp.getId() != null) out.print(" id=\"" + comp.getId() + "\""); for (Method method : comp.getClass().getMethods()) { if (!method.getName().startsWith("get") && !method.getName().startsWith("is")) continue; else if (method.getParameterTypes().length != 0) continue; String name; if (method.getName().startsWith("get")) name = method.getName().substring(3); else if (method.getName().startsWith("is")) name = method.getName().substring(2); else continue; // XXX: getURL name = Character.toLowerCase(name.charAt(0)) + name.substring(1); ValueExpression expr = comp.getValueExpression(name); Class type = method.getReturnType(); if (expr != null) { out.print(" " + name + "=\"" + expr.getExpressionString() + "\""); } else if (method.getDeclaringClass().equals(UIComponent.class) || method.getDeclaringClass().equals(UIComponentBase.class)) { } else if (name.equals("family")) { } else if (String.class.equals(type)) { try { Object value = method.invoke(comp); if (value != null) out.print(" " + name + "=\"" + value + "\""); } catch (Exception e) { } } } int facetCount = comp.getFacetCount(); int childCount = comp.getChildCount(); if (facetCount == 0 && childCount == 0) { out.print("/>"); if (isError) out.print("</span>"); out.println(); return; } out.println(">"); if (isError) out.print("</span>"); for (int i = 0; i < childCount; i++) { printComponentTree(out, errorId, context, comp.getChildren().get(i), depth + 1); } for (int i = 0; i < depth; i++) out.print(' '); if (isError) out.print("<span style='color:red'>"); out.println("</" + comp.getClass().getSimpleName() + ">"); if (isError) out.print("</span>"); }