List of usage examples for org.springframework.core MethodParameter getParameterAnnotation
@SuppressWarnings("unchecked") @Nullable public <A extends Annotation> A getParameterAnnotation(Class<A> annotationType)
From source file:com.fengduo.bee.commons.component.FormModelMethodArgumentResolver.java
@SuppressWarnings("unused") private ServletRequest prepareServletRequest(Object target, NativeWebRequest request, MethodParameter parameter) { String modelPrefixName = parameter.getParameterAnnotation(FormBean.class).value(); HttpServletRequest nativeRequest = (HttpServletRequest) request.getNativeRequest(); MultipartRequest multipartRequest = WebUtils.getNativeRequest(nativeRequest, MultipartRequest.class); MockHttpServletRequest mockRequest = null; if (multipartRequest != null) { MockMultipartHttpServletRequest mockMultipartRequest = new MockMultipartHttpServletRequest(); for (MultipartFile file : multipartRequest.getFileMap().values()) { mockMultipartRequest.addFile( new MultipartFileWrapper(getNewParameterName(file.getName(), modelPrefixName), file)); }/* w ww . ja v a 2s . c o m*/ mockRequest = mockMultipartRequest; } else { mockRequest = new MockHttpServletRequest(); } for (Entry<String, String> entry : getUriTemplateVariables(request).entrySet()) { String parameterName = entry.getKey(); String value = entry.getValue(); if (isFormModelAttribute(parameterName, modelPrefixName)) { mockRequest.setParameter(getNewParameterName(parameterName, modelPrefixName), value); } } for (Object parameterEntry : nativeRequest.getParameterMap().entrySet()) { Entry<String, String[]> entry = (Entry<String, String[]>) parameterEntry; String parameterName = entry.getKey(); String[] value = entry.getValue(); if (isFormModelAttribute(parameterName, modelPrefixName)) { mockRequest.setParameter(getNewParameterName(parameterName, modelPrefixName), value); } } return mockRequest; }
From source file:org.zht.framework.web.bind.resolver.FormModelMethodArgumentResolver.java
/** * Resolve the argument from the model or if not found instantiate it with * its default if it is available. The model attribute is then populated * with request values via data binding and optionally validated * if {@code @java.validation.Valid} is present on the argument. * * @throws org.springframework.validation.BindException * if data binding and validation result in an error * and the next method parameter is not of type {@link org.springframework.validation.Errors}. * @throws Exception if WebDataBinder initialization fails. *//* w w w . j a v a2s . co m*/ public final Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest request, WebDataBinderFactory binderFactory) throws Exception { String name = parameter.getParameterAnnotation(FormModel.class).value(); Object target = (mavContainer.containsAttribute(name)) ? mavContainer.getModel().get(name) : createAttribute(name, parameter, binderFactory, request); WebDataBinder binder = binderFactory.createBinder(request, target, name); target = binder.getTarget(); if (target != null) { bindRequestParameters(mavContainer, binderFactory, binder, request, parameter); validateIfApplicable(binder, parameter); if (binder.getBindingResult().hasErrors()) { List<BindingResult> list = (List<BindingResult>) request .getAttribute(ValidateConstant.BINDING_RESULT_LIST_NAME, Integer.MAX_VALUE / 2 + 1); if (null == list) { list = new ArrayList<BindingResult>(); request.setAttribute(ValidateConstant.BINDING_RESULT_LIST_NAME, list, 0); } list.add(binder.getBindingResult()); request.setAttribute(ValidateConstant.BINDING_RESULT_HAS_ERROR, true, 0); // if (isBindExceptionRequired(binder, parameter)) { // throw new BindException(binder.getBindingResult()); // } } } target = binder.convertIfNecessary(binder.getTarget(), parameter.getParameterType()); mavContainer.addAttribute(name, target); return target; }
From source file:com.fengduo.bee.commons.component.FormModelMethodArgumentResolver.java
/** * Resolve the argument from the model or if not found instantiate it with its default if it is available. The model * attribute is then populated with request values via data binding and optionally validated if * {@code @java.validation.Valid} is present on the argument. * //from www . jav a2 s . c o m * @throws org.springframework.validation.BindException if data binding and validation result in an error and the * next method parameter is not of type {@link org.springframework.validation.Errors}. * @throws Exception if WebDataBinder initialization fails. */ public final Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest request, WebDataBinderFactory binderFactory) throws Exception { String name = parameter.getParameterAnnotation(FormBean.class).value(); Object target = (mavContainer.containsAttribute(name)) ? mavContainer.getModel().get(name) : createAttribute(name, parameter, binderFactory, request); WebDataBinder binder = binderFactory.createBinder(request, target, name); target = binder.getTarget(); if (target != null) { bindRequestParameters(mavContainer, binderFactory, binder, request, parameter); validateIfApplicable(binder, parameter); if (binder.getBindingResult().hasErrors()) { if (isBindExceptionRequired(binder, parameter)) { throw new BindException(binder.getBindingResult()); } } } target = binder.convertIfNecessary(binder.getTarget(), parameter.getParameterType()); mavContainer.addAttribute(name, target); return target; }
From source file:org.jm.swagger.SpringMVCAPIReader.java
/** * Create {@link DocumentationParameter} from {@link MethodParameter} * //from w w w .jav a 2 s.co m * @param methodParamater * @return */ private DocumentationParameter convertMethodParameter(MethodParameter methodParamater) { DocumentationParameter documentationParameter = new DocumentationParameter(); documentationParameter.setDataType(methodParamater.getParameterType().getSimpleName()); methodParamater.initParameterNameDiscovery(new LocalVariableTableParameterNameDiscoverer()); documentationParameter.setName(methodParamater.getParameterName()); documentationParameter.setDescription("description"); documentationParameter.setNotes("notes"); documentationParameter.setParamType("path"); documentationParameter.setDefaultValue("default value"); documentationParameter.setAllowMultiple(false); PathVariable pathVariable = methodParamater.getParameterAnnotation(PathVariable.class); if (pathVariable != null) { documentationParameter.setRequired(true); } RequestParam requestParam = methodParamater.getParameterAnnotation(RequestParam.class); if (requestParam != null) { documentationParameter.setRequired(requestParam.required()); documentationParameter.setDefaultValue(requestParam.defaultValue()); } ApiParam apiParam = methodParamater.getParameterAnnotation(ApiParam.class); if (apiParam != null) { documentationParameter.setName(apiParam.name()); documentationParameter.setDescription(apiParam.value()); // documentationParameter.setAllowableValues(apiParam.allowableValues()); } return documentationParameter; }
From source file:de.escalon.hypermedia.spring.ActionInputParameter.java
private Object[] getPossibleValues(MethodParameter methodParameter, AnnotatedParameters actionDescriptor) { try {// www . j av a 2 s.c om Class<?> parameterType = methodParameter.getNestedParameterType(); Object[] possibleValues; Class<?> nested; if (Enum[].class.isAssignableFrom(parameterType)) { possibleValues = parameterType.getComponentType().getEnumConstants(); } else if (Enum.class.isAssignableFrom(parameterType)) { possibleValues = parameterType.getEnumConstants(); } else if (Collection.class.isAssignableFrom(parameterType) && Enum.class.isAssignableFrom(nested = TypeDescriptor.nested(methodParameter, 1).getType())) { possibleValues = nested.getEnumConstants(); } else { Select select = methodParameter.getParameterAnnotation(Select.class); if (select != null) { Class<? extends Options> optionsClass = select.options(); Options options = optionsClass.newInstance(); // collect call values to pass to options.get List<Object> from = new ArrayList<Object>(); for (String paramName : select.args()) { AnnotatedParameter parameterValue = actionDescriptor.getAnnotatedParameter(paramName); if (parameterValue != null) { from.add(parameterValue.getCallValue()); } } Object[] args = from.toArray(); possibleValues = options.get(select.value(), args); } else { possibleValues = new Object[0]; } } return possibleValues; } catch (Exception e) { throw new RuntimeException(e); } }
From source file:de.escalon.hypermedia.spring.SpringActionInputParameter.java
public Object[] getPossibleValues(MethodParameter methodParameter, ActionDescriptor actionDescriptor) { try {//from w w w .j av a 2 s . c o m Class<?> parameterType = methodParameter.getNestedParameterType(); Object[] possibleValues; Class<?> nested; if (Enum[].class.isAssignableFrom(parameterType)) { possibleValues = parameterType.getComponentType().getEnumConstants(); } else if (Enum.class.isAssignableFrom(parameterType)) { possibleValues = parameterType.getEnumConstants(); } else if (Collection.class.isAssignableFrom(parameterType) && Enum.class.isAssignableFrom(nested = TypeDescriptor.nested(methodParameter, 1).getType())) { possibleValues = nested.getEnumConstants(); } else { Select select = methodParameter.getParameterAnnotation(Select.class); if (select != null) { Class<? extends Options> optionsClass = select.options(); Options options = optionsClass.newInstance(); // collect call values to pass to options.get List<Object> from = new ArrayList<Object>(); for (String paramName : select.args()) { ActionInputParameter parameterValue = actionDescriptor.getActionInputParameter(paramName); if (parameterValue != null) { from.add(parameterValue.getValue()); } } Object[] args = from.toArray(); possibleValues = options.get(select.value(), args); } else { possibleValues = new Object[0]; } } return possibleValues; } catch (Exception e) { throw new RuntimeException(e); } }
From source file:org.simbasecurity.manager.service.rest.resolver.JSonArgumentResolver.java
@Override public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception { String body = getRequestBody(nativeWebRequest); ObjectMapper objectMapper = new ObjectMapper(); JsonNode rootNode = objectMapper.readTree(body); JsonNode objectNode = rootNode.get(methodParameter.getParameterAnnotation(JsonBody.class).value()); if (objectNode == null) { objectNode = rootNode;/*from ww w . j a v a 2s . c om*/ } if (Collection.class.isAssignableFrom(methodParameter.getParameterType())) { return readAsCollection(objectMapper, objectNode, methodParameter); } else { return readAsObject(objectMapper, objectNode, methodParameter); } }
From source file:org.springframework.cloud.stream.binder.kafka.streams.KafkaStreamsStreamListenerSetupMethodOrchestrator.java
@Override @SuppressWarnings({ "unchecked" }) public Object[] adaptAndRetrieveInboundArguments(Method method, String inboundName, ApplicationContext applicationContext, StreamListenerParameterAdapter... streamListenerParameterAdapters) { Object[] arguments = new Object[method.getParameterTypes().length]; for (int parameterIndex = 0; parameterIndex < arguments.length; parameterIndex++) { MethodParameter methodParameter = MethodParameter.forExecutable(method, parameterIndex); Class<?> parameterType = methodParameter.getParameterType(); Object targetReferenceValue = null; if (methodParameter.hasParameterAnnotation(Input.class)) { targetReferenceValue = AnnotationUtils .getValue(methodParameter.getParameterAnnotation(Input.class)); Input methodAnnotation = methodParameter.getParameterAnnotation(Input.class); inboundName = methodAnnotation.value(); } else if (arguments.length == 1 && StringUtils.hasText(inboundName)) { targetReferenceValue = inboundName; }/*from ww w .j a v a2 s. c o m*/ if (targetReferenceValue != null) { Assert.isInstanceOf(String.class, targetReferenceValue, "Annotation value must be a String"); Object targetBean = applicationContext.getBean((String) targetReferenceValue); BindingProperties bindingProperties = this.bindingServiceProperties .getBindingProperties(inboundName); enableNativeDecodingForKTableAlways(parameterType, bindingProperties); //Retrieve the StreamsConfig created for this method if available. //Otherwise, create the StreamsBuilderFactory and get the underlying config. if (!this.methodStreamsBuilderFactoryBeanMap.containsKey(method)) { buildStreamsBuilderAndRetrieveConfig(method, applicationContext, inboundName); } try { StreamsBuilderFactoryBean streamsBuilderFactoryBean = this.methodStreamsBuilderFactoryBeanMap .get(method); StreamsBuilder streamsBuilder = streamsBuilderFactoryBean.getObject(); KafkaStreamsConsumerProperties extendedConsumerProperties = this.kafkaStreamsExtendedBindingProperties .getExtendedConsumerProperties(inboundName); //get state store spec KafkaStreamsStateStoreProperties spec = buildStateStoreSpec(method); Serde<?> keySerde = this.keyValueSerdeResolver.getInboundKeySerde(extendedConsumerProperties); Serde<?> valueSerde = this.keyValueSerdeResolver .getInboundValueSerde(bindingProperties.getConsumer(), extendedConsumerProperties); final KafkaConsumerProperties.StartOffset startOffset = extendedConsumerProperties .getStartOffset(); Topology.AutoOffsetReset autoOffsetReset = null; if (startOffset != null) { switch (startOffset) { case earliest: autoOffsetReset = Topology.AutoOffsetReset.EARLIEST; break; case latest: autoOffsetReset = Topology.AutoOffsetReset.LATEST; break; default: break; } } if (extendedConsumerProperties.isResetOffsets()) { LOG.warn("Detected resetOffsets configured on binding " + inboundName + ". " + "Setting resetOffsets in Kafka Streams binder does not have any effect."); } if (parameterType.isAssignableFrom(KStream.class)) { KStream<?, ?> stream = getkStream(inboundName, spec, bindingProperties, streamsBuilder, keySerde, valueSerde, autoOffsetReset); KStreamBoundElementFactory.KStreamWrapper kStreamWrapper = (KStreamBoundElementFactory.KStreamWrapper) targetBean; //wrap the proxy created during the initial target type binding with real object (KStream) kStreamWrapper.wrap((KStream<Object, Object>) stream); this.kafkaStreamsBindingInformationCatalogue .addStreamBuilderFactory(streamsBuilderFactoryBean); for (StreamListenerParameterAdapter streamListenerParameterAdapter : streamListenerParameterAdapters) { if (streamListenerParameterAdapter.supports(stream.getClass(), methodParameter)) { arguments[parameterIndex] = streamListenerParameterAdapter.adapt(kStreamWrapper, methodParameter); break; } } if (arguments[parameterIndex] == null && parameterType.isAssignableFrom(stream.getClass())) { arguments[parameterIndex] = stream; } Assert.notNull(arguments[parameterIndex], "Cannot convert argument " + parameterIndex + " of " + method + "from " + stream.getClass() + " to " + parameterType); } else if (parameterType.isAssignableFrom(KTable.class)) { String materializedAs = extendedConsumerProperties.getMaterializedAs(); String bindingDestination = this.bindingServiceProperties .getBindingDestination(inboundName); KTable<?, ?> table = getKTable(streamsBuilder, keySerde, valueSerde, materializedAs, bindingDestination, autoOffsetReset); KTableBoundElementFactory.KTableWrapper kTableWrapper = (KTableBoundElementFactory.KTableWrapper) targetBean; //wrap the proxy created during the initial target type binding with real object (KTable) kTableWrapper.wrap((KTable<Object, Object>) table); this.kafkaStreamsBindingInformationCatalogue .addStreamBuilderFactory(streamsBuilderFactoryBean); arguments[parameterIndex] = table; } else if (parameterType.isAssignableFrom(GlobalKTable.class)) { String materializedAs = extendedConsumerProperties.getMaterializedAs(); String bindingDestination = this.bindingServiceProperties .getBindingDestination(inboundName); GlobalKTable<?, ?> table = getGlobalKTable(streamsBuilder, keySerde, valueSerde, materializedAs, bindingDestination, autoOffsetReset); GlobalKTableBoundElementFactory.GlobalKTableWrapper globalKTableWrapper = (GlobalKTableBoundElementFactory.GlobalKTableWrapper) targetBean; //wrap the proxy created during the initial target type binding with real object (KTable) globalKTableWrapper.wrap((GlobalKTable<Object, Object>) table); this.kafkaStreamsBindingInformationCatalogue .addStreamBuilderFactory(streamsBuilderFactoryBean); arguments[parameterIndex] = table; } } catch (Exception ex) { throw new IllegalStateException(ex); } } else { throw new IllegalStateException(StreamListenerErrorMessages.INVALID_DECLARATIVE_METHOD_PARAMETERS); } } return arguments; }
From source file:org.springframework.cloud.stream.reactive.StreamEmitterAnnotationBeanPostProcessor.java
@SuppressWarnings({ "rawtypes", "unchecked" }) private void invokeSetupMethodOnToTargetChannel(Method method, Object bean, String outboundName) { Object[] arguments = new Object[method.getParameterCount()]; Object targetBean = null;/*from www.ja v a 2s.c o m*/ for (int parameterIndex = 0; parameterIndex < arguments.length; parameterIndex++) { MethodParameter methodParameter = new SynthesizingMethodParameter(method, parameterIndex); Class<?> parameterType = methodParameter.getParameterType(); Object targetReferenceValue = null; if (methodParameter.hasParameterAnnotation(Output.class)) { targetReferenceValue = AnnotationUtils .getValue(methodParameter.getParameterAnnotation(Output.class)); } else if (arguments.length == 1 && StringUtils.hasText(outboundName)) { targetReferenceValue = outboundName; } if (targetReferenceValue != null) { targetBean = this.applicationContext.getBean((String) targetReferenceValue); for (StreamListenerParameterAdapter<?, Object> streamListenerParameterAdapter : this.streamListenerParameterAdapters) { if (streamListenerParameterAdapter.supports(targetBean.getClass(), methodParameter)) { arguments[parameterIndex] = streamListenerParameterAdapter.adapt(targetBean, methodParameter); if (arguments[parameterIndex] instanceof FluxSender) { closeableFluxResources.add((FluxSender) arguments[parameterIndex]); } break; } } Assert.notNull(arguments[parameterIndex], "Cannot convert argument " + parameterIndex + " of " + method + "from " + targetBean.getClass() + " to " + parameterType); } else { throw new IllegalStateException(StreamEmitterErrorMessages.ATLEAST_ONE_OUTPUT); } } Object result; try { result = method.invoke(bean, arguments); } catch (Exception e) { throw new BeanInitializationException("Cannot setup StreamEmitter for " + method, e); } if (!Void.TYPE.equals(method.getReturnType())) { if (targetBean == null) { targetBean = this.applicationContext.getBean(outboundName); } boolean streamListenerResultAdapterFound = false; for (StreamListenerResultAdapter streamListenerResultAdapter : this.streamListenerResultAdapters) { if (streamListenerResultAdapter.supports(result.getClass(), targetBean.getClass())) { Closeable fluxDisposable = streamListenerResultAdapter.adapt(result, targetBean); closeableFluxResources.add(fluxDisposable); streamListenerResultAdapterFound = true; break; } } Assert.state(streamListenerResultAdapterFound, StreamEmitterErrorMessages.CANNOT_CONVERT_RETURN_TYPE_TO_ANY_AVAILABLE_RESULT_ADAPTERS); } }
From source file:org.springframework.cloud.stream.reactive.StreamEmitterAnnotationBeanPostProcessor.java
private static void validateStreamEmitterMethod(Method method, int outputAnnotationCount, String methodAnnotatedOutboundName) { if (StringUtils.hasText(methodAnnotatedOutboundName)) { Assert.isTrue(outputAnnotationCount == 0, StreamEmitterErrorMessages.INVALID_OUTPUT_METHOD_PARAMETERS); } else {/*from w w w . jav a 2s .c om*/ Assert.isTrue(outputAnnotationCount > 0, StreamEmitterErrorMessages.NO_OUTPUT_SPECIFIED); } if (!method.getReturnType().equals(Void.TYPE)) { Assert.isTrue(StringUtils.hasText(methodAnnotatedOutboundName), StreamEmitterErrorMessages.RETURN_TYPE_NO_OUTBOUND_SPECIFIED); Assert.isTrue(method.getParameterCount() == 0, StreamEmitterErrorMessages.RETURN_TYPE_METHOD_ARGUMENTS); } else { if (!StringUtils.hasText(methodAnnotatedOutboundName)) { int methodArgumentsLength = method.getParameterTypes().length; for (int parameterIndex = 0; parameterIndex < methodArgumentsLength; parameterIndex++) { MethodParameter methodParameter = new MethodParameter(method, parameterIndex); if (methodParameter.hasParameterAnnotation(Output.class)) { String outboundName = (String) AnnotationUtils .getValue(methodParameter.getParameterAnnotation(Output.class)); Assert.isTrue(StringUtils.hasText(outboundName), StreamEmitterErrorMessages.INVALID_OUTBOUND_NAME); } else { throw new IllegalArgumentException( StreamEmitterErrorMessages.OUTPUT_ANNOTATION_MISSING_ON_METHOD_PARAMETERS_VOID_RETURN_TYPE); } } } } }