List of usage examples for java.lang.reflect Parameter getAnnotation
public <T extends Annotation> T getAnnotation(Class<T> annotationClass)
From source file:io.silverware.microservices.providers.cdi.internal.RestInterface.java
private static String getParamName(final Parameter methodParameter, Method method, final Class<?> clazz) { final ParamName paramName = methodParameter.getAnnotation(ParamName.class); if (paramName != null && paramName.value() != null && !paramName.value().trim().isEmpty()) { return paramName.value().trim(); }/* w w w . ja va2s . c o m*/ final JsonProperty jsonProperty = methodParameter.getAnnotation(JsonProperty.class); if (jsonProperty != null && jsonProperty.value() != null && !jsonProperty.value().trim().isEmpty()) { return jsonProperty.value().trim(); } if (!methodParameter.isNamePresent()) { log.warn(String.format( "Method parameter name is not present for method %s in class %s. Please use compilation argument (or test compilation argument) \"-parameters\"" + " or use annotation @%s or @%s for parameters of this method.", method.getName(), clazz.getCanonicalName(), ParamName.class.getCanonicalName(), JsonProperty.class.getCanonicalName())); } return methodParameter.getName(); }
From source file:edu.usu.sdl.openstorefront.doc.JaxrsProcessor.java
private static void mapMethodParameters(List<APIParamModel> parameterList, Parameter parameters[]) { for (Parameter parameter : parameters) { APIParamModel paramModel = new APIParamModel(); paramModel.setFieldName(parameter.getName()); QueryParam queryParam = (QueryParam) parameter.getAnnotation(QueryParam.class); FormParam formParam = (FormParam) parameter.getAnnotation(FormParam.class); MatrixParam matrixParam = (MatrixParam) parameter.getAnnotation(MatrixParam.class); HeaderParam headerParam = (HeaderParam) parameter.getAnnotation(HeaderParam.class); CookieParam cookieParam = (CookieParam) parameter.getAnnotation(CookieParam.class); PathParam pathParam = (PathParam) parameter.getAnnotation(PathParam.class); BeanParam beanParam = (BeanParam) parameter.getAnnotation(BeanParam.class); if (queryParam != null) { paramModel.setParameterType(QueryParam.class.getSimpleName()); paramModel.setParameterName(queryParam.value()); }//from ww w. j a v a 2 s .c o m if (formParam != null) { paramModel.setParameterType(FormParam.class.getSimpleName()); paramModel.setParameterName(formParam.value()); } if (matrixParam != null) { paramModel.setParameterType(MatrixParam.class.getSimpleName()); paramModel.setParameterName(matrixParam.value()); } if (pathParam != null) { paramModel.setParameterType(PathParam.class.getSimpleName()); paramModel.setParameterName(pathParam.value()); } if (headerParam != null) { paramModel.setParameterType(HeaderParam.class.getSimpleName()); paramModel.setParameterName(headerParam.value()); } if (cookieParam != null) { paramModel.setParameterType(CookieParam.class.getSimpleName()); paramModel.setParameterName(cookieParam.value()); } if (beanParam != null) { Class paramClass = parameter.getType(); mapParameters(parameterList, ReflectionUtil.getAllFields(paramClass).toArray(new Field[0])); } if (StringUtils.isNotBlank(paramModel.getParameterType())) { APIDescription aPIDescription = (APIDescription) parameter.getAnnotation(APIDescription.class); if (aPIDescription != null) { paramModel.setParameterDescription(aPIDescription.value()); } ParameterRestrictions restrictions = (ParameterRestrictions) parameter .getAnnotation(ParameterRestrictions.class); if (restrictions != null) { paramModel.setRestrictions(restrictions.value()); } RequiredParam requiredParam = (RequiredParam) parameter.getAnnotation(RequiredParam.class); if (requiredParam != null) { paramModel.setRequired(true); } DefaultValue defaultValue = (DefaultValue) parameter.getAnnotation(DefaultValue.class); if (defaultValue != null) { paramModel.setDefaultValue(defaultValue.value()); } parameterList.add(paramModel); } } }
From source file:edu.usu.sdl.openstorefront.doc.JaxrsProcessor.java
private static void mapConsumedObjects(APIMethodModel methodModel, Parameter parameters[]) { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.enable(SerializationFeature.INDENT_OUTPUT); objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); for (Parameter parameter : parameters) { //deterimine if this is "Body" object List<Annotation> paramAnnotation = new ArrayList<>(); paramAnnotation.add(parameter.getAnnotation(QueryParam.class)); paramAnnotation.add(parameter.getAnnotation(FormParam.class)); paramAnnotation.add(parameter.getAnnotation(MatrixParam.class)); paramAnnotation.add(parameter.getAnnotation(HeaderParam.class)); paramAnnotation.add(parameter.getAnnotation(CookieParam.class)); paramAnnotation.add(parameter.getAnnotation(PathParam.class)); paramAnnotation.add(parameter.getAnnotation(BeanParam.class)); boolean consumeObject = true; for (Annotation annotation : paramAnnotation) { if (annotation != null) { consumeObject = false;//from w w w . j a va 2 s .c o m break; } } if (consumeObject) { APIValueModel valueModel = new APIValueModel(); try { valueModel.setValueObjectName(parameter.getType().getSimpleName()); DataType dataType = (DataType) parameter.getAnnotation(DataType.class); if (dataType != null) { String typeName = dataType.value().getSimpleName(); if (StringUtils.isNotBlank(dataType.actualClassName())) { typeName = dataType.actualClassName(); } valueModel.setTypeObjectName(typeName); try { valueModel .setTypeObject(objectMapper.writeValueAsString(dataType.value().newInstance())); Set<String> fieldList = mapValueField(valueModel.getTypeFields(), ReflectionUtil.getAllFields(dataType.value()).toArray(new Field[0]), true); String cleanUpJson = StringProcessor.stripeFieldJSON(valueModel.getTypeObject(), fieldList); valueModel.setTypeObject(cleanUpJson); mapComplexTypes(valueModel.getAllComplexTypes(), ReflectionUtil.getAllFields(dataType.value()).toArray(new Field[0]), true); APIDescription aPIDescription = (APIDescription) dataType.value() .getAnnotation(APIDescription.class); if (aPIDescription != null) { valueModel.setTypeDescription(aPIDescription.value()); } } catch (InstantiationException iex) { log.log(Level.WARNING, MessageFormat.format( "Unable to instantiated type: {0} make sure the type is not abstract.", parameter.getType())); } } else { try { valueModel.setValueObject( objectMapper.writeValueAsString(parameter.getType().newInstance())); Set<String> fieldList = mapValueField(valueModel.getValueFields(), ReflectionUtil.getAllFields(parameter.getType()).toArray(new Field[0]), true); String cleanUpJson = StringProcessor.stripeFieldJSON(valueModel.getValueObject(), fieldList); valueModel.setValueObject(cleanUpJson); mapComplexTypes(valueModel.getAllComplexTypes(), ReflectionUtil.getAllFields(parameter.getType()).toArray(new Field[0]), true); APIDescription aPIDescription = (APIDescription) parameter.getType() .getAnnotation(APIDescription.class); if (aPIDescription != null) { valueModel.setTypeDescription(aPIDescription.value()); } } catch (InstantiationException iex) { log.log(Level.WARNING, MessageFormat.format( "Unable to instantiated type: {0} make sure the type is not abstract.", parameter.getType())); } } } catch (IllegalAccessException | JsonProcessingException ex) { log.log(Level.WARNING, null, ex); } //There can only be one consume(Request Body Parameter) object //We take the first one and ignore the rest. methodModel.setConsumeObject(valueModel); break; } } }
From source file:com.newtranx.util.mysql.fabric.SpringMybatisSetShardKeyAspect.java
@Around("@annotation(com.newtranx.util.mysql.fabric.WithShardKey) || @within(com.newtranx.util.mysql.fabric.WithShardKey)") public Object setShardKey(ProceedingJoinPoint pjp) throws Throwable { Method method = AspectJUtils.getMethod(pjp); String key = null;/*from w w w . j av a 2 s.c o m*/ boolean force = method.getAnnotation(WithShardKey.class).force(); int i = 0; for (Parameter p : method.getParameters()) { ShardKey a = p.getAnnotation(ShardKey.class); if (a != null) { if (key != null) throw new RuntimeException("found multiple shardkey"); Object obj = pjp.getArgs()[i]; if (StringUtils.isEmpty(a.property())) key = obj.toString(); else { BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(obj); key = bw.getPropertyValue(a.property()).toString(); } } i++; } if (key == null) throw new RuntimeException("can not find shardkey"); fabricShardKey.set(key, force); return pjp.proceed(); }
From source file:com.github.ljtfreitas.restify.http.spring.contract.metadata.reflection.SpringWebJavaMethodParameterMetadata.java
public SpringWebJavaMethodParameterMetadata(java.lang.reflect.Parameter javaMethodParameter, Class<?> targetClassType) { this.type = JavaType.of(new JavaTypeResolver(targetClassType).parameterizedTypeOf(javaMethodParameter)); this.pathParameter = AnnotationUtils .synthesizeAnnotation(javaMethodParameter.getAnnotation(PathVariable.class), javaMethodParameter); this.headerParameter = AnnotationUtils .synthesizeAnnotation(javaMethodParameter.getAnnotation(RequestHeader.class), javaMethodParameter); this.bodyParameter = AnnotationUtils .synthesizeAnnotation(javaMethodParameter.getAnnotation(RequestBody.class), javaMethodParameter); this.queryParameter = AnnotationUtils .synthesizeAnnotation(javaMethodParameter.getAnnotation(RequestParam.class), javaMethodParameter); this.name = Optional.ofNullable(pathParameter).map(PathVariable::value).filter(s -> !s.trim().isEmpty()) .orElseGet(() -> Optional.ofNullable(headerParameter).map(RequestHeader::value) .filter(s -> !s.trim().isEmpty()) .orElseGet(() -> Optional.ofNullable(queryParameter).map(RequestParam::value) .filter(s -> !s.trim().isEmpty()) .orElseGet(() -> Optional.ofNullable(javaMethodParameter.getName()).orElseThrow( () -> new IllegalStateException("Could not get the name of the parameter " + javaMethodParameter))))); this.serializerType = SpringWebEndpointMethodParameterSerializer.of(this); }
From source file:alba.solr.docvalues.DynamicDocValuesHelper.java
public Object eval(int doc) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException { // TODO Auto-generated method stub /*if (doc < 0 || doc > this.readerContext.reader().maxDoc()) { return null;/*from w w w.jav a2 s .c o m*/ }*/ Map<String, Object> params = new HashMap<String, Object>(); for (String s : args.keySet()) { if (args.get(s).startsWith("\"")) { params.put(s, args.get(s)); } else if (NumberUtils.isNumber(args.get(s))) { Object objVal; try { objVal = Long.parseLong(args.get(s)); } catch (NumberFormatException nfe1) { try { objVal = Float.parseFloat(args.get(s)); } catch (NumberFormatException nfe2) { objVal = s; } } if (objVal != null) { params.put(s, objVal); } else { params.put(s, "N/A"); } } else if ("false".equals(args.get(s).toLowerCase())) { params.put(s, false); } else if ("true".equals(args.get(s).toLowerCase())) { params.put(s, true); } else { SchemaField f = fp.getReq().getSchema().getField(args.get(s)); ValueSource vs = f.getType().getValueSource(f, fp); Object objVal = null; try { objVal = vs.getValues(this.context, this.readerContext).longVal(doc); params.put(s, objVal); } catch (IOException | UnsupportedOperationException e) { // TODO Auto-generated catch block // TODO Log properly try { objVal = vs.getValues(this.context, this.readerContext).floatVal(doc); } catch (IOException | UnsupportedOperationException e1) { // TODO Auto-generated catch block e1.printStackTrace(); try { objVal = vs.getValues(this.context, this.readerContext).strVal(doc); } catch (IOException | UnsupportedOperationException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } } logger.error("error converting values ", e); } if (objVal != null) { params.put(s, objVal); } else { params.put(s, "N/A"); } } } CallableFunction cf = functions.get(this.functionName); if (cf == null) { logger.error("unable to get function " + this.functionName); } if (cf != null) { List<Object> fnParams = new ArrayList<Object>(); Parameter[] methodParameters = cf.getMethod().getParameters(); //TODO spostare quanto pi codice possibile in fase di inizializzazione for (Parameter p : methodParameters) { if (p.isAnnotationPresent(Param.class)) { Param paramAnnotation = p.getAnnotation(Param.class); fnParams.add(params.get(paramAnnotation.name())); } } return cf.getMethod().invoke(cf.getInstance(), fnParams.toArray()); } else { return null; } }
From source file:alba.solr.docvalues.FloatFunction.java
@Override public float floatVal(int doc) { // TODO Auto-generated method stub Map<String, Object> params = new HashMap<String, Object>(); for (String s : args.keySet()) { if (args.get(s).startsWith("\"")) { params.put(s, args.get(s));/*w w w .j ava 2 s . c om*/ } else if (NumberUtils.isNumber(args.get(s))) { Object objVal; try { objVal = Long.parseLong(args.get(s)); } catch (NumberFormatException nfe1) { try { objVal = Float.parseFloat(args.get(s)); } catch (NumberFormatException nfe2) { objVal = s; } } if (objVal != null) { params.put(s, objVal); } else { params.put(s, "N/A"); } } else if ("false".equals(args.get(s).toLowerCase())) { params.put(s, false); } else if ("true".equals(args.get(s).toLowerCase())) { params.put(s, true); } else { SchemaField f = fp.getReq().getSchema().getField(args.get(s)); ValueSource vs = f.getType().getValueSource(f, fp); Object objVal = null; try { objVal = vs.getValues(this.context, this.readerContext).longVal(doc); params.put(s, objVal); } catch (IOException e) { // TODO Auto-generated catch block // TODO Log properly try { objVal = vs.getValues(this.context, this.readerContext).floatVal(doc); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); try { objVal = vs.getValues(this.context, this.readerContext).strVal(doc); } catch (IOException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } } e.printStackTrace(); } if (objVal != null) { params.put(s, objVal); } else { params.put(s, "N/A"); } } } CallableFunction cf = functions.get(this.functionName); if (cf == null) { logger.error("unable to get function " + this.functionName); } if (cf != null) { List<Object> fnParams = new ArrayList<Object>(); Parameter[] methodParameters = cf.getMethod().getParameters(); //TODO spostare quanto pi codice possibile in fase di inizializzazione for (Parameter p : methodParameters) { if (p.isAnnotationPresent(Param.class)) { Param paramAnnotation = p.getAnnotation(Param.class); fnParams.add(params.get(paramAnnotation.name())); } } try { return (float) cf.getMethod().invoke(cf.getInstance(), fnParams.toArray()); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { // TODO Auto-generated catch block logger.error("errore mentre chiamavo " + cf.getMethod().getName(), e); for (Object o : fnParams) { logger.error("p " + o.toString()); } } } return -1f; }
From source file:com.phoenixnap.oss.ramlapisync.data.ApiParameterMetadata.java
/** * Default constructor that creates a metadata object from a Java parameter * /*from www . j a v a 2 s.com*/ * @param param Java Parameter representation */ public ApiParameterMetadata(Parameter param) { super(); this.resourceId = false; this.nullable = false; String annotatedName = null; if (param == null) { throw new NullArgumentException("param"); } RequestParam requestParam = param.getAnnotation(RequestParam.class); if (requestParam != null) { annotatedName = requestParam.value(); nullable = !requestParam.required(); } PathVariable pathVariable = param.getAnnotation(PathVariable.class); if (pathVariable != null) { resourceId = true; annotatedName = pathVariable.value(); } RequestBody requestBody = param.getAnnotation(RequestBody.class); if (requestBody != null) { nullable = !requestBody.required(); } this.name = resolveParameterName(annotatedName, param); this.param = param; if (param != null) { this.type = param.getType(); this.genericType = (Class<?>) TypeHelper.inferGenericType(param.getParameterizedType()); } Example parameterExample = param.getAnnotation(Example.class); if (parameterExample != null && StringUtils.hasText(parameterExample.value())) { this.example = parameterExample.value(); } }
From source file:org.jspare.forvertx.web.handler.DefaultHandler.java
/** * Resolve parameter./*from w w w .jav a2s .c o m*/ * * @param parameter * the parameter * @param routingContext * the routing context * @return the object */ @SuppressWarnings("unchecked") protected Object resolveParameter(Parameter parameter, RoutingContext routingContext) { if (parameter.getType().equals(RoutingContext.class)) { return routingContext; } if (parameter.getType().equals(HttpServerRequest.class)) { return routingContext.request(); } if (parameter.getType().equals(HttpServerResponse.class)) { return routingContext.response(); } if (StringUtils.isNotEmpty(routingContext.request().getParam(parameter.getName()))) { return routingContext.request().getParam(parameter.getName()); } if (parameter.isAnnotationPresent(ArrayModel.class)) { ArrayModel am = parameter.getAnnotation(ArrayModel.class); Class<? extends Collection<?>> collection = (Class<? extends Collection<?>>) am.collectionClass(); Class<?> clazz = am.value(); return ArrayModelParser.toList(routingContext.getBody().toString(), collection, clazz); } if (parameter.isAnnotationPresent(MapModel.class)) { MapModel mm = parameter.getAnnotation(MapModel.class); Class<?> mapClazz = mm.mapClass(); Class<?> key = mm.key(); Class<?> value = mm.value(); return MapModelParser.toMap(routingContext.getBody().toString(), mapClazz, key, value); } if (parameter.getType().getPackage().getName().endsWith(".model") || parameter.getType().isAnnotationPresent(Model.class) || parameter.isAnnotationPresent(Model.class)) { try { if (routingContext.getBody() == null) { return null; } return my(Json.class).fromJSON(routingContext.getBody().toString(), parameter.getType()); } catch (SerializationException e) { log.debug("Invalid content of body for class [{}] on parameter [{}]", parameter.getClass(), parameter.getName()); return null; } } if (parameter.isAnnotationPresent(org.jspare.forvertx.web.mapping.handling.Parameter.class)) { String parameterName = parameter.getAnnotation(org.jspare.forvertx.web.mapping.handling.Parameter.class) .value(); // Test types Type typeOfParameter = parameter.getType(); if (typeOfParameter.equals(Integer.class)) { return Integer.parseInt(routingContext.request().getParam(parameterName)); } if (typeOfParameter.equals(Double.class)) { return Double.parseDouble(routingContext.request().getParam(parameterName)); } if (typeOfParameter.equals(Long.class)) { return Long.parseLong(routingContext.request().getParam(parameterName)); } return routingContext.request().getParam(parameterName); } if (parameter.isAnnotationPresent(org.jspare.forvertx.web.mapping.handling.Header.class)) { String headerName = parameter.getAnnotation(org.jspare.forvertx.web.mapping.handling.Header.class) .value(); return routingContext.request().getHeader(headerName); } return null; }