List of usage examples for java.lang Class getMethods
@CallerSensitive public Method[] getMethods() throws SecurityException
From source file:com.grepcurl.random.ObjectGenerator.java
protected <T> T generate(Class<T> klass, SetterOverrides setterOverrides, Deque<Object> objectStack, Object... constructorArgs) { Validate.notNull(klass);/*w ww .j av a 2s . c om*/ Validate.notNull(constructorArgs); if (verbose) { log(String.format("generating object of type: %s, with args: %s, with overrides: %s", klass, Arrays.toString(constructorArgs), setterOverrides)); } try { Class[] constructorTypes = _toClasses(constructorArgs); T t; if (klass.isEnum()) { int randomOrdinal = randomInt(0, klass.getEnumConstants().length - 1); t = klass.getEnumConstants()[randomOrdinal]; } else { t = klass.getConstructor(constructorTypes).newInstance(constructorArgs); } objectStack.push(t); Method[] methods = klass.getMethods(); for (Method method : methods) { _processMethod(method, setterOverrides, t, objectStack); } objectStack.pop(); return t; } catch (Exception e) { e.printStackTrace(); throw new FailedRandomObjectGenerationException(e); } }
From source file:net.lightbody.bmp.proxy.jetty.util.jmx.ModelMBeanImpl.java
/** Define an attribute on the managed object. * The meta data is defined by looking for standard getter and * setter methods. Descriptions are obtained with a call to * findDescription with the attribute name. * @param name The name of the attribute. Normal java bean * capitlization is enforced on this name. * @param writable If false, do not look for a setter. * @param onMBean ./* w w w . ja va 2s . c o m*/ */ public synchronized void defineAttribute(String name, boolean writable, boolean onMBean) { _dirty = true; String uName = name.substring(0, 1).toUpperCase() + name.substring(1); name = java.beans.Introspector.decapitalize(name); Class oClass = onMBean ? this.getClass() : _object.getClass(); Class type = null; Method getter = null; Method setter = null; Method[] methods = oClass.getMethods(); for (int m = 0; m < methods.length; m++) { if ((methods[m].getModifiers() & Modifier.PUBLIC) == 0) continue; // Look for a getter if (methods[m].getName().equals("get" + uName) && methods[m].getParameterTypes().length == 0) { if (getter != null) throw new IllegalArgumentException("Multiple getters for attr " + name); getter = methods[m]; if (type != null && !type.equals(methods[m].getReturnType())) throw new IllegalArgumentException("Type conflict for attr " + name); type = methods[m].getReturnType(); } // Look for an is getter if (methods[m].getName().equals("is" + uName) && methods[m].getParameterTypes().length == 0) { if (getter != null) throw new IllegalArgumentException("Multiple getters for attr " + name); getter = methods[m]; if (type != null && !type.equals(methods[m].getReturnType())) throw new IllegalArgumentException("Type conflict for attr " + name); type = methods[m].getReturnType(); } // look for a setter if (writable && methods[m].getName().equals("set" + uName) && methods[m].getParameterTypes().length == 1) { if (setter != null) throw new IllegalArgumentException("Multiple setters for attr " + name); setter = methods[m]; if (type != null && !type.equals(methods[m].getParameterTypes()[0])) throw new IllegalArgumentException("Type conflict for attr " + name); type = methods[m].getParameterTypes()[0]; } } if (getter == null && setter == null) throw new IllegalArgumentException("No getter or setters found for " + name); try { // Remember the methods _getter.put(name, getter); _setter.put(name, setter); // create and add the info _attributes.add(new ModelMBeanAttributeInfo(name, findDescription(name), getter, setter)); } catch (Exception e) { log.warn(LogSupport.EXCEPTION, e); throw new IllegalArgumentException(e.toString()); } }
From source file:edu.utah.further.core.cxf.UtilServiceRestImpl.java
/** * Return the list of all known RESTful services' meta data objects. * * @return a composite MD object containing a list of service meta data objects * @see edu.utah.further.core.metadata.service.UtilServiceRest#getAllSoapServiceMd() *///from w w w. j a v a 2s. c o m @Override public MetaData getAllSoapServiceMd() { final WsType webServiceType = WsType.SOAP; if (soapServiceMd == null) { soapServiceMd = new MetaData(); // Build class meta data elements for (final Class<?> serviceClass : getSoapClasses()) { // Process only interfaces, not implementations if (serviceClass.getAnnotation(Implementation.class) != null) { continue; } final WsElementMd classMd = new WsClassMdBuilder(webServiceType, null, serviceClass) .setType(serviceClass.getName()).build(); if (classMd == null) { continue; } soapServiceMd.addChild(classMd); // Build method meta data elements for (final Method method : serviceClass.getMethods()) { final WsElementMd methodMd = new WsMethodMdBuilder(webServiceType, classMd, method) .setDocumentation(method.getAnnotation(Documentation.class)).build(); if (methodMd == null) { continue; } classMd.addChild(methodMd); } } } return soapServiceMd; }
From source file:au.com.onegeek.lambda.core.Lambda.java
public void run() throws UnableToParseTestsException, UnableToParseDataException, ProviderNotFoundException { // Read config logger.debug("Checking context..."); logger.debug(context == null || (context.getConfig() == null) ? "Context is null" : "context is not null"); // Import General Configuration // Import Plugins: Parsers, Reporting Engines, Connectors // - This should enable filtering on input files etc. logger.info("Running Lambda"); // Set paths to reporting // Startup Selenium etc. // Create the browser driver try {/*from ww w . j ava 2 s .c o m*/ logger.debug("Creating " + browser + " Driver."); this.driver = BrowserFactory.getDriver(this.browser); driver.get(this.hostname); } catch (Exception e) { e.printStackTrace(); logger.debug("Could not create driver for browser '" + browser + "' because of: " + e.getMessage() + "\n Exiting now..."); System.exit(1); } // Start the Selenium Server try { this.selenium = new WebDriverBackedSeleniumProvider(this.driver, this.hostname); } catch (Exception e) { e.printStackTrace(); logger.debug("Could not start selenium or the server because: " + e.getMessage()); } // Import Plugins (Including the Selenium Plugin) this.importPlugins(); // Parse the tests try { // Parse the data map this.importData(); this.importTests(); } catch (Exception e) { this.shutdown(); throw new ProviderNotFoundException(e.getMessage()); } logger.info("Running non Testng Tests"); for (Class<Test> clazz : tests) { Test test = null; try { test = clazz.newInstance(); } catch (InstantiationException e) { logger.info("Could not instantiate the Test class: " + e.getMessage()); // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { logger.info("Could not instantiate the Test class: " + e.getMessage()); // TODO Auto-generated catch block e.printStackTrace(); } for (Method m : clazz.getMethods()) { org.testng.annotations.Test testAnnotation = m.getAnnotation(org.testng.annotations.Test.class); if (testAnnotation != null) { logger.info("Runing test with name: " + m.getName()); // Crap - how do we do variables? TestNG has @DataProviders, can we leverage this? String dataProviderMethodName = testAnnotation.dataProvider(); if (dataProviderMethodName != null) { Method dataProvidermethod = null; try { dataProvidermethod = clazz.getDeclaredMethod(dataProviderMethodName); Object[][] data = (Object[][]) dataProvidermethod.invoke(test); for (Object[] array : data) { m.invoke(test, array); } } catch (SecurityException e) { logger.info("Could not instantiate the DataProvider method SE: " + e.getMessage()); // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchMethodException e) { logger.info("Could not instantiate the DataProvider method NSME: " + e.getMessage()); // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalArgumentException e) { logger.info("Could not instantiate the Test class IAE: " + e.getMessage()); // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { logger.info("Could not instantiate the Test class IAE: " + e.getMessage()); // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { logger.info("Could not instantiate the Test class ITE: " + e.getMessage()); // TODO Auto-generated catch block e.printStackTrace(); } } } } } // Create TestNG objects /* logger.info("Starting TestNG Instance"); this.testng = new TestNG(); testng.setVerbose(10); TestListenerAdapter tla = new TestListenerAdapter(); testng.setTestClasses(this.tests); testng.addListener(tla); // Run the TestNG suite logger.info("Running Tests"); testng.run(); */ this.shutdown(); // Timer has already been stopped issue.. Consider running this in own // Thread? // Produce Reports // }
From source file:com.weibo.api.motan.filter.ServiceMockFilter.java
@Override public Response filter(Caller<?> caller, Request request) { // Do nothing when mock is empty. String mockServiceName = caller.getUrl().getParameter(URLParamType.mock.getName()); if (StringUtils.isEmpty(mockServiceName) || "false".equals(mockServiceName)) { return caller.call(request); }//from w ww . j a v a2 s .com MockInfo info = getServiceStat(caller.getUrl()); DefaultResponse response = new DefaultResponse(); if (mockServiceName.startsWith(RETURN_PREFIX)) { String value = mockServiceName.substring(RETURN_PREFIX.length()); try { info.callNum.addAndGet(1); long sleepTime = caclSleepTime(info); Thread.sleep(sleepTime); response.setValue(parseMockValue(value)); } catch (RuntimeException e) { if (e.getCause() != null) { response.setException(new MotanBizException("mock service call process error", e.getCause())); } else { response.setException(new MotanBizException("mock service call process error", e)); } } catch (Exception e) { throw new IllegalStateException( "Illegal mock json value in <motan:service ... mock=\"" + mockServiceName + "\" />"); } } else { try { Class<?> mockClass = isDefault(mockServiceName) ? ReflectUtil.forName(caller.getInterface().getName() + "Mock") : ReflectUtil.forName(mockServiceName); if (!caller.getInterface().isAssignableFrom(mockClass)) { throw new MotanFrameworkException("The mock implemention class " + mockClass.getName() + " not implement interface " + caller.getInterface().getName()); } try { mockClass.getConstructor(); } catch (NoSuchMethodException e) { throw new IllegalStateException("No such empty constructor \"public " + mockClass.getSimpleName() + "()\" in mock implemention class " + mockClass.getName()); } String methodDesc = ReflectUtil.getMethodDesc(request.getMethodName(), request.getParamtersDesc()); Method[] methods = mockClass.getMethods(); boolean invoke = false; for (Method method : methods) { if (methodDesc.equals(ReflectUtil.getMethodDesc(method))) { Object value = invoke(mockClass.newInstance(), method, request.getArguments(), info); response.setValue(value); invoke = true; break; } } if (!invoke) { throw new MotanFrameworkException("Mock method is not found." + methodDesc); } } catch (ClassNotFoundException e) { throw new MotanFrameworkException("Mock service is not found." + (isDefault(mockServiceName) ? caller.getInterface().getName() + "Mock" : mockServiceName)); } catch (Exception e) { if (e.getCause() != null) { response.setException(new MotanBizException("mock service call process error", e.getCause())); } else { response.setException(new MotanBizException("mock service call process error", e)); } } } return response; }
From source file:edu.utah.further.core.cxf.UtilServiceRestImpl.java
/** * Return the list of all known RESTful services' meta data objects. * * @return a composite MD object containing a list of service meta data objects * @see edu.utah.further.core.metadata.service.UtilServiceRest#getAllRestServiceMd() *//*from ww w. j av a2 s .c o m*/ @Override public MetaData getAllRestServiceMd() { final WsType webServiceType = WsType.REST; if (restServiceMd == null) { restServiceMd = new MetaData(); // Build class meta data elements for (final Class<?> serviceClass : getRestClasses()) { // Process only interfaces, not implementations if (serviceClass.getAnnotation(Implementation.class) != null) { continue; } final WsElementMd classMd = new WsClassMdBuilder(webServiceType, null, serviceClass) .setType(serviceClass.getName()).build(); if (classMd == null) { continue; } restServiceMd.addChild(classMd); // Build method meta data elements for (final Method method : serviceClass.getMethods()) { final WsElementMd methodMd = new WsMethodMdBuilder(webServiceType, classMd, method) .setHttpMethod(method.getAnnotations()) .setDocumentation(method.getAnnotation(Documentation.class)) .setPath(method.getAnnotation(Path.class)) .setExamplePath(method.getAnnotation(ExamplePath.class)).build(); if (methodMd == null) { continue; } classMd.addChild(methodMd); // Build field meta data elements final Class<?>[] parameterTypes = method.getParameterTypes(); final Annotation[][] parameterAnnotations = method.getParameterAnnotations(); for (int i = 0; i < parameterTypes.length; i++) { final WsElementMd parameterMd = new WsParameterMdBuilder(webServiceType, methodMd) .setParameterAnnotations(parameterAnnotations[i]) .setType(parameterTypes[i].getSimpleName()).build(); if (parameterMd == null) { continue; } methodMd.addChild(parameterMd); } } } } return restServiceMd; }
From source file:net.sf.qooxdoo.rpc.RemoteCallUtils.java
/** * Invokes a method compatible to the specified parameters. * * @param instance the object on which to invoke the * method (must not be * <code>null</code>). * @param methodName the name of the method to invoke (must * not be <code>null</code>). * @param parameters the method parameters (as JSON * objects - must not be * <code>null</code>). * * @exception Exception thrown if the method cannot be found * or if invoking it fails. If the method * cannot be found, a * <code>NoSuchMethodException</code> is * thrown. *//* ww w . j a v a 2 s .c o m*/ protected Object callCompatibleMethod(Object instance, String methodName, JSONArray parameters) throws Exception { Class clazz = instance.getClass(); StringBuffer cacheKeyBuffer = new StringBuffer(clazz.getName()); cacheKeyBuffer.append('-'); cacheKeyBuffer.append(methodName); int parameterCount = parameters.length(); Object parameter; int i; for (i = 0; i < parameterCount; ++i) { parameter = parameters.get(i); cacheKeyBuffer.append('-'); cacheKeyBuffer.append(parameter == null ? null : parameter.getClass().getName()); } String cacheKey = cacheKeyBuffer.toString(); Method method = (Method) _methodCache.get(cacheKey); Class[] methodParameterTypes; Object[] convertedParameters = new Object[parameterCount]; String lastError = null; if (method == null) { Method[] methods = clazz.getMethods(); Method candidate; int methodCount = methods.length; for (i = 0; i < methodCount; ++i) { candidate = methods[i]; if (!candidate.getName().equals(methodName)) { continue; } if (!throwsExpectedException(candidate)) { continue; } methodParameterTypes = candidate.getParameterTypes(); if (methodParameterTypes.length != parameterCount) { continue; } try { convertParameters(parameters, convertedParameters, methodParameterTypes); } catch (Exception e) { lastError = e.getMessage(); continue; } method = candidate; break; } if (method == null) { if (lastError == null) { throw new NoSuchMethodException(methodName); } throw new NoSuchMethodException(methodName + " - " + lastError); } _methodCache.put(cacheKey, method); return method.invoke(instance, convertedParameters); } try { convertParameters(parameters, convertedParameters, method.getParameterTypes()); } catch (Exception e) { // maybe it works with another method - not very fast from a // performance standpoint, but supports a variety of methods _methodCache.remove(cacheKey); return callCompatibleMethod(instance, methodName, parameters); } return method.invoke(instance, convertedParameters); }
From source file:com.datatorrent.lib.util.PojoUtils.java
private static String getSingleFieldSetterExpression(final Class<?> pojoClass, final String fieldExpression, final Class<?> exprClass) { JavaStatement code = new JavaStatement( pojoClass.getName().length() + fieldExpression.length() + exprClass.getName().length() + 32); /* Construct ((<pojo class name>)pojo). */ code.appendCastToTypeExpr(pojoClass, OBJECT).append("."); try {//ww w . j a v a2s . c om final Field field = pojoClass.getField(fieldExpression); if (ClassUtils.isAssignable(exprClass, field.getType())) { /* there is public field on the class, use direct assignment. */ /* append <field name> = (<field type>)val; */ return code.append(field.getName()).append(" = ").appendCastToTypeExpr(exprClass, VAL) .getStatement(); } logger.debug("{} can not be assigned to {}. Proceeding to locate a setter method.", exprClass, field); } catch (NoSuchFieldException ex) { logger.debug("{} does not have field {}. Proceeding to locate a setter method.", pojoClass, fieldExpression); } catch (SecurityException ex) { logger.debug("{} does not have field {}. Proceeding to locate a setter method.", pojoClass, fieldExpression); } final String setMethodName = SET + upperCaseWord(fieldExpression); Method bestMatchMethod = null; List<Method> candidates = new ArrayList<Method>(); for (Method method : pojoClass.getMethods()) { if (setMethodName.equals(method.getName())) { Class<?>[] parameterTypes = method.getParameterTypes(); if (parameterTypes.length == 1) { if (exprClass == parameterTypes[0]) { bestMatchMethod = method; break; } else if (ClassUtils.isAssignable(exprClass, parameterTypes[0])) { candidates.add(method); } } } } if (bestMatchMethod == null) { // We did not find the exact match, use candidates to find the match if (candidates.size() == 0) { logger.debug("{} does not have suitable setter method {}. Returning original expression {}.", pojoClass, setMethodName, fieldExpression); /* We did not find any match at all, use original expression */ /* append = (<expr type>)val;*/ return code.append(fieldExpression).append(" = ").appendCastToTypeExpr(exprClass, VAL) .getStatement(); } else { // TODO: see if we can find a better match bestMatchMethod = candidates.get(0); } } /* We found a method that we may use for setter */ /* append <method name>((<expr class)val); */ return code.append(bestMatchMethod.getName()).append("(").appendCastToTypeExpr(exprClass, VAL).append(")") .getStatement(); }