List of usage examples for java.lang.reflect Method getAnnotations
public Annotation[] getAnnotations()
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 va 2 s . c o m*/ 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(); }
From source file:com.github.wnameless.spring.routing.RoutingPathResolver.java
/** * Creates a {@link RoutingPathResolver}. * /*from w ww . j av a 2 s . c o m*/ * @param appCtx * the Spring {@link ApplicationContext} * @param basePackages * packages to be searched */ public RoutingPathResolver(ApplicationContext appCtx, String... basePackages) { env = appCtx.getEnvironment(); Map<String, Object> beans = appCtx.getBeansWithAnnotation(Controller.class); beans.putAll(appCtx.getBeansWithAnnotation(RestController.class)); retainBeansByPackageNames(beans, basePackages); for (Object bean : beans.values()) { List<Method> mappingMethods = getMethodsListWithAnnotation(bean.getClass(), RequestMapping.class); RequestMapping classRM = bean.getClass().getAnnotation(RequestMapping.class); for (Method method : mappingMethods) { RequestMapping methodRM = method.getAnnotation(RequestMapping.class); for (Entry<String, RequestMethod> rawPathAndMethod : computeRawPaths(classRM, methodRM)) { String rawPath = rawPathAndMethod.getKey(); String path = computePath(rawPath); String regexPath = computeRegexPath(path); routingPaths.add(new RoutingPath(rawPathAndMethod.getValue(), rawPath, path, Pattern.compile(regexPath), bean.getClass().getAnnotations(), method.getAnnotations())); } } } }
From source file:org.sindice.rdfcommons.beanmapper.BeanDeserializer.java
@SuppressWarnings("unchecked") public <T> T deserialize(DeserializationContext context, Class<T> clazz, Annotation[] annotations, Identifier identifier, QueryEndpoint endPoint) throws DeserializationException { final T bean; try {//from w w w . j a v a2 s. c om bean = clazz.newInstance(); } catch (Exception e) { throw new DeserializationException("Error while instantiating object.", e); } context.registerInstance(identifier, bean); final String classUrl = getClassURL(bean.getClass()); final BeanMap beanMap = new BeanMap(bean); String propertyURL; for (Map.Entry<String, Object> entry : (Set<Map.Entry<String, Object>>) beanMap.entrySet()) { // Skipping self description. if ("class".equals(entry.getKey())) { continue; } final String propertyName = entry.getKey(); final Method propertyWriteMethod = beanMap.getWriteMethod(propertyName); if (propertyWriteMethod == null) { throw new DeserializationException( String.format("Cannot find setter for property '%s' in bean %s", propertyName, bean)); } final Class propertyType = propertyWriteMethod.getParameterTypes()[0]; // Skipping properties marked as ignored. if (isIgnored(propertyWriteMethod)) { continue; } final Object value = retrieveObject(classUrl, propertyName, propertyWriteMethod, identifier, endPoint, context); // Skipping missing values. if (value == null) { continue; } Object deserializedValue = context.deserialize(context, propertyType, propertyWriteMethod.getAnnotations(), new Identifier(value, Identifier.Type.resource), endPoint); try { propertyWriteMethod.invoke(bean, deserializedValue); } catch (Exception e) { throw new DeserializationException( String.format("Error while setting value [%s] on bean [%s] using setter [%s].", value, bean, propertyWriteMethod), e); } } return bean; }
From source file:org.wso2.msf4j.swagger.ExtendedSwaggerReader.java
private String getHttpMethodFromCustomAnnotations(Method method) { for (Annotation methodAnnotation : method.getAnnotations()) { HttpMethod httpMethod = methodAnnotation.annotationType().getAnnotation(HttpMethod.class); if (httpMethod != null) { return httpMethod.value().toLowerCase(Locale.US); }/*from w w w . j av a2 s . c o m*/ } return null; }
From source file:org.jvnet.hudson.test.HudsonTestCase.java
/** * Called during the {@link #setUp()} to give a test case an opportunity to * control the test environment in which Hudson is run. * * <p>/* www . j a v a 2 s . co m*/ * One could override this method and call a series of {@code withXXX} methods, * or you can use the annotations with {@link Recipe} meta-annotation. */ protected void recipe() throws Exception { recipeLoadCurrentPlugin(); // look for recipe meta-annotation Method runMethod = getClass().getMethod(getName()); for (final Annotation a : runMethod.getAnnotations()) { Recipe r = a.annotationType().getAnnotation(Recipe.class); if (r == null) continue; final Runner runner = r.value().newInstance(); recipes.add(runner); tearDowns.add(new LenientRunnable() { public void run() throws Exception { runner.tearDown(HudsonTestCase.this, a); } }); runner.setup(this, a); } }
From source file:com.opensymphony.xwork2.validator.AnnotationValidationConfigurationBuilder.java
private List<ValidatorConfig> processAnnotations(Object o) { List<ValidatorConfig> result = new ArrayList<ValidatorConfig>(); String fieldName = null;//from w ww . java2 s . co m String methodName = null; Annotation[] annotations = null; if (o instanceof Class) { Class clazz = (Class) o; annotations = clazz.getAnnotations(); } if (o instanceof Method) { Method method = (Method) o; fieldName = resolvePropertyName(method); methodName = method.getName(); annotations = method.getAnnotations(); } if (annotations != null) { for (Annotation a : annotations) { // Process collection of custom validations if (a instanceof Validations) { processValidationAnnotation(a, fieldName, methodName, result); } // Process single custom validator if (a instanceof Validation) { Validation v = (Validation) a; if (v.validations() != null) { for (Validations val : v.validations()) { processValidationAnnotation(val, fieldName, methodName, result); } } } // Process single custom validator else if (a instanceof ExpressionValidator) { ExpressionValidator v = (ExpressionValidator) a; ValidatorConfig temp = processExpressionValidatorAnnotation(v, fieldName, methodName); if (temp != null) { result.add(temp); } } // Process single custom validator else if (a instanceof CustomValidator) { CustomValidator v = (CustomValidator) a; ValidatorConfig temp = processCustomValidatorAnnotation(v, fieldName, methodName); if (temp != null) { result.add(temp); } } // Process ConversionErrorFieldValidator else if (a instanceof ConversionErrorFieldValidator) { ConversionErrorFieldValidator v = (ConversionErrorFieldValidator) a; ValidatorConfig temp = processConversionErrorFieldValidatorAnnotation(v, fieldName, methodName); if (temp != null) { result.add(temp); } } // Process DateRangeFieldValidator else if (a instanceof DateRangeFieldValidator) { DateRangeFieldValidator v = (DateRangeFieldValidator) a; ValidatorConfig temp = processDateRangeFieldValidatorAnnotation(v, fieldName, methodName); if (temp != null) { result.add(temp); } } // Process EmailValidator else if (a instanceof EmailValidator) { EmailValidator v = (EmailValidator) a; ValidatorConfig temp = processEmailValidatorAnnotation(v, fieldName, methodName); if (temp != null) { result.add(temp); } } // Process FieldExpressionValidator else if (a instanceof FieldExpressionValidator) { FieldExpressionValidator v = (FieldExpressionValidator) a; ValidatorConfig temp = processFieldExpressionValidatorAnnotation(v, fieldName, methodName); if (temp != null) { result.add(temp); } } // Process IntRangeFieldValidator else if (a instanceof IntRangeFieldValidator) { IntRangeFieldValidator v = (IntRangeFieldValidator) a; ValidatorConfig temp = processIntRangeFieldValidatorAnnotation(v, fieldName, methodName); if (temp != null) { result.add(temp); } } // Process ShortRangeFieldValidator else if (a instanceof ShortRangeFieldValidator) { ShortRangeFieldValidator v = (ShortRangeFieldValidator) a; ValidatorConfig temp = processShortRangeFieldValidatorAnnotation(v, fieldName, methodName); if (temp != null) { result.add(temp); } } // Process DoubleRangeFieldValidator else if (a instanceof DoubleRangeFieldValidator) { DoubleRangeFieldValidator v = (DoubleRangeFieldValidator) a; ValidatorConfig temp = processDoubleRangeFieldValidatorAnnotation(v, fieldName, methodName); if (temp != null) { result.add(temp); } } // Process RequiredFieldValidator else if (a instanceof RequiredFieldValidator) { RequiredFieldValidator v = (RequiredFieldValidator) a; ValidatorConfig temp = processRequiredFieldValidatorAnnotation(v, fieldName, methodName); if (temp != null) { result.add(temp); } } // Process RequiredStringValidator else if (a instanceof RequiredStringValidator) { RequiredStringValidator v = (RequiredStringValidator) a; ValidatorConfig temp = processRequiredStringValidatorAnnotation(v, fieldName, methodName); if (temp != null) { result.add(temp); } } // Process StringLengthFieldValidator else if (a instanceof StringLengthFieldValidator) { StringLengthFieldValidator v = (StringLengthFieldValidator) a; ValidatorConfig temp = processStringLengthFieldValidatorAnnotation(v, fieldName, methodName); if (temp != null) { result.add(temp); } } // Process UrlValidator else if (a instanceof UrlValidator) { UrlValidator v = (UrlValidator) a; ValidatorConfig temp = processUrlValidatorAnnotation(v, fieldName, methodName); if (temp != null) { result.add(temp); } } // Process ConditionalVisitorFieldValidator else if (a instanceof ConditionalVisitorFieldValidator) { ConditionalVisitorFieldValidator v = (ConditionalVisitorFieldValidator) a; ValidatorConfig temp = processConditionalVisitorFieldValidatorAnnotation(v, fieldName, methodName); if (temp != null) { result.add(temp); } } // Process VisitorFieldValidator else if (a instanceof VisitorFieldValidator) { VisitorFieldValidator v = (VisitorFieldValidator) a; ValidatorConfig temp = processVisitorFieldValidatorAnnotation(v, fieldName, methodName); if (temp != null) { result.add(temp); } } // Process RegexFieldValidator else if (a instanceof RegexFieldValidator) { RegexFieldValidator v = (RegexFieldValidator) a; ValidatorConfig temp = processRegexFieldValidatorAnnotation(v, fieldName, methodName); if (temp != null) { result.add(temp); } } } } return result; }
From source file:com.netsteadfast.greenstep.service.aspect.ServiceAuthorityCheckAspect.java
@Around(ServiceAspectConstants.AROUND_VALUE) public Object aroundMethod(ProceedingJoinPoint pjp) throws AuthorityException, ServiceException, Throwable { MethodSignature signature = (MethodSignature) pjp.getSignature(); Annotation[] annotations = pjp.getTarget().getClass().getAnnotations(); String serviceId = this.getServiceId(annotations); Subject subject = SecurityUtils.getSubject(); Method method = signature.getMethod(); if (subject.hasRole(Constants.SUPER_ROLE_ALL) || subject.hasRole(Constants.SUPER_ROLE_ADMIN)) { SysEventLogSupport.log((String) subject.getPrincipal(), Constants.getSystem(), this.getEventId(serviceId, method.getName()), true); return pjp.proceed(); }/* w ww . j a v a2 s . co m*/ if (StringUtils.isBlank(serviceId)) { // service id SysEventLogSupport.log((String) subject.getPrincipal(), Constants.getSystem(), this.getEventId(serviceId, method.getName()), true); return pjp.proceed(); } if (!this.isServiceAuthorityCheck(annotations)) { // ServiceAuthority check=false ? SysEventLogSupport.log((String) subject.getPrincipal(), Constants.getSystem(), this.getEventId(serviceId, method.getName()), true); return pjp.proceed(); } Annotation[] methodAnnotations = method.getAnnotations(); if (this.isServiceMethodAuthority(serviceId, methodAnnotations, subject)) { SysEventLogSupport.log((String) subject.getPrincipal(), Constants.getSystem(), this.getEventId(serviceId, method.getName()), true); return pjp.proceed(); } logger.warn("[decline] user[" + subject.getPrincipal() + "] " + pjp.getTarget().getClass().getName() + " - " + signature.getMethod().getName()); SysEventLogSupport.log((String) subject.getPrincipal(), Constants.getSystem(), this.getEventId(serviceId, method.getName()), false); throw new AuthorityException(SysMessageUtil.get(GreenStepSysMsgConstants.NO_PERMISSION)); }
From source file:org.qifu.base.aspect.ServiceAuthorityCheckAspect.java
@Around(AspectConstants.LOGIC_SERVICE_PACKAGE) public Object logicServiceProcess(ProceedingJoinPoint pjp) throws AuthorityException, ServiceException, Throwable { MethodSignature signature = (MethodSignature) pjp.getSignature(); Annotation[] annotations = pjp.getTarget().getClass().getAnnotations(); String serviceId = AspectConstants.getServiceId(annotations); Subject subject = SecurityUtils.getSubject(); Method method = signature.getMethod(); if (subject.hasRole(Constants.SUPER_ROLE_ALL) || subject.hasRole(Constants.SUPER_ROLE_ADMIN)) { SysEventLogSupport.log((String) subject.getPrincipal(), Constants.getSystem(), this.getEventId(serviceId, method.getName()), true); return pjp.proceed(); }/*from w w w. j a va 2 s . c o m*/ if (StringUtils.isBlank(serviceId)) { // service id SysEventLogSupport.log((String) subject.getPrincipal(), Constants.getSystem(), this.getEventId(serviceId, method.getName()), true); return pjp.proceed(); } if (!this.isServiceAuthorityCheck(annotations)) { // ServiceAuthority check=false ? SysEventLogSupport.log((String) subject.getPrincipal(), Constants.getSystem(), this.getEventId(serviceId, method.getName()), true); return pjp.proceed(); } Annotation[] methodAnnotations = method.getAnnotations(); if (this.isServiceMethodAuthority(serviceId, methodAnnotations, subject)) { SysEventLogSupport.log((String) subject.getPrincipal(), Constants.getSystem(), this.getEventId(serviceId, method.getName()), true); return pjp.proceed(); } logger.warn("[decline] user[" + subject.getPrincipal() + "] " + pjp.getTarget().getClass().getName() + " - " + signature.getMethod().getName()); SysEventLogSupport.log((String) subject.getPrincipal(), Constants.getSystem(), this.getEventId(serviceId, method.getName()), false); throw new AuthorityException(SysMessageUtil.get(SysMsgConstants.NO_PERMISSION)); }
From source file:com.netsteadfast.greenstep.aspect.ServiceAuthorityCheckAspect.java
@Around(AspectConstants.LOGIC_SERVICE_PACKAGE) public Object logicServiceProcess(ProceedingJoinPoint pjp) throws AuthorityException, ServiceException, Throwable { MethodSignature signature = (MethodSignature) pjp.getSignature(); Annotation[] annotations = pjp.getTarget().getClass().getAnnotations(); String serviceId = AspectConstants.getServiceId(annotations); Subject subject = SecurityUtils.getSubject(); Method method = signature.getMethod(); if (subject.hasRole(Constants.SUPER_ROLE_ALL) || subject.hasRole(Constants.SUPER_ROLE_ADMIN)) { SysEventLogSupport.log((String) subject.getPrincipal(), Constants.getSystem(), this.getEventId(serviceId, method.getName()), true); return pjp.proceed(); }// ww w . jav a 2 s . c om if (StringUtils.isBlank(serviceId)) { // service id SysEventLogSupport.log((String) subject.getPrincipal(), Constants.getSystem(), this.getEventId(serviceId, method.getName()), true); return pjp.proceed(); } if (!this.isServiceAuthorityCheck(annotations)) { // ServiceAuthority check=false ? SysEventLogSupport.log((String) subject.getPrincipal(), Constants.getSystem(), this.getEventId(serviceId, method.getName()), true); return pjp.proceed(); } Annotation[] methodAnnotations = method.getAnnotations(); if (this.isServiceMethodAuthority(serviceId, methodAnnotations, subject)) { SysEventLogSupport.log((String) subject.getPrincipal(), Constants.getSystem(), this.getEventId(serviceId, method.getName()), true); return pjp.proceed(); } logger.warn("[decline] user[" + subject.getPrincipal() + "] " + pjp.getTarget().getClass().getName() + " - " + signature.getMethod().getName()); SysEventLogSupport.log((String) subject.getPrincipal(), Constants.getSystem(), this.getEventId(serviceId, method.getName()), false); throw new AuthorityException(SysMessageUtil.get(GreenStepSysMsgConstants.NO_PERMISSION)); }
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"); }/*from ww w . j av a 2s . com*/ 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); }