Java Code Examples for java.lang.reflect.Parameter#getAnnotation()

The following examples show how to use java.lang.reflect.Parameter#getAnnotation() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ComponentEventBusUtil.java    From flow with Apache License 2.0 6 votes vote down vote up
/**
 * Scans the event type and forms a map of event data expression (for
 * {@link com.vaadin.flow.dom.DomListenerRegistration#addEventData(String)}
 * ) to Java type, with the same order as the parameters for the event
 * constructor (as returned by {@link #getEventConstructor(Class)}).
 *
 * @return a map of event data expressions, in the order defined by the
 *         component event constructor parameters
 */
private static LinkedHashMap<String, Class<?>> findEventDataExpressions(
        Constructor<? extends ComponentEvent<?>> eventConstructor) {
    LinkedHashMap<String, Class<?>> eventDataExpressions = new LinkedHashMap<>();
    // Parameter 0 is always "Component source"
    // Parameter 1 is always "boolean fromClient"
    for (int i = 2; i < eventConstructor.getParameterCount(); i++) {
        Parameter p = eventConstructor.getParameters()[i];
        EventData eventData = p.getAnnotation(EventData.class);
        if (eventData == null || eventData.value().isEmpty()) {
            // The parameter foo of the constructor Bar(Foo foo) has no
            // @DomEvent, or its value is empty."
            throw new IllegalArgumentException(String.format(
                    "The parameter %s of the constructor %s has no @%s, or the annotation value is empty",
                    p.getName(), eventConstructor.toString(),
                    EventData.class.getSimpleName()));
        }
        eventDataExpressions.put(eventData.value(),p.getType());
    }
    return eventDataExpressions;
}
 
Example 2
Source File: SelenideDriverHandler.java    From selenium-jupiter with Apache License 2.0 6 votes vote down vote up
public SelenideConfig getSelenideConfig(Parameter parameter,
        Optional<Object> testInstance) throws IllegalAccessException {

    SelenideConfig config = new SelenideConfig();
    if (parameter != null) {
        // @SelenideConfiguration as parameter
        SelenideConfiguration selenideConfiguration = parameter
                .getAnnotation(SelenideConfiguration.class);
        if (selenideConfiguration != null) {
            config.browser(selenideConfiguration.browser());
            config.headless(selenideConfiguration.headless());
            config.browserBinary(selenideConfiguration.browserBinary());
        }

        // @SelenideConfiguration as field
        SelenideConfig globalConfig = annotationsReader
                .getFromAnnotatedField(testInstance,
                        SelenideConfiguration.class, SelenideConfig.class);
        if (globalConfig != null) {
            config = globalConfig;
        }
    }

    return config;
}
 
Example 3
Source File: ComponentEventBusUtil.java    From flow with Apache License 2.0 6 votes vote down vote up
/**
 * Checks if the given constructor can be used when firing a
 * {@link ComponentEvent} based on a {@link DomEvent}.
 *
 * @param constructor
 *            the constructor to check
 * @return <code>true</code> if the constructor can be used,
 *         <code>false</code> otherwise
 */
public static boolean isDomEventConstructor(Constructor<?> constructor) {
    if (constructor.getParameterCount() < 2) {
        return false;
    }
    if (!Component.class
            .isAssignableFrom(constructor.getParameterTypes()[0])) {
        return false;
    }
    if (constructor.getParameterTypes()[1] != boolean.class) {
        return false;
    }
    for (int param = 2; param < constructor.getParameterCount(); param++) {
        Parameter p = constructor.getParameters()[param];

        if (p.getAnnotation(EventData.class) == null) {
            return false;
        }
    }

    return true;
}
 
Example 4
Source File: ApiBuilder.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
private JaxrsQueryParameter jaxrsQueryParameter(Class<?> clz, Method method, Parameter parameter) {
	JaxrsParameterDescribe jaxrsParameterDescribe = parameter.getAnnotation(JaxrsParameterDescribe.class);
	QueryParam queryParam = parameter.getAnnotation(QueryParam.class);
	JaxrsQueryParameter o = new JaxrsQueryParameter();
	if (null != jaxrsParameterDescribe) {
		o.setDescription(jaxrsParameterDescribe.value());
	} else {
		logger.print("类: {}, 方法: {} ,未设置参数 {} 的JaxrsParameterDescribe.", clz.getName(), method.getName(),
				queryParam.value());
		o.setDescription("");
	}
	o.setName(queryParam.value());
	o.setType(this.simpleType(parameter.getType().getName()));
	return o;
}
 
Example 5
Source File: ServiceMethodInfo.java    From spring-cloud-sockets with Apache License 2.0 5 votes vote down vote up
private void findPayloadParameter(){
	if(this.method.getParameterCount() == 0){
		throw new IllegalStateException("Service methods must have at least one receiving parameter");
	}

	else if(this.method.getParameterCount() == 1){
		this.payloadParameter = new MethodParameter(this.method, 0);
	}
	int payloadAnnotations = Flux.just(this.method.getParameters())
			.filter(parameter -> parameter.getAnnotation(Payload.class) != null)
			.reduce(0, (a, parameter) -> { return a+1; })
			.block();
	if(payloadAnnotations > 1){
		throw new IllegalStateException("Service methods can have at most one @Payload annotated parameters");
	}

	for(int i=0; i<this.method.getParameters().length; i++){
		Parameter p = this.method.getParameters()[i];
		if(p.getAnnotation(Payload.class) != null){
			this.payloadParameter = new MethodParameter(this.method, i);
			break;
		}
	}
	if(this.payloadParameter == null){
		throw new IllegalStateException("Service methods annotated with more than one parameter must declare one @Payload parameter");
	}
	resolvePayloadType();
}
 
Example 6
Source File: ControllerUtils.java    From pippo with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the name of a parameter.
 *
 * @param parameter
 * @return the name of a parameter.
 */
public static String getParameterName(Parameter parameter) {
    // identify parameter name and pattern from controllerMethod signature
    String methodParameterName = parameter.getName();
    if (parameter.isAnnotationPresent(Param.class)) {
        Param param = parameter.getAnnotation(Param.class);
        if (!StringUtils.isNullOrEmpty(param.value())) {
            methodParameterName = param.value();
        }
    }

    return methodParameterName;
}
 
Example 7
Source File: DescribeBuilder.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
private JaxrsQueryParameter jaxrsQueryParameter(Class<?> clz, Method method, Parameter parameter) {
	JaxrsParameterDescribe jaxrsParameterDescribe = parameter.getAnnotation(JaxrsParameterDescribe.class);
	QueryParam queryParam = parameter.getAnnotation(QueryParam.class);
	JaxrsQueryParameter o = new JaxrsQueryParameter();
	if (null != jaxrsParameterDescribe) {
		o.setDescription(jaxrsParameterDescribe.value());
	} else {
		logger.print("类: {}, 方法: {} ,未设置参数 {} 的JaxrsParameterDescribe.", clz.getName(), method.getName(),
				queryParam.value());
		o.setDescription("");
	}
	o.setName(queryParam.value());
	o.setType(this.simpleType(parameter.getType().getName()));
	return o;
}
 
Example 8
Source File: EndpointValidator.java    From msf4j with Apache License 2.0 5 votes vote down vote up
private boolean validateOnPongMethod(Object webSocketEndpoint)
        throws WebSocketMethodParameterException, WebSocketEndpointMethodReturnTypeException {
    EndpointDispatcher dispatcher = new EndpointDispatcher();
    Method method;
    if (dispatcher.getOnPongMessageMethod(webSocketEndpoint).isPresent()) {
        method = dispatcher.getOnPongMessageMethod(webSocketEndpoint).get();
    } else {
        return true;
    }
    validateReturnType(method);
    boolean foundPrimaryPong = false;
    for (Parameter parameter: method.getParameters()) {
        Class<?> paraType = parameter.getType();
        if (paraType == String.class) {
            if (parameter.getAnnotation(PathParam.class) == null) {
                throw new WebSocketMethodParameterException("Invalid parameter found on pong message method: " +
                                                                    "string parameter without " +
                                                                    "@PathParam annotation.");
            }
        } else if (paraType == PongMessage.class) {
            if (foundPrimaryPong) {
                throw new WebSocketMethodParameterException("Invalid parameter found on pong message method: " +
                                                                    "only one PongMessage should be declared.");
            }
            foundPrimaryPong = true;
        } else if (paraType != WebSocketConnection.class) {
            throw new WebSocketMethodParameterException("Invalid parameter found on pong message method: " +
                                                                paraType);
        }
    }
    return foundPrimaryPong;
}
 
Example 9
Source File: MultipartParamBinder.java    From oxygen with Apache License 2.0 5 votes vote down vote up
@Override
public DataBinder build(Parameter parameter) {
  DataBinder dataBinder = new DataBinder();
  dataBinder.setType(parameter.getType());
  dataBinder.setName(parameter.getName());
  MultipartParam param = parameter.getAnnotation(MultipartParam.class);
  if (param != null && param.value().length() > 0) {
    dataBinder.setName(param.value());
  }
  dataBinder.setFunc(ctx -> ctx.request().getMultipartItem(dataBinder.getName()));
  return dataBinder;
}
 
Example 10
Source File: OperaDriverHandler.java    From selenium-jupiter with Apache License 2.0 5 votes vote down vote up
@Override
public MutableCapabilities getOptions(Parameter parameter,
        Optional<Object> testInstance)
        throws IOException, IllegalAccessException {
    OperaOptions operaOptions = new OperaOptions();

    if (parameter != null) {
        // @Arguments
        Arguments arguments = parameter.getAnnotation(Arguments.class);
        if (arguments != null) {
            stream(arguments.value()).forEach(operaOptions::addArguments);
        }

        // @Extensions
        Extensions extensions = parameter.getAnnotation(Extensions.class);
        if (extensions != null) {
            for (String extension : extensions.value()) {
                operaOptions.addExtensions(getExtension(extension));
            }
        }

        // @Binary
        Binary binary = parameter.getAnnotation(Binary.class);
        if (binary != null) {
            operaOptions.setBinary(binary.value());
        }

        // @Options
        OperaOptions optionsFromAnnotatedField = annotationsReader
                .getFromAnnotatedField(testInstance, Options.class,
                        OperaOptions.class);
        if (optionsFromAnnotatedField != null) {
            operaOptions = optionsFromAnnotatedField.merge(operaOptions);
        }
    }

    return operaOptions;
}
 
Example 11
Source File: AnnotatedArgumentBuilder.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
protected Object defaultValue(Parameter parameter, AnnotatedType parameterType, GlobalEnvironment environment) {

        GraphQLArgument meta = parameter.getAnnotation(GraphQLArgument.class);
        if (meta == null) return null;
        try {
            return defaultValueProvider(meta.defaultValueProvider(), environment)
                    .getDefaultValue(parameter, environment.getMappableInputType(parameterType), ReservedStrings.decode(environment.messageBundle.interpolate(meta.defaultValue())));
        } catch (ReflectiveOperationException e) {
            throw new IllegalArgumentException(
                    meta.defaultValueProvider().getName() + " must expose a public default constructor, or a constructor accepting " + GlobalEnvironment.class.getName(), e);
        }
    }
 
Example 12
Source File: TypeUtil.java    From fastquery with Apache License 2.0 5 votes vote down vote up
/**
 * 查询标识有指定注解的参数
 *
 * @param clazz      待查找的类型
 * @param parameters 参数类型集
 * @return 参数类型
 */
public static Parameter findParameter(Class<? extends Annotation> clazz, Parameter[] parameters) {
    for (Parameter parameter : parameters) {
        if (parameter.getAnnotation(clazz) != null) {
            return parameter;
        }
    }
    return null;
}
 
Example 13
Source File: ApiBuilder.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
private JaxrsPathParameter jaxrsPathParameter(Class<?> clz, Method method, Parameter parameter) throws Exception {
	JaxrsParameterDescribe jaxrsParameterDescribe = parameter.getAnnotation(JaxrsParameterDescribe.class);
	PathParam pathParam = parameter.getAnnotation(PathParam.class);
	JaxrsPathParameter o = new JaxrsPathParameter();
	o.setName(pathParam.value());
	if (null != jaxrsParameterDescribe) {
		o.setDescription(jaxrsParameterDescribe.value());
	} else {
		logger.print("类: {}, 方法: {} ,未设置参数 {} 的JaxrsParameterDescribe.", clz.getName(), method.getName(),
				pathParam.value());
		o.setDescription("");
	}
	o.setType(this.getJaxrsParameterType(parameter));
	return o;
}
 
Example 14
Source File: EndpointValidator.java    From msf4j with Apache License 2.0 5 votes vote down vote up
private boolean validateOnStringMethod(Object webSocketEndpoint)
        throws WebSocketMethodParameterException, WebSocketEndpointMethodReturnTypeException {
    EndpointDispatcher dispatcher = new EndpointDispatcher();
    Method method;
    if (dispatcher.getOnStringMessageMethod(webSocketEndpoint).isPresent()) {
        method = dispatcher.getOnStringMessageMethod(webSocketEndpoint).get();
    } else {
        return true;
    }
    validateReturnType(method);
    boolean foundPrimaryString = false;
    for (Parameter parameter: method.getParameters()) {
        Class<?> paraType = parameter.getType();
        if (paraType == String.class) {
            if (parameter.getAnnotation(PathParam.class) == null) {
                if (foundPrimaryString) {
                    throw new WebSocketMethodParameterException("Invalid parameter found on text message method: " +
                                                                        "More than one string parameter without " +
                                                                        "@PathParam annotation.");
                }
                foundPrimaryString = true;
            }
        } else if (paraType != WebSocketConnection.class) {
            throw new WebSocketMethodParameterException("Invalid parameter found on text message method: " +
                                                                paraType);
        }
    }
    return foundPrimaryString;
}
 
Example 15
Source File: FunctionMappingExtractor.java    From flink with Apache License 2.0 5 votes vote down vote up
private static Optional<FunctionArgumentTemplate> tryExtractInputGroupArgument(Method method, int paramPos) {
	final Parameter parameter = method.getParameters()[paramPos];
	final DataTypeHint hint = parameter.getAnnotation(DataTypeHint.class);
	if (hint != null) {
		final DataTypeTemplate template = DataTypeTemplate.fromAnnotation(hint, null);
		if (template.inputGroup != null) {
			return Optional.of(FunctionArgumentTemplate.of(template.inputGroup));
		}
	}
	return Optional.empty();
}
 
Example 16
Source File: SpringAnnotationProcessorTest.java    From servicecomb-toolkit with Apache License 2.0 4 votes vote down vote up
@Test
public void parseParameter() throws NoSuchMethodException {
  Class<ParamAnnotationResource> paramAnnotationResourceClass = ParamAnnotationResource.class;
  OasContext oasContext = new OasContext(null);
  OperationContext operationContext;
  ParameterContext parameterContext;

  RequestParamAnnotationProcessor requestParamAnnotationProcessor = new RequestParamAnnotationProcessor();
  Method requestParamMethod = paramAnnotationResourceClass.getMethod("requestParam", String.class);
  Parameter requestParamMethodParam = requestParamMethod.getParameters()[0];
  RequestParam requestParamAnnotation = requestParamMethodParam
      .getAnnotation(RequestParam.class);
  operationContext = new OperationContext(requestParamMethod, oasContext);
  parameterContext = new ParameterContext(operationContext, requestParamMethodParam);
  requestParamAnnotationProcessor.process(requestParamAnnotation, parameterContext);
  io.swagger.v3.oas.models.parameters.Parameter oasParameter = parameterContext.toParameter();
  Assert.assertNull(parameterContext.getDefaultValue());
  Assert.assertNull(oasParameter.getSchema().getDefault());

  PathVariableAnnotationProcessor pathVariableAnnotationProcessor = new PathVariableAnnotationProcessor();
  Method pathVariableMethod = paramAnnotationResourceClass.getMethod("pathVariable", String.class);
  Parameter pathVariableMethodParam = pathVariableMethod.getParameters()[0];
  PathVariable pathVariableAnnotation = pathVariableMethodParam
      .getAnnotation(PathVariable.class);
  operationContext = new OperationContext(pathVariableMethod, oasContext);
  parameterContext = new ParameterContext(operationContext, pathVariableMethodParam);
  pathVariableAnnotationProcessor.process(pathVariableAnnotation, parameterContext);
  parameterContext.toParameter();
  Assert.assertTrue(parameterContext.isRequired());

  RequestPartAnnotationProcessor requestPartAnnotationProcessor = new RequestPartAnnotationProcessor();
  Method requestPartMethod = paramAnnotationResourceClass.getMethod("requestPart", MultipartFile.class);
  Parameter requestPartMethodParam = requestPartMethod.getParameters()[0];
  RequestPart requestPartParamAnnotation = requestPartMethodParam
      .getAnnotation(RequestPart.class);
  operationContext = new OperationContext(requestPartMethod, oasContext);
  parameterContext = new ParameterContext(operationContext, requestPartMethodParam);
  requestPartAnnotationProcessor.process(requestPartParamAnnotation, parameterContext);
  oasParameter = parameterContext.toParameter();
  Assert.assertNull(parameterContext.getDefaultValue());
  Assert.assertEquals(FileSchema.class, oasParameter.getSchema().getClass());

  RequestHeaderAnnotationProcessor requestHeaderAnnotationProcessor = new RequestHeaderAnnotationProcessor();
  Method requestHeaderMethod = paramAnnotationResourceClass.getMethod("requestHeader", String.class);
  Parameter requestHeaderMethodParam = requestHeaderMethod.getParameters()[0];
  RequestHeader requestHeaderParamAnnotation = requestHeaderMethodParam
      .getAnnotation(RequestHeader.class);
  operationContext = new OperationContext(requestPartMethod, oasContext);
  parameterContext = new ParameterContext(operationContext, requestHeaderMethodParam);
  requestHeaderAnnotationProcessor.process(requestHeaderParamAnnotation, parameterContext);
  oasParameter = parameterContext.toParameter();
  Assert.assertNull(parameterContext.getDefaultValue());
  Assert.assertNull(oasParameter.getSchema().getDefault());

  RequestBodyAnnotationProcessor requestBodyAnnotationProcessor = new RequestBodyAnnotationProcessor();
  Method requestBodyMethod = paramAnnotationResourceClass.getMethod("requestBody", String.class);
  Parameter requestBodyMethodParam = requestBodyMethod.getParameters()[0];
  RequestBody requestBodyParamAnnotation = requestBodyMethodParam
      .getAnnotation(RequestBody.class);
  operationContext = new OperationContext(requestBodyMethod, oasContext);
  parameterContext = new ParameterContext(operationContext, requestBodyMethodParam);
  requestBodyAnnotationProcessor.process(requestBodyParamAnnotation, parameterContext);
  parameterContext.toParameter();
  Assert.assertTrue(parameterContext.isRequired());
}
 
Example 17
Source File: PoseidonLegoSet.java    From Poseidon with Apache License 2.0 4 votes vote down vote up
private void resolveInjectableConstructorDependencies(Constructor<?> constructor, Object[] initParams, int offset, Optional<Request> request) throws MissingInformationException, ElementNotFoundException {
    for (int i = offset; i < constructor.getParameterCount(); i++) {
        final Parameter constructorParameter = constructor.getParameters()[i];
        final RequestAttribute requestAttribute = constructorParameter.getAnnotation(RequestAttribute.class);
        final com.flipkart.poseidon.datasources.ServiceClient serviceClientAttribute = constructorParameter.getAnnotation(com.flipkart.poseidon.datasources.ServiceClient.class);
        final SystemDataSource systemDataSourceAttribute = constructorParameter.getAnnotation(SystemDataSource.class);
        if (requestAttribute != null) {
            final String attributeName = StringUtils.isNullOrEmpty(requestAttribute.value()) ? constructorParameter.getName() : requestAttribute.value();
            initParams[i] = request.map(r -> r.getAttribute(attributeName)).map(attr -> {
                if (constructorParameter.getType().isAssignableFrom(attr.getClass())) {
                    return attr;
                } else {
                    return mapper.convertValue(attr, mapper.constructType(constructorParameter.getParameterizedType()));
                }
            }).orElse(null);
        } else if (serviceClientAttribute != null) {
            ServiceClient serviceClient = serviceClientsByName.get(constructor.getParameterTypes()[i].getName());
            if (serviceClient == null) {
                throw new ElementNotFoundException("Unable to find ServiceClient for class = " + constructor.getParameterTypes()[i]);
            }
            initParams[i] = serviceClient;
        } else if (systemDataSourceAttribute != null) {
            final DataSource<?> systemDataSource = systemDataSources.get(systemDataSourceAttribute.value());
            if (systemDataSource == null) {
                throw new ElementNotFoundException("Unable to find SystemDataSource for id = " + systemDataSourceAttribute.value());
            }
            initParams[i] = systemDataSource;
        } else {
            final Qualifier qualifier = constructorParameter.getAnnotation(Qualifier.class);
            String beanName = null;
            if (qualifier != null && !StringUtils.isNullOrEmpty(qualifier.value())) {
                beanName = qualifier.value();
            }

            initParams[i] = beanName == null ? context.getBean(constructor.getParameterTypes()[i]) : context.getBean(beanName, constructor.getParameterTypes()[i]);
            if (initParams[i] == null) {
                throw new MissingInformationException("Unmet dependency for constructor " + constructor.getName() + ": " + constructor.getParameterTypes()[i].getCanonicalName());
            }
        }
    }
}
 
Example 18
Source File: AnnotatedArgumentBuilder.java    From graphql-spqr with Apache License 2.0 4 votes vote down vote up
protected String getArgumentDescription(Parameter parameter, AnnotatedType parameterType, MessageBundle messageBundle) {
    GraphQLArgument meta = parameter.getAnnotation(GraphQLArgument.class);
    return meta != null ? messageBundle.interpolate(meta.description()) : null;
}
 
Example 19
Source File: LogOperationAspect.java    From GreenSummer with GNU Lesser General Public License v2.1 4 votes vote down vote up
private StringBuilder extractArguments(
    Method method,
    Object[] args) {
  StringBuilder theSB = new StringBuilder();
  try {
    Parameter[] parameters = method.getParameters();
    boolean added = false;
    if (parameters != null && parameters.length > 0) {
      theSB.append(": ");
      for (int i = 0; i < parameters.length; i++) {
        Parameter parameter = parameters[i];
        if (parameter.getAnnotation(DontLog.class) == null && args[i] != null) {
          final Class<?> parameterType = parameter.getType();
          final boolean isLogable = Logable.class.isAssignableFrom(parameterType);
          //@formatter:off
                      if (
                          parameterType.isPrimitive()
                          || parameterType.isEnum()
                          || CharSequence.class.isAssignableFrom(parameterType)
                          || isLogable
                          ) {
                          addParameterName(theSB, added, parameter);
                          if(isLogable) {
                            theSB.append(((Logable)args[i]).formatted());
                          } else {
                            theSB.append(args[i].toString());
                          }
                          added = true;
                      } else if (
                              parameterType.isArray()
                              && (
                                  parameterType.getComponentType().isPrimitive()
                                  || parameterType.getComponentType().isEnum()
                                  || CharSequence.class.isAssignableFrom(parameterType.getComponentType())
                              )
                      ) {
                          addParameterName(theSB, added, parameter);
                          int lenght = Array.getLength(args[i]);
                          StringJoiner st = new StringJoiner(",");
                          for(int j = 0 ; j < lenght ; j++) {
                            st.add(Array.get(args[i], j).toString());
                          }
                          theSB.append(st.toString());
                          added = true;
                      }
                      //@formatter:on
        }
      }
    }
  } catch (Exception e) {
    log.error("Error extracting arguments from method", e);
  }
  return theSB;
}
 
Example 20
Source File: TempDirectoryExtension.java    From pdfcompare with Apache License 2.0 4 votes vote down vote up
@Override
public boolean supportsParameter(ParameterContext paramContext, ExtensionContext extensionContext) throws ParameterResolutionException {
    final Parameter parameter = paramContext.getParameter();
    return parameter.getAnnotation(TempDirectory.class) != null && Path.class.equals(parameter.getType());
}