List of usage examples for java.lang.reflect Method getParameterAnnotations
@Override
public Annotation[][] getParameterAnnotations()
From source file:org.statefulj.framework.binders.common.AbstractRestfulBinder.java
protected void copyParameters(CtMethod ctMethod, Method method, ClassPool cp) throws NotFoundException, IllegalArgumentException, IllegalAccessException, InvocationTargetException, CannotCompileException { String[] parmNames = (method != null) ? parmDiscover.getParameterNames(method) : null; MethodInfo methodInfo = ctMethod.getMethodInfo(); ParameterAnnotationsAttribute paramAtrributeInfo = new ParameterAnnotationsAttribute( methodInfo.getConstPool(), ParameterAnnotationsAttribute.visibleTag); Annotation[][] paramArrays = new Annotation[method.getParameterTypes().length][]; java.lang.annotation.Annotation[][] parmAnnotations = method.getParameterAnnotations(); int parmIndex = 0; for (Class<?> parm : method.getParameterTypes()) { // Clone the parameter Class ////from w w w. j ava2 s.c o m CtClass ctParm = cp.get(parm.getName()); // Add the parameter to the method // ctMethod.addParameter(ctParm); // Add the Parameter Annotations to the Method // String parmName = (parmNames != null && parmNames.length > parmIndex) ? parmNames[parmIndex] : null; paramArrays[parmIndex] = createParameterAnnotations(parmName, ctMethod.getMethodInfo(), parmAnnotations[parmIndex], paramAtrributeInfo.getConstPool()); parmIndex++; } paramAtrributeInfo.setAnnotations(paramArrays); methodInfo.addAttribute(paramAtrributeInfo); }
From source file:play.modules.swagger.PlayReader.java
private List<Annotation> getParamAnnotations(Class<?> cls, Method method, String simpleTypeName, int fieldPosition) { Type[] genericParameterTypes = method.getGenericParameterTypes(); Annotation[][] paramAnnotations = method.getParameterAnnotations(); List<Annotation> annotations = getParamAnnotations(cls, genericParameterTypes, paramAnnotations, simpleTypeName, fieldPosition); if (annotations != null) { return annotations; }/* ww w .ja v a 2s . c o m*/ // Fallback to type for (int i = 0; i < genericParameterTypes.length; i++) { annotations = getParamAnnotations(cls, genericParameterTypes, paramAnnotations, simpleTypeName, i); if (annotations != null) { return annotations; } } return null; }
From source file:org.apache.lens.cli.doc.TestGenerateCLIUserDoc.java
@Test public void generateDoc() throws IOException { BufferedWriter bw = new BufferedWriter(new FileWriter(new File(APT_FILE))); StringBuilder sb = new StringBuilder(); sb.append(getCLIIntroduction()).append("\n\n\n"); List<Class<? extends CommandMarker>> classes = Lists.newArrayList(LensConnectionCommands.class, LensDatabaseCommands.class, LensStorageCommands.class, LensCubeCommands.class, LensDimensionCommands.class, LensFactCommands.class, LensDimensionTableCommands.class, LensNativeTableCommands.class, LensQueryCommands.class, LensLogResourceCommands.class, LensSchemaCommands.class); for (Class claz : classes) { UserDocumentation doc = (UserDocumentation) claz.getAnnotation(UserDocumentation.class); if (doc != null && StringUtils.isNotBlank(doc.title())) { sb.append("** ").append(doc.title()).append("\n\n ").append(doc.description()).append("\n\n"); }/*from w ww . j a v a 2 s . c o m*/ sb.append("*--+--+\n" + "|<<Command>>|<<Description>>|\n" + "*--+--+\n"); TreeSet<Method> methods = Sets.newTreeSet(new Comparator<Method>() { @Override public int compare(Method o1, Method o2) { return o1.getAnnotation(CliCommand.class).value()[0] .compareTo(o2.getAnnotation(CliCommand.class).value()[0]); } }); for (Method method : claz.getMethods()) { if (method.getAnnotation(CliCommand.class) != null) { methods.add(method); } else { log.info("Not adding " + method.getDeclaringClass().getSimpleName() + "#" + method.getName()); } } List<DocEntry> docEntries = Lists.newArrayList(); for (Method method : methods) { CliCommand annot = method.getAnnotation(CliCommand.class); StringBuilder commandBuilder = new StringBuilder(); String sep = ""; for (String value : annot.value()) { commandBuilder.append(sep).append(value); sep = "/"; } for (Annotation[] annotations : method.getParameterAnnotations()) { for (Annotation paramAnnot : annotations) { if (paramAnnot instanceof CliOption) { CliOption cliOption = (CliOption) paramAnnot; HashSet<String> keys = Sets.newHashSet(cliOption.key()); boolean optional = false; if (keys.contains("")) { optional = true; keys.remove(""); } if (!keys.isEmpty()) { commandBuilder.append(" "); if (!cliOption.mandatory()) { commandBuilder.append("["); } if (optional) { commandBuilder.append("["); } sep = ""; for (String key : keys) { commandBuilder.append(sep).append("--").append(key); sep = "/"; } if (optional) { commandBuilder.append("]"); } sep = ""; } commandBuilder.append(" ") .append(cliOption.help().replaceAll("<", "\\\\<").replaceAll(">", "\\\\>")); if (!cliOption.mandatory()) { commandBuilder.append("]"); } } } } docEntries.add(new DocEntry(commandBuilder.toString(), annot.help().replaceAll("<", "<<<").replaceAll(">", ">>>"))); } for (DocEntry entry : docEntries) { for (int i = 0; i < entry.getHelp().length; i++) { sb.append("|").append(i == 0 ? entry.getCommand() : entry.getCommand().replaceAll(".", " ")) .append("|").append(entry.getHelp()[i]).append("|").append("\n"); } sb.append("*--+--+\n"); } sb.append(" <<").append(getReadableName(claz.getSimpleName())).append(">>\n\n===\n\n"); } bw.write(sb.toString()); bw.close(); }
From source file:ca.uhn.fhir.rest.method.OperationMethodBinding.java
protected OperationMethodBinding(Class<?> theReturnResourceType, Class<? extends IBaseResource> theReturnTypeFromRp, Method theMethod, FhirContext theContext, Object theProvider, boolean theIdempotent, String theOperationName, Class<? extends IBaseResource> theOperationType, OperationParam[] theReturnParams, BundleTypeEnum theBundleType) {//w w w . j av a 2 s . co m super(theReturnResourceType, theMethod, theContext, theProvider); myBundleType = theBundleType; myIdempotent = theIdempotent; myIdParamIndex = MethodUtil.findIdParameterIndex(theMethod, getContext()); if (myIdParamIndex != null) { for (Annotation next : theMethod.getParameterAnnotations()[myIdParamIndex]) { if (next instanceof IdParam) { myCanOperateAtTypeLevel = ((IdParam) next).optional() == true; } } } else { myCanOperateAtTypeLevel = true; } Description description = theMethod.getAnnotation(Description.class); if (description != null) { myDescription = description.formalDefinition(); if (isBlank(myDescription)) { myDescription = description.shortDefinition(); } } if (isBlank(myDescription)) { myDescription = null; } if (isBlank(theOperationName)) { throw new ConfigurationException("Method '" + theMethod.getName() + "' on type " + theMethod.getDeclaringClass().getName() + " is annotated with @" + Operation.class.getSimpleName() + " but this annotation has no name defined"); } if (theOperationName.startsWith("$") == false) { theOperationName = "$" + theOperationName; } myName = theOperationName; if (theContext.getVersion().getVersion().isEquivalentTo(FhirVersionEnum.DSTU1)) { throw new ConfigurationException("@" + Operation.class.getSimpleName() + " methods are not supported on servers for FHIR version " + theContext.getVersion().getVersion().name() + " - Found one on class " + theMethod.getDeclaringClass().getName()); } if (theReturnTypeFromRp != null) { setResourceName(theContext.getResourceDefinition(theReturnTypeFromRp).getName()); } else { if (Modifier.isAbstract(theOperationType.getModifiers()) == false) { setResourceName(theContext.getResourceDefinition(theOperationType).getName()); } else { setResourceName(null); } } if (theMethod.getReturnType().isAssignableFrom(Bundle.class)) { throw new ConfigurationException("Can not return a DSTU1 bundle from an @" + Operation.class.getSimpleName() + " method. Found in method " + theMethod.getName() + " defined in type " + theMethod.getDeclaringClass().getName()); } if (theMethod.getReturnType().equals(IBundleProvider.class)) { myReturnType = ReturnTypeEnum.BUNDLE; } else { myReturnType = ReturnTypeEnum.RESOURCE; } if (getResourceName() == null) { myOtherOperatiopnType = RestOperationTypeEnum.EXTENDED_OPERATION_SERVER; } else if (myIdParamIndex == null) { myOtherOperatiopnType = RestOperationTypeEnum.EXTENDED_OPERATION_TYPE; } else { myOtherOperatiopnType = RestOperationTypeEnum.EXTENDED_OPERATION_INSTANCE; } myReturnParams = new ArrayList<OperationMethodBinding.ReturnType>(); if (theReturnParams != null) { for (OperationParam next : theReturnParams) { ReturnType type = new ReturnType(); type.setName(next.name()); type.setMin(next.min()); type.setMax(next.max()); if (type.getMax() == OperationParam.MAX_DEFAULT) { type.setMax(1); } if (!next.type().equals(IBase.class)) { if (next.type().isInterface() || Modifier.isAbstract(next.type().getModifiers())) { throw new ConfigurationException( "Invalid value for @OperationParam.type(): " + next.type().getName()); } type.setType(theContext.getElementDefinition(next.type()).getName()); } myReturnParams.add(type); } } if (myIdParamIndex != null) { myCanOperateAtInstanceLevel = true; } if (getResourceName() == null) { myCanOperateAtServerLevel = true; } }
From source file:kenh.xscript.impl.BaseElement.java
@Override public int invoke() throws UnsupportedScriptException { logger.info(getInfo());/*from w w w . ja v a 2 s . c o m*/ Annotation ignoreSuperClass = this.getClass().getAnnotation(IgnoreSuperClass.class); Method[] methods = this.getClass().getMethods(); if (ignoreSuperClass != null) methods = this.getClass().getDeclaredMethods(); for (Method method : methods) { String name = method.getName(); Class[] classes = method.getParameterTypes(); Annotation primal = method.getAnnotation(Primal.class); Annotation process = method.getAnnotation(Processing.class); Annotation[][] annotations = method.getParameterAnnotations(); if (process == null && !name.equals(METHOD)) continue; boolean parsedAll = true; if (primal != null) parsedAll = false; boolean find = true; // true, find the suitable method to invoke Object[] objs = new Object[annotations.length]; if (annotations.length == 0) { // non-parameter method if (attributes.size() == 0) find = true; else { logger.trace("Failure(no parameter required): " + method.toGenericString()); find = false; } } else { if (annotations.length != attributes.size()) continue; for (int i = 0; i < annotations.length; i++) { boolean parsed = parsedAll; // parse all attribute boolean reparse = false; // has Reparse annotation Annotation[] anns = annotations[i]; Class class2 = classes[i]; if (anns == null) { logger.trace("Failure(parameter without annotation): " + method.toGenericString()); find = false; break; } String attributeName = null; for (Annotation ann : anns) { if (ann instanceof Attribute) { attributeName = ((Attribute) ann).value(); } if (ann instanceof Primal) { parsed = false; } if (ann instanceof Reparse) { reparse = true; } } if (StringUtils.isBlank(attributeName)) { logger.trace("Failure(annotation value is empty): " + method.toGenericString()); find = false; break; } if (!attributes.containsKey(attributeName)) { logger.trace("Failure(can't find attribute[" + attributeName + "]): " + method.toGenericString()); find = false; break; } Object attrValue = null; try { // parse the parameter of process method if (parsed) { if (reparse) { attrValue = env.parse("{" + attributes.get(attributeName) + "}"); } else { attrValue = env.parse(attributes.get(attributeName)); } } else { attrValue = attributes.get(attributeName); } } catch (UnsupportedExpressionException e) { logger.trace("Failure(error[" + attributeName + ", " + e.getMessage() + "]): " + method.toGenericString()); find = false; //break; throw new UnsupportedScriptException(this, e); } Class class1 = attrValue.getClass(); if (class2.isAssignableFrom(class1) || class2 == Object.class) { objs[i] = attrValue; } else if (class1 == String.class) { try { Object obj = Environment.convert((String) attrValue, class2); if (obj == null) { logger.trace("Failure(Convert failure[" + attributeName + ", null]): " + method.toGenericString()); find = false; break; } else { objs[i] = obj; } } catch (Exception e) { logger.trace("Failure(Convert exception[" + attributeName + "]): " + method.toGenericString()); find = false; break; //UnsupportedScriptException ex = new UnsupportedScriptException(this, e); //throw ex; } } else { logger.trace("Failure(Unsupported class[" + attributeName + ", " + class1 + ", " + class2 + "]): " + method.toGenericString()); find = false; break; } } } if (find) { try { logger.debug("Invoke: " + method.toGenericString()); if (method.getReturnType() == int.class) { return (Integer) method.invoke(this, objs); } else if (method.getReturnType() == Integer.class) { return (Integer) method.invoke(this, objs); } else { method.invoke(this, objs); return NONE; } } catch (InvocationTargetException e) { Throwable t = e.getTargetException(); if (t instanceof UnsupportedScriptException) { throw (UnsupportedScriptException) t; } else { UnsupportedScriptException ex = new UnsupportedScriptException(this, e); throw ex; } } catch (Exception e) { UnsupportedScriptException ex = new UnsupportedScriptException(this, e); throw ex; } } } throw new UnsupportedScriptException(this, "Can't fine the method to process."); }
From source file:com.mnt.base.web.action.impl.AbstractActionControllerManager.java
public void setControllers(Collection<ActionController> controllers) { if (!CommonUtil.isEmpty(controllers)) { for (ActionController ac : controllers) { Class<?> acClazz = ac.getController().getClass(); if (CommonUtil.isEmpty(ac.path())) { ACPath acPath = acClazz.getAnnotation(ACPath.class); ACWebHandler acWebHandler = acClazz.getAnnotation(ACWebHandler.class); if (acWebHandler != null) { ac.setWebHandler(acWebHandler.value()); }/* w w w . ja va 2s . c om*/ if (acPath == null && acClazz.getInterfaces().length > 0) { Class<?>[] clazzs = acClazz.getInterfaces(); for (Class<?> clazz : clazzs) { acClazz = clazz; acPath = acClazz.getAnnotation(ACPath.class); if (acPath != null) { acWebHandler = acClazz.getAnnotation(ACWebHandler.class); if (acWebHandler != null) { ac.setWebHandler(acWebHandler.value()); } break; } } } if (acPath != null) { log.info(new StringBuilder("Attach the action controller for path: ").append(acPath.value()) .append(", implementation class: ") .append(ac.getController().getClass().getName())); actionControllerMap.put(acPath.value(), ac); } else { log.error( "Skip the invalid action controller, the path of the action controller need to be specified, class: " + ac.getClass().getName()); continue; } } else { log.info(new StringBuilder("Attach the action controller for path: ").append(ac.path()) .append(", implementation class: ").append(ac.getClass().getName())); actionControllerMap.put(ac.path(), ac); } Map<String, MethodInfoHolder> acMs = new HashMap<String, MethodInfoHolder>(); List<ResourceInfoHolder> acRs = new ArrayList<ResourceInfoHolder>(); Method[] methods = acClazz.getDeclaredMethods(); ACMethod acMethod; MethodInfoHolder mih; ResourceInfoHolder rih; for (Method m : methods) { acMethod = m.getAnnotation(ACMethod.class); if (acMethod != null) { mih = new MethodInfoHolder(); mih.method = m; mih.method.setAccessible(true); mih.acMethod = acMethod; mih.paramsMap = new LinkedHashMap<String, Class<?>>(); Class<?>[] pts = m.getParameterTypes(); if (pts.length > 0) { Annotation[][] pass = m.getParameterAnnotations(); Annotation[] pas; ACParam acParam; // skip the first two parameters: parameterMap, responseMap for (int i = 0; i < pass.length; i++) { pas = pass[i]; if (pas.length != 1 || !(pas[0] instanceof ACParam)) { log.warn("no corresponding ACParam specified for actioncontroller: " + acClazz.getName() + " method: " + m.getName() + " parameter at index: " + i + "."); mih.paramsMap.put(ACParam.NULL_PREFIX + i, pts[i]); continue; } acParam = (ACParam) (pas[0]); if (acParam.beanPrefix()) { String beanFieldIndexKey = ACParam.BEAN_PREFIX + i; mih.paramsMap.put(beanFieldIndexKey, pts[i]); if (mih.beanFieldDefMap == null) { mih.beanFieldDefMap = new LinkedHashMap<String, Map<String, Field>>(); } Class<?> paramClass = pts[i]; Field[] fields = paramClass.getDeclaredFields(); Map<String, Field> beanFieldDefMap = new LinkedHashMap<String, Field>(); for (Field field : fields) { field.setAccessible(true); beanFieldDefMap.put(new StringBuilder(acParam.value()).append(".") .append(field.getName()).toString(), field); } mih.beanFieldDefMap.put(beanFieldIndexKey, beanFieldDefMap); } else { mih.paramsMap.put(acParam.value(), pts[i]); } } } if (!CommonUtil.isEmpty(acMethod.resource())) { String resourceDef = acMethod.resource(); rih = mih.new ResourceInfoHolder(resourceDef); if (rih.parse()) { acRs.add(rih); } } acMs.put(acMethod.type(), mih); } } if (!acMs.isEmpty()) { acMethodsMap.put(ac, acMs); } if (!acRs.isEmpty()) { acResourcesMap.put(ac, acRs); } } } }
From source file:com.agimatec.validation.jsr303.extensions.MethodValidatorMetaBeanFactory.java
private void buildMethodConstraints(MethodBeanDescriptorImpl beanDesc) throws InvocationTargetException, IllegalAccessException { beanDesc.setMethodConstraints(new HashMap()); for (Method method : beanDesc.getMetaBean().getBeanClass().getDeclaredMethods()) { if (!factoryContext.getFactory().getAnnotationIgnores().isIgnoreAnnotations(method)) { MethodDescriptorImpl methodDesc = new MethodDescriptorImpl(beanDesc.getMetaBean(), new Validation[0]); beanDesc.putMethodDescriptor(method, methodDesc); // return value validations AppendValidationToList validations = new AppendValidationToList(); for (Annotation anno : method.getAnnotations()) { if (anno instanceof Valid) { methodDesc.setCascaded(true); } else { processAnnotation(anno, methodDesc.getMetaBean().getClass(), validations); }// w w w. j a v a 2 s . c o m } methodDesc.getConstraintDescriptors().addAll((List) validations.getValidations()); // parameter validations Annotation[][] paramsAnnos = method.getParameterAnnotations(); Class[] paramTypes = method.getParameterTypes(); int idx = 0; for (Annotation[] paramAnnos : paramsAnnos) { processAnnotations(methodDesc, paramAnnos, paramTypes[idx], idx); idx++; } } } }
From source file:com.nominanuda.hyperapi.HyperApiHttpInvocationHandler.java
private HttpUriRequest encode(String uriPrefix, Class<?> hyperApi2, Method method, Object[] args) { String httpMethod = null;//from ww w . j a va 2s .c om URISpec<DataObject> spec = null; DataObject uriParams = new DataObjectImpl(); @SuppressWarnings("unused") String[] consumedMediaTypes = null; Annotation[] methodAnnotations = method.getAnnotations(); HttpEntity entity = null; for (Annotation a : methodAnnotations) { if (a instanceof POST) { httpMethod = "POST"; } else if (a instanceof GET) { httpMethod = "GET"; } else if (a instanceof PUT) { httpMethod = "PUT"; } else if (a instanceof DELETE) { httpMethod = "DELETE"; } else if (a instanceof Path) { spec = new DataObjectURISpec(uriPrefix + ((Path) a).value()); } else if (a instanceof Consumes) { consumedMediaTypes = (((Consumes) a).value()); } } Annotation[][] parameterAnnotations = method.getParameterAnnotations(); Class<?>[] parameterTypes = method.getParameterTypes(); for (int i = 0; i < parameterTypes.length; i++) { Class<?> parameterType = parameterTypes[i]; Annotation[] annotations = parameterAnnotations[i]; Object arg = args[i]; boolean annotationFound = false; for (Annotation annotation : annotations) { if (annotation instanceof PathParam) { annotationFound = true; if (arg != null) { uriParams.put(((PathParam) annotation).value(), arg.toString());//TODO multivalue or complex transformations } break; } else if (annotation instanceof QueryParam) { annotationFound = true; if (arg != null) { uriParams.put(((QueryParam) annotation).value(), arg.toString());//TODO multivalue or complex transformations } break; } } if (!annotationFound) { Check.unsupportedoperation.assertNull(entity); entity = getEntity(arg, parameterType, annotations); } } String uri = spec.template(uriParams); HttpUriRequest result = createRequest(uri, httpMethod); if (result instanceof HttpEntityEnclosingRequest && entity != null) { ((HttpEntityEnclosingRequest) result).setEntity(entity); } return result; }
From source file:org.saiku.reporting.backend.temp.cpf.InterPluginCall.java
public void run() { String pluginName = plugin.getName(); Class<?> classe = null; Method operation = null; Object o = null;// w w w. ja v a2 s . c om try { classe = getPluginManager().getBean(pluginName + SUFIX).getClass(); Method[] methods = classe.getMethods(); o = classe.newInstance(); for (Method m : methods) { if (m.getName() == method) { operation = m; } } } catch (PluginBeanException ex) { logger.error("Trying to get a plugin not declared on beans", ex); } catch (InstantiationException ex) { logger.error("Error while instanciating class of bean with id " + pluginName, ex); } catch (IllegalAccessException ex) { logger.error("Error while instanciating class of bean with id " + pluginName, ex); } Annotation[][] params = operation.getParameterAnnotations(); Class<?>[] paramTypes = operation.getParameterTypes(); List<Object> parameters = new ArrayList<Object>(); for (int i = 0; i < params.length; i++) { String paramName = ""; String paramDefaultValue = ""; for (Annotation annotation : params[i]) { String annotationClass = annotation.annotationType().getName(); if (annotationClass == "javax.ws.rs.QueryParam") { QueryParam param = (QueryParam) annotation; paramName = param.value(); } else if (annotationClass == "javax.ws.rs.DefaultValue") { DefaultValue param = (DefaultValue) annotation; paramDefaultValue = param.value(); } } if (requestParameters.containsKey(paramName)) { if (paramTypes[i] == int.class) { int val = Integer.parseInt((String) requestParameters.get(paramName)); parameters.add(val); } else if (paramTypes[i] == java.lang.Boolean.class) { boolean val = Boolean.parseBoolean((String) requestParameters.get(paramName)); parameters.add(val); } else if (paramTypes[i] == java.util.List.class) { List<String> list = new ArrayList<String>(); String values = (String) requestParameters.get(paramName); String[] splittedValues = values.split(","); for (String s : splittedValues) { list.add(s); } parameters.add(list); } else if (paramTypes[i] == java.lang.String.class) { parameters.add(requestParameters.get(paramName)); } requestParameters.remove(paramName); } else { if (paramTypes[i] == int.class) { int val = Integer.parseInt((String) paramDefaultValue); parameters.add(val); } else if (paramTypes[i] == java.lang.Boolean.class) { boolean val = Boolean.parseBoolean((String) paramDefaultValue); parameters.add(val); } else if (paramTypes[i] == java.util.List.class) { List<String> list = new ArrayList<String>(); String values = paramDefaultValue; String[] splittedValues = values.split(","); for (String s : splittedValues) { list.add(s); } parameters.add(list); } else if (paramTypes[i] == java.lang.String.class) { parameters.add(paramDefaultValue); } } } parameters.add((HttpServletResponse) getParameterProviders().get("path").getParameter("httpresponse")); CpfHttpServletRequest cpfRequest = (CpfHttpServletRequest) getRequest(); for (Map.Entry<String, Object> entry : requestParameters.entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); cpfRequest.setParameter(key, (String) value); } parameters.add(getRequest()); try { operation.invoke(o, parameters.toArray()); } catch (IllegalAccessException ex) { logger.error("", ex); } catch (IllegalArgumentException ex) { logger.error("", ex); } catch (InvocationTargetException ex) { logger.error("", ex); } catch (Exception ex) { logger.error("", ex); } }