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; }
private String doCommand(Object target, String method, String[] args) { if (target == null) ; // System.err.println("Huh? Target should never be null " + // domain); else { String cname = "_" + method.replaceAll("-", "_"); try { Method m = target.getClass().getMethod(cname, new Class[] {String[].class}); return (String) m.invoke(target, new Object[] {args}); } catch (NoSuchMethodException e) { // Ignore } catch (InvocationTargetException e) { if (e.getCause() instanceof IllegalArgumentException) { domain.error( "%s, for cmd: %s, arguments; %s", e.getCause().getMessage(), method, Arrays.toString(args)); } else { domain.warning("Exception in replace: %s", e.getCause()); e.getCause().printStackTrace(); } } catch (Exception e) { domain.warning("Exception in replace: " + e + " method=" + method); e.printStackTrace(); } } return null; }
static <T> T set(Class<T> interf, Object value) { Properties p = new Properties(); Method ms[] = interf.getMethods(); for (Method m : ms) { p.put(m.getName(), value); } return Configurable.createConfigurable(interf, (Map<Object, Object>) p); }
/** * Try to execute given method on given object. Handles invocation target exceptions. XXX nearly * duplicates tryMethod in JGEngine. * * @return null means method does not exist or returned null/void */ static Object tryMethod(Object o, String name, Object[] args) { try { Method met = JREEngine.getMethod(o.getClass(), name, args); if (met == null) return null; return met.invoke(o, args); } catch (InvocationTargetException ex) { Throwable ex_t = ex.getTargetException(); ex_t.printStackTrace(); return null; } catch (IllegalAccessException ex) { System.err.println("Unexpected exception:"); ex.printStackTrace(); return null; } }
public void loadAndRun(String className) throws Throwable { // System.out.println("Loading " + className + "..."); Class testClass = new VerifyClassLoader().loadClass(className); // System.out.println("Loaded " + className); try { Method main = testClass.getMethod("main", new Class[] {String[].class}); // System.out.println("Running " + className); main.invoke(null, new Object[] {new String[] {}}); // System.out.println("Finished running " + className); } catch (NoSuchMethodException e) { return; } catch (InvocationTargetException e) { throw e.getTargetException(); } }
public static void invokeSetMethodCaseInsensitive(Object obj, String prop, String value) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { String alternateMethodName = null; Class cl = obj.getClass(); String setMeth = "set" + prop; Method[] methodsList = cl.getMethods(); boolean methodFound = false; int i = 0; for (i = 0; i < methodsList.length; ++i) { if (methodsList[i].getName().equalsIgnoreCase(setMeth) == true) { Class[] parameterTypes = methodsList[i].getParameterTypes(); if (parameterTypes.length == 1) { if (parameterTypes[0].getName().equals("java.lang.String")) { methodFound = true; break; } else alternateMethodName = methodsList[i].getName(); } } } if (methodFound == true) { Object[] params = {value}; methodsList[i].invoke(obj, params); return; } if (alternateMethodName != null) { try { // try int method Class[] cldef = {Integer.TYPE}; Method meth = cl.getMethod(alternateMethodName, cldef); Object[] params = {Integer.valueOf(value)}; meth.invoke(obj, params); return; } catch (NoSuchMethodException nsmex) { // try boolean method Class[] cldef = {Boolean.TYPE}; Method meth = cl.getMethod(alternateMethodName, cldef); Object[] params = {Boolean.valueOf(value)}; meth.invoke(obj, params); return; } } else throw new NoSuchMethodException(setMeth); }
public void run() { while (Thread.currentThread() == thread) { try { Socket socket = server.accept(); Client client = new Client(parent, socket); if (clientValidationMethod != null) { try { clientValidationMethod.invoke(parent, new Object[] {this, client}); } catch (Exception e) { // System.err.println("Disabling serverEvent() for port " + port); e.printStackTrace(); } } if (client.active()) { synchronized (clients) { addClient(client); if (serverEventMethod != null) { try { serverEventMethod.invoke(parent, new Object[] {this, client}); } catch (Exception e) { // System.err.println("Disabling serverEvent() for port " + port); e.printStackTrace(); } } } } } catch (SocketException e) { // thrown when server.close() is called and server is waiting on accept System.err.println("Server SocketException: " + e.getMessage()); thread = null; } catch (IOException e) { // errorMessage("run", e); e.printStackTrace(); thread = null; } try { Thread.sleep(8); } catch (InterruptedException ex) { } } }
public static void invokeSetMethod(Object obj, String prop, String value) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { Class cl = obj.getClass(); // change first letter to uppercase String setMeth = "set" + prop.substring(0, 1).toUpperCase() + prop.substring(1); // try string method try { Class[] cldef = {String.class}; Method meth = cl.getMethod(setMeth, cldef); Object[] params = {value}; meth.invoke(obj, params); return; } catch (NoSuchMethodException ex) { try { // try int method Class[] cldef = {Integer.TYPE}; Method meth = cl.getMethod(setMeth, cldef); Object[] params = {Integer.valueOf(value)}; meth.invoke(obj, params); return; } catch (NoSuchMethodException nsmex) { // try boolean method Class[] cldef = {Boolean.TYPE}; Method meth = cl.getMethod(setMeth, cldef); Object[] params = {Boolean.valueOf(value)}; meth.invoke(obj, params); return; } } }
/** Verify and invoke main if present in the specified class. */ public static void invokeApplicationMain(Class mainClass, String[] args) throws InvocationTargetException, IllegalAccessException, ClassNotFoundException { String err = localStrings.getLocalString("utility.no.main", "", new Object[] {mainClass}); // determine the main method using reflection // verify that it is public static void and takes // String[] as the only argument Method mainMethod = null; try { mainMethod = mainClass.getMethod("main", new Class[] {String[].class}); } catch (NoSuchMethodException msme) { _logger.log(Level.SEVERE, "enterprise_util.excep_in_utility", msme); throw new ClassNotFoundException(err); } // check modifiers: public static int modifiers = mainMethod.getModifiers(); if (!Modifier.isPublic(modifiers) || !Modifier.isStatic(modifiers)) { err = localStrings.getLocalString( "utility.main.notpublicorstatic", "The main method is either not public or not static"); _logger.log(Level.SEVERE, "enterprise_util.excep_in_utility_main.notpublicorstatic"); throw new ClassNotFoundException(err); } // check return type and exceptions if (!mainMethod.getReturnType().equals(Void.TYPE)) { err = localStrings.getLocalString( "utility.main.notvoid", "The main method's return type is not void "); _logger.log(Level.SEVERE, "enterprise_util.excep_in_utility_main.notvoid"); throw new ClassNotFoundException(err); } // build args to the main and call it Object params[] = new Object[1]; params[0] = args; mainMethod.invoke(null, params); }
/** * Gets the specified method from a query module. * * @param mod query module object * @param path path of the module * @param name method name * @param arity number of arguments * @param qc query context * @param ii input info * @return method if found, {@code null} otherwise * @throws QueryException query exception */ private static Method getModMethod( final Object mod, final String path, final String name, final long arity, final QueryContext qc, final InputInfo ii) throws QueryException { // find method with identical name and arity Method meth = null; for (final Method m : mod.getClass().getMethods()) { if (m.getName().equals(name) && m.getParameterTypes().length == arity) { if (meth != null) throw JAVAAMBIG_X.get(ii, "Q{" + path + '}' + name + '#' + arity); meth = m; } } if (meth == null) throw FUNCJAVA_X.get(ii, path + ':' + name); // check if user has sufficient permissions to call the function Perm perm = Perm.ADMIN; final QueryModule.Requires req = meth.getAnnotation(QueryModule.Requires.class); if (req != null) perm = Perm.get(req.value().name()); if (!qc.context.user.has(perm)) return null; // Add module locks to QueryContext. final QueryModule.Lock lock = meth.getAnnotation(QueryModule.Lock.class); if (lock != null) { for (final String read : lock.read()) qc.readLocks.add(DBLocking.MODULE_PREFIX + read); for (final String write : lock.write()) qc.writeLocks.add(DBLocking.MODULE_PREFIX + write); } return meth; }
public boolean handleCommand(String line, PrintWriter out) { String[] split = line.split("[\t ]"); String commandName = split[0]; try { Method[] methods = exportedInterface.getMethods(); for (Method method : methods) { if (method.getName().equals(commandName) && method.getReturnType() == void.class) { return invokeMethod(line, out, method, split); } } throw new NoSuchMethodException(); } catch (NoSuchMethodException nsmex) { out.println(fullName + ": didn't understand request \"" + line + "\"."); } catch (Exception ex) { Log.warn(fullName + ": exception thrown while handling command \"" + line + "\".", ex); out.println(fullName + ": request denied \"" + line + "\" (" + ex.toString() + ")."); } finally { out.flush(); out.close(); } return false; }
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; }
/** * Constructor. * * @param r HTTP servlet request */ BXServletRequest(final HttpServletRequest r) { req = r; method = Method.valueOf(r.getMethod()); url = r.getRequestURL().toString(); // MiltonUtils.stripContext(r); REQUEST.set(r); }