Java Code Examples for org.springframework.core.MethodParameter#getParameterName()

The following examples show how to use org.springframework.core.MethodParameter#getParameterName() . 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: RequestParamMapMethodArgumentResolver.java    From netty-websocket-spring-boot-starter with Apache License 2.0 6 votes vote down vote up
@Override
public Object resolveArgument(MethodParameter parameter, Channel channel, Object object) throws Exception {
    RequestParam ann = parameter.getParameterAnnotation(RequestParam.class);
    String name = ann.name();
    if (name.isEmpty()) {
        name = parameter.getParameterName();
        if (name == null) {
            throw new IllegalArgumentException(
                    "Name for argument type [" + parameter.getNestedParameterType().getName() +
                            "] not available, and parameter name information not found in class file either.");
        }
    }

    if (!channel.hasAttr(REQUEST_PARAM)) {
        QueryStringDecoder decoder = new QueryStringDecoder(((FullHttpRequest) object).uri());
        channel.attr(REQUEST_PARAM).set(decoder.parameters());
    }

    Map<String, List<String>> requestParams = channel.attr(REQUEST_PARAM).get();
    MultiValueMap multiValueMap = new LinkedMultiValueMap(requestParams);
    if (MultiValueMap.class.isAssignableFrom(parameter.getParameterType())) {
        return multiValueMap;
    } else {
        return multiValueMap.toSingleValueMap();
    }
}
 
Example 2
Source File: HttpEntityMethodProcessor.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
@Nullable
public Object resolveArgument(MethodParameter parameter, @Nullable ModelAndViewContainer mavContainer,
		NativeWebRequest webRequest, @Nullable WebDataBinderFactory binderFactory)
		throws IOException, HttpMediaTypeNotSupportedException {

	ServletServerHttpRequest inputMessage = createInputMessage(webRequest);
	Type paramType = getHttpEntityType(parameter);
	if (paramType == null) {
		throw new IllegalArgumentException("HttpEntity parameter '" + parameter.getParameterName() +
				"' in method " + parameter.getMethod() + " is not parameterized");
	}

	Object body = readWithMessageConverters(webRequest, parameter, paramType);
	if (RequestEntity.class == parameter.getParameterType()) {
		return new RequestEntity<>(body, inputMessage.getHeaders(),
				inputMessage.getMethod(), inputMessage.getURI());
	}
	else {
		return new HttpEntity<>(body, inputMessage.getHeaders());
	}
}
 
Example 3
Source File: HttpEntityMethodProcessor.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
@Nullable
public Object resolveArgument(MethodParameter parameter, @Nullable ModelAndViewContainer mavContainer,
		NativeWebRequest webRequest, @Nullable WebDataBinderFactory binderFactory)
		throws IOException, HttpMediaTypeNotSupportedException {

	ServletServerHttpRequest inputMessage = createInputMessage(webRequest);
	Type paramType = getHttpEntityType(parameter);
	if (paramType == null) {
		throw new IllegalArgumentException("HttpEntity parameter '" + parameter.getParameterName() +
				"' in method " + parameter.getMethod() + " is not parameterized");
	}

	Object body = readWithMessageConverters(webRequest, parameter, paramType);
	if (RequestEntity.class == parameter.getParameterType()) {
		return new RequestEntity<>(body, inputMessage.getHeaders(),
				inputMessage.getMethod(), inputMessage.getURI());
	}
	else {
		return new HttpEntity<>(body, inputMessage.getHeaders());
	}
}
 
Example 4
Source File: PathVariableMapMethodArgumentResolver.java    From netty-websocket-spring-boot-starter with Apache License 2.0 6 votes vote down vote up
@Override
public Object resolveArgument(MethodParameter parameter, Channel channel, Object object) throws Exception {
    PathVariable ann = parameter.getParameterAnnotation(PathVariable.class);
    String name = ann.name();
    if (name.isEmpty()) {
        name = parameter.getParameterName();
        if (name == null) {
            throw new IllegalArgumentException(
                    "Name for argument type [" + parameter.getNestedParameterType().getName() +
                            "] not available, and parameter name information not found in class file either.");
        }
    }
    Map<String, String> uriTemplateVars = channel.attr(URI_TEMPLATE).get();
    if (!CollectionUtils.isEmpty(uriTemplateVars)) {
        return uriTemplateVars;
    } else {
        return Collections.emptyMap();
    }
}
 
Example 5
Source File: HttpEntityMethodProcessor.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
private Type getHttpEntityType(MethodParameter parameter) {
	Assert.isAssignable(HttpEntity.class, parameter.getParameterType());
	Type parameterType = parameter.getGenericParameterType();
	if (parameterType instanceof ParameterizedType) {
		ParameterizedType type = (ParameterizedType) parameterType;
		if (type.getActualTypeArguments().length != 1) {
			throw new IllegalArgumentException("Expected single generic parameter on '" +
					parameter.getParameterName() + "' in method " + parameter.getMethod());
		}
		return type.getActualTypeArguments()[0];
	}
	else if (parameterType instanceof Class) {
		return Object.class;
	}
	throw new IllegalArgumentException("HttpEntity parameter '" + parameter.getParameterName() +
			"' in method " + parameter.getMethod() + " is not parameterized");
}
 
Example 6
Source File: HandlerMethodMultiArgumentResolver.java    From distributed-transaction-process with MIT License 6 votes vote down vote up
@Override
    public Object resolveArgument(
            MethodParameter parameter, ModelAndViewContainer mavContainer,
            NativeWebRequest webRequest, WebDataBinderFactory binderFactory)
            throws Exception {

//        String json = getRequestInfo(webRequest);
//        Class<?> parameterType = parameter.getParameterType();

        JSONObject para = getRequestInfo1(webRequest);
        Class<?> type = parameter.getParameterType();
        String name = parameter.getParameterName();
        if (null != para && para.containsKey(name)) {
            return JSON.parseObject(para.getString(name), type);
        }
        return null;
    }
 
Example 7
Source File: AbstractNamedValueMethodArgumentResolver.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Fall back on the parameter name from the class file if necessary and
 * replace {@link ValueConstants#DEFAULT_NONE} with null.
 */
private NamedValueInfo updateNamedValueInfo(MethodParameter parameter, NamedValueInfo info) {
	String name = info.name;
	if (info.name.isEmpty()) {
		name = parameter.getParameterName();
		if (name == null) {
			Class<?> type = parameter.getParameterType();
			throw new IllegalArgumentException(
					"Name for argument of type [" + type.getName() + "] not specified, " +
							"and parameter name information not found in class file either.");
		}
	}
	return new NamedValueInfo(name, info.required,
			ValueConstants.DEFAULT_NONE.equals(info.defaultValue) ? null : info.defaultValue);
}
 
Example 8
Source File: AbstractParameterSnippet.java    From spring-auto-restdocs with Apache License 2.0 5 votes vote down vote up
private void addFieldDescriptor(HandlerMethod handlerMethod,
        JavadocReader javadocReader, ConstraintReader constraintReader,
        FieldDescriptors fieldDescriptors, MethodParameter param, A annot) {
    String javaParameterName = param.getParameterName();
    String pathName = getPath(annot);

    String parameterName = hasLength(pathName) ? pathName : javaParameterName;
    String parameterTypeName = determineTypeName(param.nestedIfOptional().getNestedParameterType());
    String description = javadocReader.resolveMethodParameterComment(
            handlerMethod.getBeanType(), handlerMethod.getMethod().getName(),
            javaParameterName);

    FieldDescriptor descriptor = fieldWithPath(parameterName)
            .type(parameterTypeName)
            .description(description);

    Attribute constraints = constraintAttribute(param, constraintReader);
    Attribute optionals = optionalsAttribute(param, annot);
    Attribute deprecated = deprecatedAttribute(param, annot, javadocReader);
    final Attribute defaultValue = defaultValueAttribute(annot);
    if (defaultValue == null) {
        descriptor.attributes(constraints, optionals, deprecated);
    } else {
        descriptor.attributes(constraints, optionals, deprecated, defaultValue);
    }

    fieldDescriptors.putIfAbsent(parameterName, descriptor);
}
 
Example 9
Source File: AbstractNamedValueMethodArgumentResolver.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new NamedValueInfo based on the given NamedValueInfo with sanitized values.
 */
private NamedValueInfo updateNamedValueInfo(MethodParameter parameter, NamedValueInfo info) {
	String name = info.name;
	if (info.name.length() == 0) {
		name = parameter.getParameterName();
		if (name == null) {
			throw new IllegalArgumentException("Name for argument type [" + parameter.getParameterType().getName() +
					"] not available, and parameter name information not found in class file either.");
		}
	}
	String defaultValue = (ValueConstants.DEFAULT_NONE.equals(info.defaultValue) ? null : info.defaultValue);
	return new NamedValueInfo(name, info.required, defaultValue);
}
 
Example 10
Source File: PathVariableMethodArgumentResolver.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public void contributeMethodArgument(MethodParameter parameter, Object value,
		UriComponentsBuilder builder, Map<String, Object> uriVariables, ConversionService conversionService) {

	if (Map.class.isAssignableFrom(parameter.nestedIfOptional().getNestedParameterType())) {
		return;
	}

	PathVariable ann = parameter.getParameterAnnotation(PathVariable.class);
	String name = (ann != null && !StringUtils.isEmpty(ann.value()) ? ann.value() : parameter.getParameterName());
	String formatted = formatUriValue(conversionService, new TypeDescriptor(parameter.nestedIfOptional()), value);
	uriVariables.put(name, formatted);
}
 
Example 11
Source File: RequestParamMethodArgumentResolver.java    From netty-websocket-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
@Override
public Object resolveArgument(MethodParameter parameter, Channel channel, Object object) throws Exception {
    RequestParam ann = parameter.getParameterAnnotation(RequestParam.class);
    String name = ann.name();
    if (name.isEmpty()) {
        name = parameter.getParameterName();
        if (name == null) {
            throw new IllegalArgumentException(
                    "Name for argument type [" + parameter.getNestedParameterType().getName() +
                            "] not available, and parameter name information not found in class file either.");
        }
    }

    if (!channel.hasAttr(REQUEST_PARAM)) {
        QueryStringDecoder decoder = new QueryStringDecoder(((FullHttpRequest) object).uri());
        channel.attr(REQUEST_PARAM).set(decoder.parameters());
    }

    Map<String, List<String>> requestParams = channel.attr(REQUEST_PARAM).get();
    List<String> arg = (requestParams != null ? requestParams.get(name) : null);
    TypeConverter typeConverter = beanFactory.getTypeConverter();
    if (arg == null) {
        if ("\n\t\t\n\t\t\n\uE000\uE001\uE002\n\t\t\t\t\n".equals(ann.defaultValue())) {
            return null;
        }else {
            return typeConverter.convertIfNecessary(ann.defaultValue(), parameter.getParameterType());
        }
    }
    if (List.class.isAssignableFrom(parameter.getParameterType())) {
        return typeConverter.convertIfNecessary(arg, parameter.getParameterType());
    } else {
        return typeConverter.convertIfNecessary(arg.get(0), parameter.getParameterType());
    }
}
 
Example 12
Source File: PathVariableMethodArgumentResolver.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public void contributeMethodArgument(MethodParameter parameter, Object value,
		UriComponentsBuilder builder, Map<String, Object> uriVariables, ConversionService conversionService) {

	if (Map.class.isAssignableFrom(parameter.getParameterType())) {
		return;
	}

	PathVariable ann = parameter.getParameterAnnotation(PathVariable.class);
	String name = (ann == null || StringUtils.isEmpty(ann.value()) ? parameter.getParameterName() : ann.value());
	value = formatUriValue(conversionService, new TypeDescriptor(parameter), value);
	uriVariables.put(name, value);
}
 
Example 13
Source File: DataRestRequestBuilder.java    From springdoc-openapi with Apache License 2.0 5 votes vote down vote up
/**
 * Build common parameters.
 *
 * @param domainType the domain type
 * @param openAPI the open api
 * @param requestMethod the request method
 * @param methodAttributes the method attributes
 * @param operation the operation
 * @param pNames the p names
 * @param parameters the parameters
 */
public void buildCommonParameters(Class<?> domainType, OpenAPI openAPI, RequestMethod requestMethod, MethodAttributes methodAttributes, Operation operation, String[] pNames, MethodParameter[] parameters) {
	parameters = DelegatingMethodParameter.customize(pNames, parameters);
	for (MethodParameter methodParameter : parameters) {
		final String pName = methodParameter.getParameterName();
		ParameterInfo parameterInfo = new ParameterInfo(pName, methodParameter);
		if (isParamToIgnore(methodParameter)) {
			if (PersistentEntityResource.class.equals(methodParameter.getParameterType())) {
				Schema<?> schema = SpringDocAnnotationsUtils.resolveSchemaFromType(domainType, openAPI.getComponents(), null, methodParameter.getParameterAnnotations());
				parameterInfo.setParameterModel(new Parameter().schema(schema));
			}
			else if (methodParameter.getParameterAnnotation(BackendId.class) != null) {
				parameterInfo.setParameterModel(new Parameter().name("id").in(ParameterIn.PATH.toString()).schema(new StringSchema()));
			}
			Parameter parameter;
			io.swagger.v3.oas.annotations.Parameter parameterDoc = AnnotatedElementUtils.findMergedAnnotation(
					AnnotatedElementUtils.forAnnotations(methodParameter.getParameterAnnotations()),
					io.swagger.v3.oas.annotations.Parameter.class);
			if (parameterDoc != null) {
				if (parameterDoc.hidden() || parameterDoc.schema().hidden())
					continue;
				parameter = parameterBuilder.buildParameterFromDoc(parameterDoc, openAPI.getComponents(), methodAttributes.getJsonViewAnnotation());
				parameterInfo.setParameterModel(parameter);
			}
			parameter = requestBuilder.buildParams(parameterInfo, openAPI.getComponents(), requestMethod, null);

			addParameters(openAPI, requestMethod, methodAttributes, operation, methodParameter, parameterInfo, parameter);
		}
	}
}
 
Example 14
Source File: AbstractNamedValueMethodArgumentResolver.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new NamedValueInfo based on the given NamedValueInfo with sanitized values.
 */
private NamedValueInfo updateNamedValueInfo(MethodParameter parameter, NamedValueInfo info) {
	String name = info.name;
	if (info.name.length() == 0) {
		name = parameter.getParameterName();
		if (name == null) {
			throw new IllegalArgumentException("Name for argument type [" + parameter.getParameterType().getName() +
					"] not available, and parameter name information not found in class file either.");
		}
	}
	String defaultValue = (ValueConstants.DEFAULT_NONE.equals(info.defaultValue) ? null : info.defaultValue);
	return new NamedValueInfo(name, info.required, defaultValue);
}
 
Example 15
Source File: AbstractNamedValueArgumentResolver.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Create a new NamedValueInfo based on the given NamedValueInfo with
 * sanitized values.
 */
private NamedValueInfo updateNamedValueInfo(MethodParameter parameter, NamedValueInfo info) {
	String name = info.name;
	if (info.name.isEmpty()) {
		name = parameter.getParameterName();
		if (name == null) {
			String type = parameter.getNestedParameterType().getName();
			throw new IllegalArgumentException("Name for argument type [" + type + "] not " +
					"available, and parameter name information not found in class file either.");
		}
	}
	String defaultValue = (ValueConstants.DEFAULT_NONE.equals(info.defaultValue) ? null : info.defaultValue);
	return new NamedValueInfo(name, info.required, defaultValue);
}
 
Example 16
Source File: NodeServiceImpl.java    From java-trader with Apache License 2.0 4 votes vote down vote up
/**
 * 根据path找到并发现REST Controller
 */
public static NodeMessage controllerInvoke(RequestMappingHandlerMapping requestMappingHandlerMapping, NodeMessage reqMessage) {
    String path = ConversionUtil.toString(reqMessage.getField(NodeMessage.FIELD_PATH));
    //匹配合适的
    Object result = null;
    Throwable t = null;
    RequestMappingInfo reqMappingInfo=null;
    HandlerMethod reqHandlerMethod = null;
    Map<RequestMappingInfo, HandlerMethod> map = requestMappingHandlerMapping.getHandlerMethods();
    for(RequestMappingInfo info:map.keySet()) {
        List<String> matches = info.getPatternsCondition().getMatchingPatterns(path);
        if ( matches.isEmpty() ) {
            continue;
        }
        reqMappingInfo = info;
        reqHandlerMethod = map.get(info);
        break;
    }

    if ( reqMappingInfo==null ) {
        t = new Exception("Controller for "+path+" is not found");
        logger.error("Controller for "+path+" is not found");
    } else {
        MethodParameter[] methodParams = reqHandlerMethod.getMethodParameters();
        Object[] params = new Object[methodParams.length];
        try{
            for(int i=0;i<methodParams.length;i++) {
                MethodParameter param = methodParams[i];
                String paramName = param.getParameterName();
                params[i] = ConversionUtil.toType(param.getParameter().getType(), reqMessage.getField(paramName));
                if ( params[i]==null && !param.isOptional() ) {
                    throw new IllegalArgumentException("Method parameter "+paramName+" is missing");
                }
            }
            result = reqHandlerMethod.getMethod().invoke(reqHandlerMethod.getBean(), params);
        }catch(Throwable ex ) {
            if ( ex instanceof InvocationTargetException ) {
                t = ((InvocationTargetException)ex).getTargetException();
            }else {
                t = ex;
            }
            logger.error("Invoke controller "+path+" with params "+Arrays.asList(params)+" failed: "+t, t);
        }
    }
    NodeMessage respMessage = reqMessage.createResponse();
    if ( t!=null ) {
        respMessage.setErrCode(-1);
        respMessage.setErrMsg(t.toString());
    } else {
        respMessage.setField(NodeMessage.FIELD_RESULT, JsonUtil.object2json(result));
    }
    return respMessage;
}
 
Example 17
Source File: PayloadArgumentResolver.java    From java-technology-stack with MIT License 4 votes vote down vote up
private String getParameterName(MethodParameter param) {
	String paramName = param.getParameterName();
	return (paramName != null ? paramName : "Arg " + param.getParameterIndex());
}
 
Example 18
Source File: PayloadArgumentResolver.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
private String getParameterName(MethodParameter param) {
	String paramName = param.getParameterName();
	return (paramName != null ? paramName : "Arg " + param.getParameterIndex());
}
 
Example 19
Source File: StatefulFactory.java    From statefulj with Apache License 2.0 4 votes vote down vote up
@Override
public Object getSuggestedValue(DependencyDescriptor descriptor) {
	Object suggested = null;
	Field field = descriptor.getField();
	MethodParameter methodParameter = descriptor.getMethodParameter();

	boolean isStatefulFSM = false;
	String controllerId = null;
	Type genericFieldType = null;
	String fieldName = null;
	org.statefulj.framework.core.annotations.FSM fsmAnnotation = null;

	// If this is a StatefulFSM, parse out the Annotation and Type information
	//
	if (field != null) {
		if (isStatefulFSM(field)) {
			fsmAnnotation = field.getAnnotation(org.statefulj.framework.core.annotations.FSM.class);
			genericFieldType = field.getGenericType();
			fieldName = field.getName();
			isStatefulFSM = true;
		}
	} else if (methodParameter != null) {
		if (isStatefulFSM(methodParameter)) {
			fsmAnnotation = methodParameter.getParameterAnnotation(org.statefulj.framework.core.annotations.FSM.class);
			genericFieldType = methodParameter.getGenericParameterType();
			fieldName = methodParameter.getParameterName();
			isStatefulFSM = true;
		}
	}

	// If this is a StatefulFSM field, then resolve bean reference
	//
	if (isStatefulFSM) {

		// Determine the controllerId - either explicit or derived
		//
		controllerId = getControllerId(fsmAnnotation);
		if (StringUtils.isEmpty(controllerId)) {

			// Get the Managed Class
			//
			Class<?> managedClass = getManagedClass(fieldName, genericFieldType);

			// Fetch the Controller from the mapping
			//
			controllerId = deriveControllerId(fieldName, managedClass);
		}

		ReferenceFactory refFactory = new ReferenceFactoryImpl(controllerId);
		suggested = appContext.getBean(refFactory.getStatefulFSMId());
	}


	return (suggested != null) ? suggested : super.getSuggestedValue(descriptor);
}
 
Example 20
Source File: PayloadMethodArgumentResolver.java    From spring-analysis-note with MIT License 4 votes vote down vote up
private String getParameterName(MethodParameter param) {
	String paramName = param.getParameterName();
	return (paramName != null ? paramName : "Arg " + param.getParameterIndex());
}