List of usage examples for java.lang.reflect Method getParameterAnnotations
@Override
public Annotation[][] getParameterAnnotations()
From source file:org.apache.camel.component.bean.BeanInfo.java
@SuppressWarnings("unchecked") protected MethodInfo createMethodInfo(Class clazz, Method method) { Class[] parameterTypes = method.getParameterTypes(); Annotation[][] parametersAnnotations = method.getParameterAnnotations(); List<ParameterInfo> parameters = new ArrayList<ParameterInfo>(); List<ParameterInfo> bodyParameters = new ArrayList<ParameterInfo>(); boolean hasCustomAnnotation = false; boolean hasHandlerAnnotation = ObjectHelper.hasAnnotation(method.getAnnotations(), Handler.class); int size = parameterTypes.length; if (LOG.isTraceEnabled()) { LOG.trace("Creating MethodInfo for class: " + clazz + " method: " + method + " having " + size + " parameters"); }// w w w .j a v a 2 s. c o m for (int i = 0; i < size; i++) { Class parameterType = parameterTypes[i]; Annotation[] parameterAnnotations = parametersAnnotations[i]; Expression expression = createParameterUnmarshalExpression(clazz, method, parameterType, parameterAnnotations); hasCustomAnnotation |= expression != null; ParameterInfo parameterInfo = new ParameterInfo(i, parameterType, parameterAnnotations, expression); if (LOG.isTraceEnabled()) { LOG.trace("Parameter #" + i + ": " + parameterInfo); } parameters.add(parameterInfo); if (expression == null) { boolean bodyAnnotation = ObjectHelper.hasAnnotation(parameterAnnotations, Body.class); if (LOG.isTraceEnabled() && bodyAnnotation) { LOG.trace("Parameter #" + i + " has @Body annotation"); } hasCustomAnnotation |= bodyAnnotation; if (bodyParameters.isEmpty()) { // okay we have not yet set the body parameter and we have found // the candidate now to use as body parameter if (Exchange.class.isAssignableFrom(parameterType)) { // use exchange expression = ExpressionBuilder.exchangeExpression(); } else { // lets assume its the body and it must be mandatory convertable to the parameter type // but we allow null bodies in case the message really contains a null body expression = ExpressionBuilder.mandatoryBodyExpression(parameterType, true); } if (LOG.isTraceEnabled()) { LOG.trace("Parameter #" + i + " is the body parameter using expression " + expression); } parameterInfo.setExpression(expression); bodyParameters.add(parameterInfo); } else { // will ignore the expression for parameter evaluation } } if (LOG.isTraceEnabled()) { LOG.trace("Parameter #" + i + " has parameter info: " + parameterInfo); } } // now lets add the method to the repository return new MethodInfo(camelContext, clazz, method, parameters, bodyParameters, hasCustomAnnotation, hasHandlerAnnotation); }
From source file:org.aludratest.testcase.data.impl.xml.XmlBasedTestDataProvider.java
@Override public List<TestCaseData> getTestDataSets(Method method) { if (method.getParameterTypes().length == 0) { return Collections.singletonList(new TestCaseData("0", null, null)); }/* w ww . j a va 2 s .com*/ // get @Source annotated parameters Annotation[][] annots = method.getParameterAnnotations(); Offset offsetAnno = method.getAnnotation(Offset.class); int offset = (offsetAnno != null ? offsetAnno.value() : 0); boolean ignored = method.getAnnotation(Ignored.class) != null; String ignoredReason = null; if (ignored) { ignoredReason = method.getAnnotation(Ignored.class).value(); if ("".equals(ignoredReason)) { ignoredReason = null; } } List<TestCaseData> result = new ArrayList<TestCaseData>(); // cache for loaded file models Map<String, TestData> loadedFileModels = new HashMap<String, TestData>(); // load param by param; transpose into test case data afterwards List<List<InternalSingleDataSource>> allData = new ArrayList<List<InternalSingleDataSource>>(); for (int i = 0; i < annots.length; i++) { List<InternalSingleDataSource> paramData = getDataObjects(method, i, loadedFileModels); if (offset > 0) { if (offset < paramData.size()) { paramData = paramData.subList(offset, paramData.size()); } else { paramData = Collections.emptyList(); } } allData.add(paramData); } // transposition with the help of first loaded XML file Source firstSource = getRequiredSourceAnnotation(annots[0], "first parameter"); TestData data = loadedFileModels.get(firstSource.uri()); List<TestDataConfiguration> configs = data.getConfigurations(); if (offset > 0) { int effectiveOffset = Math.min(offset, configs.size()); configs = configs.subList(effectiveOffset, configs.size()); } for (int i = 0; i < configs.size(); i++) { TestDataConfiguration config = configs.get(i); List<InternalSingleDataSource> dataForConfig = new ArrayList<InternalSingleDataSource>(); // ensure that all data lists contain enough entries for (List<InternalSingleDataSource> ls : allData) { if (ls.size() <= i) { result.add(new TestCaseData(getNextAutoId(result, false), new AutomationException("For method " + method + ", not all referenced XML files contain the same amount of test configurations."))); dataForConfig = null; break; } else { dataForConfig.add(ls.get(i)); } } if (dataForConfig != null) { final List<InternalSingleDataSource> finalData = dataForConfig; TestDataSource source = new TestDataSource() { @Override public Data[] getData() { Data[] dataArray = new Data[finalData.size()]; for (int i = 0; i < finalData.size(); i++) { dataArray[i] = finalData.get(i).getObject(); } return dataArray; } }; if (ignored) { result.add(new TestCaseData(config.getName(), null, source, true, ignoredReason, config.getExternalTestId())); } else { result.add(new TestCaseData(config.getName(), null, source, config.isIgnored(), config.isIgnored() ? config.getIgnoredReason() : null, config.getExternalTestId())); } } } return result; }
From source file:org.LexGrid.LexBIG.caCore.applicationservice.impl.LexEVSApplicationServiceImpl.java
/** * Returns true if the given method or class is marked TOKEN_REQUIRED. * * @param object the object/*from ww w .ja v a 2s . c o m*/ * * @return true, if checks if is client safe */ @SuppressWarnings("unchecked") private int isMethodArgumentSecured(Method object) { Annotation methodArgs[][] = object.getParameterAnnotations(); for (int i = 0; i < methodArgs.length; i++) { for (int j = 0; j < methodArgs[i].length; j++) { if (methodArgs[i][j] instanceof LexEVSSecurityTokenRequiredForParameter) { return i; } } } return -1; }
From source file:pt.webdetails.cpf.InterPluginCall.java
public void run() { Class<?> classe = null; Method operation = null; Object o = null;/*from w ww. j a va2 s.c o m*/ // try { o = getBeanObject(); classe = o.getClass(); Method[] methods = classe.getMethods(); for (Method m : methods) { if (m.getName().equals(method)) { operation = m; break; } } 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(); } else if (annotationClass == "javax.ws.rs.core.Context") { if (paramTypes[i] == HttpServletRequest.class) { CpfHttpServletRequest cpfRequest = (CpfHttpServletRequest) getRequest(); for (Map.Entry<String, Object> entry : requestParameters.entrySet()) { String key = entry.getKey(); Object paramValue = entry.getValue(); if (paramValue instanceof String[]) { String[] lValues = (String[]) paramValue; if (lValues.length == 1) cpfRequest.setParameter(key, lValues[0]); else cpfRequest.setParameter(key, lValues); } else if (paramValue != null) { cpfRequest.setParameter(key, paramValue.toString()); } } parameters.add((HttpServletRequest) cpfRequest); } else if (paramTypes[i] == HttpServletResponse.class) { HttpServletResponse response = (HttpServletResponse) getParameterProviders().get("path") .getParameter("httpresponse"); if (response == null) { response = getResponse(); } parameters.add(response); } } } if (requestParameters.containsKey(paramName)) { Object paramValue = requestParameters.get(paramName); if (paramTypes[i] == int.class) { if (paramValue instanceof String[]) { String[] lValues = (String[]) paramValue; if (lValues.length > 0) paramValue = lValues[0]; else paramValue = null; } int val = Integer.parseInt((String) paramValue); parameters.add(val); } else if (paramTypes[i] == java.lang.Boolean.class || paramTypes[i] == boolean.class) { if (paramValue instanceof String[]) { String[] lValues = (String[]) paramValue; if (lValues.length > 0) paramValue = lValues[0]; else paramValue = null; } boolean val = Boolean.parseBoolean((String) paramValue); parameters.add(val); } else if (paramTypes[i] == java.util.List.class) { List<String> list = new ArrayList<String>(); String[] splittedValues; if (paramValue instanceof String[]) { splittedValues = (String[]) paramValue; } else { splittedValues = ((String) paramValue).split(","); } for (String s : splittedValues) { list.add(s); } parameters.add(list); } else if (paramTypes[i] == java.lang.String.class) { if (paramValue instanceof String[]) { String[] lValues = (String[]) paramValue; if (lValues.length > 0) paramValue = lValues[0]; else paramValue = null; } parameters.add(paramValue); } requestParameters.remove(paramName); } else { if (paramTypes[i] == int.class) { int val = Integer.parseInt(paramDefaultValue); parameters.add(val); } else if (paramTypes[i] == Boolean.class || paramTypes[i] == boolean.class) { boolean val = Boolean.parseBoolean(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); } } } try { objectResponse = 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); } }
From source file:io.milton.http.annotated.AnnotationResourceFactory.java
private boolean isPrincipalArg(java.lang.reflect.Method m, int i) { Annotation[] arr = m.getParameterAnnotations()[i]; Class annoType = io.milton.annotations.Principal.class; for (Annotation a : arr) { if (a.annotationType().equals(annoType)) { return true; }/*w w w . j a va 2 s .c o m*/ } return false; }
From source file:com.joshlong.activiti.coordinator.aop.ActivitiStateAnnotationBeanPostProcessor.java
public Object postProcessAfterInitialization(final Object bean, final String beanName) throws BeansException { // first sift through and get all the methods // then get all the annotations // then build the metadata and register the metadata final Class<?> targetClass = AopUtils.getTargetClass(bean); final ActivitiComponent component = targetClass.getAnnotation(ActivitiComponent.class); ReflectionUtils.doWithMethods(targetClass, new ReflectionUtils.MethodCallback() { @SuppressWarnings("unchecked") public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException { ActivitiState activitiState = AnnotationUtils.getAnnotation(method, ActivitiState.class); String processName = component.processKey(); if (StringUtils.hasText(activitiState.processName())) { processName = activitiState.processName(); }//from ww w. j a v a 2 s. c o m String stateName = activitiState.stateName(); if (!StringUtils.hasText(stateName)) { stateName = activitiState.value(); } Assert.notNull(stateName, "You must provide a stateName!"); Map<Integer, String> vars = new HashMap<Integer, String>(); Annotation[][] paramAnnotationsArray = method.getParameterAnnotations(); int ctr = 0; int pvMapIndex = -1; int procIdIndex = -1; for (Annotation[] paramAnnotations : paramAnnotationsArray) { ctr += 1; for (Annotation pa : paramAnnotations) { if (pa instanceof ProcessVariable) { ProcessVariable pv = (ProcessVariable) pa; String pvName = pv.value(); vars.put(ctr, pvName); } else if (pa instanceof ProcessVariables) { pvMapIndex = ctr; } else if (pa instanceof ProcessId) { procIdIndex = ctr; } } } ActivitiStateHandlerRegistration registration = new ActivitiStateHandlerRegistration(vars, method, bean, stateName, beanName, pvMapIndex, procIdIndex, processName); registry.registerActivitiStateHandler(registration); } }, new ReflectionUtils.MethodFilter() { public boolean matches(Method method) { return null != AnnotationUtils.getAnnotation(method, ActivitiState.class); } }); return bean; }
From source file:com.khs.sherpa.endpoint.SherpaEndpoint.java
@SuppressWarnings("unchecked") // @RolesAllowed("SHERPA_ADMIN") @Action(mapping = "/sherpa/admin/describe/{value}") public Object describe(@Param("value") String value) { List<Map<String, Object>> actions = new ArrayList<Map<String, Object>>(); Set<Method> methods = null; try {/* ww w. j av a 2 s .c o m*/ methods = Reflections.getAllMethods(applicationContext.getType(value), Predicates.and(Predicates.not(SherpaPredicates.withAssignableFrom(Object.class)), ReflectionUtils.withModifier(Modifier.PUBLIC), Predicates.not(ReflectionUtils.withModifier(Modifier.ABSTRACT)), Predicates.not(SherpaPredicates.withGeneric()))); } catch (NoSuchManagedBeanExcpetion e) { throw new SherpaRuntimeException(e); } for (Method method : methods) { Map<String, Object> action = new HashMap<String, Object>(); actions.add(action); action.put("name", MethodUtil.getMethodName(method)); if (method.isAnnotationPresent(DenyAll.class)) { action.put("permission", "DenyAll"); } else if (method.isAnnotationPresent(RolesAllowed.class)) { action.put("permission", "RolesAllowed"); action.put("roles", method.getAnnotation(RolesAllowed.class).value()); } else { action.put("permission", "PermitAll"); } Map<String, String> params = new HashMap<String, String>(); Class<?>[] types = method.getParameterTypes(); Annotation[][] parameters = method.getParameterAnnotations(); for (int i = 0; i < parameters.length; i++) { Class<?> type = types[i]; Param annotation = null; if (parameters[i].length > 0) { for (Annotation an : parameters[i]) { if (an.annotationType().isAssignableFrom(Param.class)) { annotation = (Param) an; break; } } } if (annotation != null) { params.put(annotation.value(), type.getName()); } } if (params.size() > 0) { action.put("params", params); } else { action.put("params", null); } } return actions; }
From source file:net.ymate.platform.validation.ValidationMeta.java
public ValidationMeta(IValidation validation, Class<?> targetClass) { __validation = validation;// w w w. j av a 2 s . c om // ?targetClass@Validation????? Validation _classValidation = targetClass.getAnnotation(Validation.class); if (_classValidation != null) { __mode = _classValidation.mode(); } else { __mode = Validation.MODE.NORMAL; } __targetClass = targetClass; __fields = new LinkedHashMap<String, Annotation[]>(); __labels = new LinkedHashMap<String, String>(); __methodLabels = new LinkedHashMap<Method, Map<String, String>>(); __methods = new LinkedHashMap<Method, Validation>(); __methodParams = new LinkedHashMap<Method, Map<String, Annotation[]>>(); // ?targetClassField? __fields.putAll(__doGetMetaFromFields(null, targetClass, __labels)); // ?targetClassMethod for (Method _method : targetClass.getDeclaredMethods()) { Map<String, String> _paramLabels = new LinkedHashMap<String, String>(); __methodLabels.put(_method, _paramLabels); // ??@Validation Validation _methodValidation = _method.getAnnotation(Validation.class); if (_methodValidation != null) { __methods.put(_method, _methodValidation); } // ???? Map<String, Annotation[]> _paramAnnos = new LinkedHashMap<String, Annotation[]>(); String[] _paramNames = ClassUtils.getMethodParamNames(_method); Annotation[][] _params = _method.getParameterAnnotations(); for (int _idx = 0; _idx < _paramNames.length; _idx++) { List<Annotation> _tmpAnnoList = new ArrayList<Annotation>(); String _paramName = _paramNames[_idx]; // ????? for (Annotation _vField : _params[_idx]) { if (_vField instanceof VField) { VField _vF = (VField) _vField; if (StringUtils.isNotBlank(_vF.name())) { _paramName = ((VField) _vField).name(); } if (StringUtils.isNotBlank(_vF.label())) { _paramLabels.put(_paramName, _vF.label()); } break; } } for (Annotation _annotation : _params[_idx]) { if (__doIsValid(_annotation)) { _tmpAnnoList.add(_annotation); } else if (_annotation instanceof VModel) { // ?@VModel _paramAnnos.putAll( __doGetMetaFromFields(_paramName, _method.getParameterTypes()[_idx], _paramLabels)); } } if (!_tmpAnnoList.isEmpty()) { _paramAnnos.put(_paramName, _tmpAnnoList.toArray(new Annotation[_tmpAnnoList.size()])); } } if (!_paramAnnos.isEmpty()) { __methodParams.put(_method, _paramAnnos); } } }
From source file:com.nineteendrops.tracdrops.client.core.TracClientObjectFactoryImpl.java
protected Object newInstance(ClassLoader classLoader, final Class aClass, final String remoteName) { return Proxy.newProxyInstance(classLoader, new Class[] { aClass }, new InvocationHandler() { public Object invoke(Object pProxy, Method pMethod, Object[] pArgs) throws Throwable { String tracClassName = Utils.findTracClassName(aClass); if (tracClassName == null) { throw new TracException( MessageUtils.registerErrorLog(log, "core.no.trac.classname.found", aClass.getName())); }/*from w w w.j av a 2 s .c o m*/ TracClassMethod tracClassMethodMetadata = Utils.getTracClassMethodAnnotation(pMethod); String tracClassMethodName = Utils.buildTracMethodNameInvocation(tracClassName, tracClassMethodMetadata); Class returnDecoder = tracClassMethodMetadata.returnDecoder(); ArrayList encodedPARGS = new ArrayList(); Annotation[][] parameterAnnotations = pMethod.getParameterAnnotations(); int parameterOrder = 0; ArrayList keptParametersForDecoder = new ArrayList(); for (Annotation[] annotations : parameterAnnotations) { Object currentParameter = pArgs[parameterOrder]; boolean skipInvocationRegistration = false; for (Annotation annotation : annotations) { if (annotation instanceof TracParameterEncoder) { Class encoder = ((TracParameterEncoder) annotation).encoder(); ParameterEncoder parameterEncoder = (ParameterEncoder) encoder.newInstance(); currentParameter = parameterEncoder.encode(tracProperties, currentParameter); } if (annotation instanceof TracParameterPolicy) { TracParameterPolicy tracParameterPolicy = (TracParameterPolicy) annotation; if (tracParameterPolicy.keptForDecoder()) { keptParametersForDecoder.add(currentParameter); } if (tracParameterPolicy.removeFromInvocation()) { skipInvocationRegistration = true; } } } if (!skipInvocationRegistration) { if (currentParameter instanceof MultiParameter) { MultiParameter multiParameter = (MultiParameter) currentParameter; for (Object objectFromMultiparameter : multiParameter.getParameters()) { encodedPARGS.add(objectFromMultiparameter); } } else { encodedPARGS.add(currentParameter); } } parameterOrder++; } if (MulticallManager.multicallActive()) { MulticallManager.multicallRegisterCall(aClass, tracClassMethodName, encodedPARGS.toArray(), returnDecoder, keptParametersForDecoder); if (log.isDebugEnabled()) { log.debug(MessageUtils.getMessage("core.invocation.multicall")); } return null; } else { MulticallManager.multicallStart(tracInvocationObjectFactory); MulticallManager.multicallRegisterCall(aClass, tracClassMethodName, encodedPARGS.toArray(), returnDecoder, keptParametersForDecoder); ArrayList result = MulticallManager.launchMulticall(tracProperties); if (log.isDebugEnabled()) { log.debug(MessageUtils.getMessage("core.invocation.singlecall")); } return result.get(0); } } }); }
From source file:com.art4ul.jcoon.bean.RestClientInterfaceInvocationHandler.java
@Override public Object invoke(Object object, Method method, Object[] params) throws Throwable { LOG.trace("invoke(method = [{}], params = [{}])", new Object[] { method.getName(), params }); Context context = new RestClientContext(object, method, params, restTemplate); if (method.isAnnotationPresent(BaseUrl.class)) { baseUrl = retrieveBaseUrl(context); return null; }//w w w.j a v a2 s . c om context.setBaseUrl(baseUrl); AnnotationProcessor annotationProcessor = AnnotationProcessor.getInstance(); // Process class annotations annotationProcessor.processAnnotationsBefore(context, originalClass.getAnnotations()); // Process method annotations annotationProcessor.processAnnotationsBefore(context, method.getAnnotations()); // Process method params for (int i = 0; i < params.length; i++) { Annotation[] annotations = method.getParameterAnnotations()[i]; Object paramValue = params[i]; annotationProcessor.processAnnotationsBefore(context, annotations, paramValue); } URI uri = context.buildUri(); LOG.debug("URI= {}", uri.toString()); HttpEntity httpEntity = context.createHttpEntity(); Class<?> returnType = null; if (!method.getReturnType().equals(Void.TYPE)) { returnType = method.getReturnType(); } ResponseEntity responseEntity = context.getRestTemplate().exchange(uri, context.getHttpMethod(), httpEntity, returnType); context.setResponseEntity(responseEntity); // Process method params after invocation for (int i = 0; i < params.length; i++) { Annotation[] annotations = method.getParameterAnnotations()[i]; Object paramValue = params[i]; annotationProcessor.processAnnotationsAfter(context, annotations, paramValue); } LOG.debug("responseEntity= {}", responseEntity.getBody()); return responseEntity.getBody(); }