@Override public Object call(Context context, List args) throws FunctionCallException { try { String clazzName = (String) (args.get(0)); String methodName = (String) (args.get(1)); LOGGER.info("XEditor extension function calling {} {}", clazzName, methodName); Class[] argTypes = new Class[args.size() - 2]; Object[] params = new Object[args.size() - 2]; for (int i = 0; i < argTypes.length; i++) { argTypes[i] = args.get(i + 2).getClass(); params[i] = args.get(i + 2); } Class clazz = ClassUtils.getClass(clazzName); Method method = MethodUtils.getMatchingAccessibleMethod(clazz, methodName, argTypes); return method.invoke(null, params); } catch (Exception ex) { LOGGER.warn("Exception in call to external java method", ex); return ex.getMessage(); } }
protected Method findLinkInvokeMethod(Class cls, String methodName) { Method exactMethod = MethodUtils.getAccessibleMethod(cls, methodName, new Class[]{Entity.class, String.class}); if (exactMethod != null) { return exactMethod; } // search through all methods Method[] methods = cls.getMethods(); for (Method availableMethod : methods) { if (availableMethod.getName().equals(methodName)) { if (availableMethod.getParameterCount() == 2 && Void.TYPE.equals(availableMethod.getReturnType())) { if (Entity.class.isAssignableFrom(availableMethod.getParameterTypes()[0]) && String.class == availableMethod.getParameterTypes()[1]) { // get accessible version of method return MethodUtils.getAccessibleMethod(availableMethod); } } } } return null; }
protected Method findGeneratorMethod(Class cls, String methodName) { Method exactMethod = MethodUtils.getAccessibleMethod(cls, methodName, Entity.class); if (exactMethod != null) { return exactMethod; } // search through all methods Method[] methods = cls.getMethods(); for (Method availableMethod : methods) { if (availableMethod.getName().equals(methodName)) { if (availableMethod.getParameterCount() == 1 && Component.class.isAssignableFrom(availableMethod.getReturnType())) { if (Entity.class.isAssignableFrom(availableMethod.getParameterTypes()[0])) { // get accessible version of method return MethodUtils.getAccessibleMethod(availableMethod); } } } } return null; }
protected void callNotificationMethod(T[] recipients, String methodName, Object... args) throws ServiceReflectionCallException { Class<?>[] paramTypes = new Class<?>[args == null ? 0 : args.length]; if (args != null) { for (int i = 0; i < paramTypes.length; ++i) { paramTypes[i] = args[i].getClass(); } } Method method; try { method = MethodUtils.getMatchingAccessibleMethod(this.getClass(), methodName, paramTypes); } catch (SecurityException e) { e.printStackTrace(); throw new ServiceReflectionCallException(e); } if (!this.remoteMethods.contains(method)) { throw new ServiceReflectionCallException("No such method"); } this.sender.sendNotification(recipients, new RemoteCallRequest(getId(), methodName, args)); }
@VisibleForTesting protected static void inVokeDetermineSchemaOrThrowExceptionMethod(Properties props, Configuration conf) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { String methodName = "determineSchemaOrThrowException"; Method method = MethodUtils.getAccessibleMethod(AvroSerdeUtils.class, methodName, Properties.class); boolean withConf = false; if (method == null) { method = MethodUtils .getAccessibleMethod(AvroSerdeUtils.class, methodName, new Class[]{Configuration.class, Properties.class}); withConf = true; } Preconditions.checkNotNull(method, "Cannot find matching " + methodName); if (!withConf) { MethodUtils.invokeStaticMethod(AvroSerdeUtils.class, methodName, props); } else { MethodUtils.invokeStaticMethod(AvroSerdeUtils.class, methodName, new Object[]{conf, props}); } }
private Method findMethod(Class<?> argType) { try { Class<?> clazz = ClassUtils.getClass(className); Class<?>[] argTypes = { argType }; return MethodUtils.getMatchingAccessibleMethod(clazz, methodName, argTypes); } catch (ClassNotFoundException ex) { throw new MCRConfigurationException("class configured for external validation not found: " + className); } }
@Override public void run() { Object beanInstance = AppBeans.get(bean); try { Method methodWithParams = MethodUtils.getAccessibleMethod(beanInstance.getClass(), beanMethod, Map.class); if (methodWithParams != null) { methodWithParams.invoke(beanInstance, params); return; } MethodUtils.invokeMethod(beanInstance, beanMethod, null); } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { throw new RuntimeException(e); } }
protected Object getComposition(FieldGroup.FieldConfig fc) { Method getCompositionMethod = MethodUtils.getAccessibleMethod(fc.getClass(), "getComposition", new Class[]{}); Object composition; try { composition = getCompositionMethod.invoke(fc); } catch (IllegalAccessException | InvocationTargetException e) { throw new RuntimeException("Invoke error", e); } return composition; }
private boolean startupErrorsPresent(BundleContext bundleContext) { // different classloaders, operating on objects required try { Object statusManager = ServiceLookup.getService(bundleContext, PlatformStatusManager.class); Object currentStatus = MethodUtils.invokeExactMethod(statusManager, "getCurrentStatus", new Object[0]); return (boolean) MethodUtils.invokeExactMethod(currentStatus, "errorsOccurred", new Object[0]); } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { throw new StatusRetrievalException("Unable to retrieve status from manager", e); } }
/** * Returns the quartz scheduler. A bit of hacky way of providing this to test code. Since * PAX doesn't have a dependency on quartz or tbe motech-scheduler, the scheduler is returned as an object * and should be casted by the caller. This method will retrieve the Spring context for scheduler and get * the scheduler by reflection from the scheduler factory bean. * @param bundleContext the bundle context that will be used for retrieving the scheduler * @return the quartz scheduler from the motech-scheduler module, as a java.lang.Object */ protected Object getQuartzScheduler(BundleContext bundleContext) { Object motechSchedulerFactoryBean = getBeanFromBundleContext(bundleContext, "org.motechproject.motech-scheduler", "motechSchedulerFactoryBean"); try { return MethodUtils.invokeMethod(motechSchedulerFactoryBean, "getQuartzScheduler", new Object[0]); } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { throw new IllegalStateException("Unable to retrieve the quartz scheduler", e); } }
private static boolean hasCustomToString(Object value) { Method toStringMethod = MethodUtils.getAccessibleMethod(value.getClass(), "toString", new Class[0]); if (toStringMethod == null ) { LOGGER.error("Unable to retrieve toString() method for {}", value); return false; } else { return !StringUtils.equals(Object.class.getName(), toStringMethod.getDeclaringClass().getName()); } }
private static void setFieldOnTarget(Object target, String property, List value) { try { if (property.startsWith("$")) { String methodName = property.substring(1); Class[] parameterTypes = new Class[null == value ? 0 : value.size()]; Object[] args = null != value ? value.toArray(new Object[value.size()]) : new Object[0]; for (int i = 0; i < args.length; ++i) { Object item = args[i]; parameterTypes[i] = item instanceof List ? List.class : item.getClass(); } MethodUtils.invokeMethod(target, methodName, args, parameterTypes); } else { PropertyDescriptor descriptor = PropertyUtil.getPropertyDescriptor(target, property); if (descriptor == null) { throw new IllegalStateException("Property [" + property + "] not available on class: " + target.getClass().getName()); } else { PropertyUtil.safeSetProperty(target, property, value.get(0)); } } } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { throw new IllegalArgumentException(e); } }
public long executeCount(Map<String, ?> lookupMap) { List<Object> args = getLookupArgs(lookupMap); List<Class> argTypes = buildArgTypes(); String countMethodName = LookupName.lookupCountMethod(lookup.getMethodName()); try { return (long) MethodUtils.invokeMethod(dataService, countMethodName, args.toArray(new Object[args.size()]), argTypes.toArray(new Class[argTypes.size()])); } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { throw new LookupExecutorException("Unable to execute count lookup " + lookup.getLookupName() + ".", e, null); } }
/** * Attempts to parse given String to an instance of a given class. The class may also * have a generic type. It will throw {@link java.lang.IllegalStateException} in case this * method was not able to parse the value. * * @param str String to parse * @param toClass a class to turn value into * @param generic generic class * @return parsed value, an instance of the given class */ public static Object parseString(String str, Class<?> toClass, Class<?> generic) { if (isBlank(str, toClass)) { return (String.class.isAssignableFrom(toClass)) ? "" : null; } if (isDateOrPeriod(toClass)) { return parseDateOrPeriod(toClass, str); } try { if (toClass.isEnum()) { Class<? extends Enum> enumClass = (Class<? extends Enum>) toClass; return Enum.valueOf(enumClass, str); } if (Collection.class.isAssignableFrom(toClass)) { return parseStringToCollection(str, toClass, generic); } else if (Map.class.isAssignableFrom(toClass)) { return parseStringToMap(str); } else if (Locale.class.isAssignableFrom(toClass)) { return LocaleUtils.toLocale(str); } else if (Byte[].class.isAssignableFrom(toClass)) { return ArrayUtils.toObject(str.getBytes()); } else { return MethodUtils.invokeStaticMethod(toClass, "valueOf", str); } } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { throw new IllegalStateException("Unable to parse value " + str + " to " + toClass, e); } }
private static Object parsePrimitive(Object val, Class toClass) { try { return MethodUtils.invokeStaticMethod(toClass, "valueOf", val); } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { throw unableToParseException(val, toClass, e); } }
private void setProperty(Object instance, FieldRecord fieldRecord, MotechDataService service, Long deleteValueFieldId, boolean retainId) throws NoSuchMethodException, ClassNotFoundException, NoSuchFieldException, IllegalAccessException { String fieldName = fieldRecord.getName(); TypeDto type = getType(fieldRecord); String methodName = "set" + StringUtils.capitalize(fieldName); ComboboxHolder holder = type.isCombobox() ? new ComboboxHolder(instance, fieldRecord) : null; String methodParameterType = getMethodParameterType(type, holder); ClassLoader classLoader = instance.getClass().getClassLoader(); Class<?> parameterType; Object parsedValue; if (Byte[].class.getName().equals(methodParameterType) || byte[].class.getName().equals(methodParameterType)) { parameterType = getCorrectByteArrayType(methodParameterType); parsedValue = parseBlobValue(fieldRecord, service, fieldName, deleteValueFieldId, instance); } else { parameterType = classLoader.loadClass(methodParameterType); parsedValue = parseValue(holder, methodParameterType, fieldRecord, classLoader); } MetadataDto versionMetadata = fieldRecord.getMetadata(Constants.MetadataKeys.VERSION_FIELD); validateNonEditableField(fieldRecord, instance, parsedValue, versionMetadata); Method method = MethodUtils.getAccessibleMethod(instance.getClass(), methodName, parameterType); if (method == null && TypeHelper.hasPrimitive(parameterType)) { method = MethodUtils.getAccessibleMethod(instance.getClass(), methodName, TypeHelper.getPrimitive(parameterType)); // if the setter is for a primitive, but we have a null, we leave the default if (method != null && parsedValue == null) { return; } } invokeMethod(method, instance, parsedValue, methodName, fieldName); setTransactionVersion(instance, fieldRecord, retainId, versionMetadata); }
private void setRelationProperty(Object instance, FieldRecord fieldRecord) throws NoSuchMethodException, ClassNotFoundException, NoSuchFieldException, IllegalAccessException, InstantiationException, CannotCompileException { String fieldName = fieldRecord.getName(); String methodName = MemberUtil.getSetterName(fieldName); Class<?> clazz = instance.getClass().getClassLoader().loadClass(instance.getClass().getName()); Field field = FieldUtils.getField(clazz, fieldName, true); Class<?> parameterType = field.getType(); Object value = null; MotechDataService serviceForRelatedClass = null; TypeDto type = getType(fieldRecord); if (StringUtils.isNotEmpty(ObjectUtils.toString(fieldRecord.getValue()))) { Class<?> argumentType = null; if (type.equals(TypeDto.ONE_TO_MANY_RELATIONSHIP) || type.equals(TypeDto.MANY_TO_MANY_RELATIONSHIP)) { argumentType = (Class<?>) ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0]; } else if (type.equals(TypeDto.MANY_TO_ONE_RELATIONSHIP) || type.equals(TypeDto.ONE_TO_ONE_RELATIONSHIP)) { argumentType = parameterType; } serviceForRelatedClass = DataServiceHelper.getDataService(bundleContext, argumentType.getName()); Object related = PropertyUtil.safeGetProperty(instance, fieldName); value = buildRelatedInstances(serviceForRelatedClass, parameterType, argumentType, fieldRecord.getValue(), related); } Method method = MethodUtils.getAccessibleMethod(instance.getClass(), methodName, parameterType); invokeMethod(method, instance, value, methodName, fieldName); }
public static Method getMatchingAccessibleMethod(Class<?> cls, String methodName, Class<?>[] parameterTypes, Collection<Method> callableMethods) { try { return cls.getMethod(methodName, parameterTypes); } catch (NoSuchMethodException e) { /* SWALLOW */ } // search through all methods Method bestMatch = null; for (Method method : callableMethods) { if (method.getName().equals(methodName)) { // compare parameters if (ClassUtils.isAssignable(parameterTypes, method .getParameterTypes(), true)) { // get accessible version of method Method accessibleMethod = MethodUtils.getAccessibleMethod(method); if (accessibleMethod != null) { if (bestMatch == null || compareParameterTypes( accessibleMethod.getParameterTypes(), bestMatch.getParameterTypes(), parameterTypes) < 0) { bestMatch = accessibleMethod; } } } } } return bestMatch; }
protected JavaDelegate javaDelegateFromExistingBean(final Object o) throws BeansException { // first create a proxy that implements JavaDelegate // then setup logic to dispatch to a cached metadata map containing the methods on the class as well as // the particular runtime arguments those methods require, including access to things like @ProcessVariable annotations if (o instanceof JavaDelegate) { return (JavaDelegate) o; } final Method javaDelegateExecutionMethod = MethodUtils.getAccessibleMethod(JavaDelegate.class, "execute", DelegateExecution.class); ProxyFactory proxyFactory = new ProxyFactory(o); proxyFactory.setProxyTargetClass(true); proxyFactory.addInterface(JavaDelegate.class); proxyFactory.addAdvice(new MethodInterceptor() { @Override public Object invoke(MethodInvocation invocation) throws Throwable { // if its one type of method handle it our selves // by looking up the appropriate handler method and invoking it dynamically Method method = invocation.getMethod(); // either its a request we can handle if (method.equals(javaDelegateExecutionMethod)) { DelegateExecution delegateExecution = (DelegateExecution) invocation.getArguments()[0]; delegateTo(o, delegateExecution); return null; } // otherwise pass thru return invocation.proceed(); } }); return (JavaDelegate) proxyFactory.getProxy(); }
/** * Bukkit requires a static getHandlerList() method on all event classes, see {@link Event}. * This test checks that such a method is present, and that it is <i>absent</i> if the class * is not instantiable (abstract class). */ @Test public void shouldHaveStaticEventHandlerMethod() { for (Class<?> clazz : classes) { Method handlerListMethod = MethodUtils.getAccessibleMethod(clazz, "getHandlerList", new Class<?>[]{}); if (canBeInstantiated(clazz)) { assertThat("Class " + clazz.getSimpleName() + " has static method getHandlerList()", handlerListMethod != null && Modifier.isStatic(handlerListMethod.getModifiers()), equalTo(true)); } else { assertThat("Non-instantiable class " + clazz.getSimpleName() + " does not have static getHandlerList()", handlerListMethod, nullValue()); } } }
/** * Creates a new {@link Batch.Call} instance that invokes a method * with the given parameters and returns the result. * * <p> * Note that currently the method is naively looked up using the method name * and class types of the passed arguments, which means that * <em>none of the arguments can be <code>null</code></em>. * For more flexibility, see * {@link Batch#forMethod(java.lang.reflect.Method, Object...)}. * </p> * * @param protocol the protocol class being called * @param method the method name * @param args zero or more arguments to be passed to the method * (individual args cannot be <code>null</code>!) * @param <T> the class type of the protocol implementation being invoked * @param <R> the return type for the method call * @return a {@code Callable} instance that will invoke the given method * and return the results * @throws NoSuchMethodException if the method named, with the given argument * types, cannot be found in the protocol class * @see Batch#forMethod(java.lang.reflect.Method, Object...) * @see org.apache.hadoop.hbase.client.HTable#coprocessorExec(Class, byte[], byte[], org.apache.hadoop.hbase.client.coprocessor.Batch.Call, org.apache.hadoop.hbase.client.coprocessor.Batch.Callback) */ public static <T extends CoprocessorProtocol,R> Call<T,R> forMethod( final Class<T> protocol, final String method, final Object... args) throws NoSuchMethodException { Class[] types = new Class[args.length]; for (int i=0; i<args.length; i++) { if (args[i] == null) { throw new NullPointerException("Method argument cannot be null"); } types[i] = args[i].getClass(); } Method m = MethodUtils.getMatchingAccessibleMethod(protocol, method, types); if (m == null) { throw new NoSuchMethodException("No matching method found for '" + method + "'"); } m.setAccessible(true); return forMethod(m, args); }
public static long extractLongFieldValue(TaskMetrics m, String fieldName) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { return (Long) MethodUtils.invokeMethod(m, fieldName, null); }
/** * Returns the getter value from the object instance, nested properties are * possible. If the propertyName is for example temperature.current, the * methods getTemperature().getCurrent() are called. */ public static Object getPropertyValue(Object instance, String property) throws Exception { Object object = getNestedObject(instance, property); String getMethod = toGetterString(PropertyResolver.last(property)); return MethodUtils.invokeMethod(object, getMethod, null); }