List of usage examples for org.springframework.core MethodParameter getContainingClass
public Class<?> getContainingClass()
From source file:com.kinglcc.spring.jms.core.Jackson2PayloadArgumentResolver.java
private Object convertJavaTypeFromMessage(Message<?> message, MethodParameter parameter) { Type targetType = parameter.getGenericParameterType(); Class<?> contextClass = parameter.getContainingClass(); Object payload = ((GenericMessageAdapterConverter) converter).fromMessage(message, targetType, contextClass);// w w w. j a v a 2s.c o m if (payload == null) { throw new MessageConversionException(message, "No converter found to convert to " + targetType + ", message=" + message); } return payload; }
From source file:org.opentides.web.processor.FormBindMethodProcessor.java
/** * Resolve the argument from the model or if not found instantiate it with * its default. The model attribute is then populated with request values * via data binding and validated. If no validation error, the model * is retrieved from database and merged with the submitted form. * /*from w ww. java2s .c o m*/ * @throws BindException if data binding and validation result in an error * @throws Exception if WebDataBinder initialization fails. */ @SuppressWarnings("unchecked") public final Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest nativeRequest, WebDataBinderFactory binderFactory) throws Exception { FormBind annot = parameter.getParameterAnnotation(FormBind.class); Class<?> clazz = parameter.getDeclaringClass(); String name = getName(annot, parameter); HttpServletRequest request = (HttpServletRequest) nativeRequest.getNativeRequest(); Method addForm = CacheUtil.getNewFormBindMethod(clazz); Object controller = beanFactory.getBean(parameter.getContainingClass()); Object target = (addForm != null) ? addForm.invoke(controller, request) : BeanUtils.instantiateClass(parameter.getParameterType()); MutablePropertyValues mpvs = new MutablePropertyValues(nativeRequest.getParameterMap()); WebDataBinder binder = binderFactory.createBinder(nativeRequest, target, name); if (binder.getTarget() != null) { binder.bind(mpvs); if (binder.getValidator() != null) binder.validate(); if (binder.getBindingResult().hasErrors()) { throw new BindException(binder.getBindingResult()); } String method = request.getMethod().toLowerCase(); // id should be the last segment of the uri String uri = request.getRequestURI(); String sid = uri.substring(uri.lastIndexOf("/") + 1); Long id = StringUtil.convertToLong(sid, 0); // if target extends BaseEntity and for update, link target to database record if (("put".equals(method) || "post".equals(method)) && id > 0 && BaseEntity.class.isAssignableFrom(parameter.getParameterType())) { // now retrieve record from database for updating Method updateForm = CacheUtil.getUpdateFormBindMethod(clazz); BaseEntity record = null; if (updateForm == null) { // no annotation, invoke from service Method getService = controller.getClass().getMethod("getService"); if (getService == null) { String message = "Cannot find method with @FormBind with update mode. " + "Also, unable to find service associated to controller." + "Please specify one that retrieves record from database."; throw new InvalidImplementationException(message); } BaseCrudService<? extends BaseEntity> service = (BaseCrudService<? extends BaseEntity>) getService .invoke(controller); record = (BaseEntity) service.load(sid); } else { // with annotation, invoke annotation record = (BaseEntity) updateForm.invoke(controller, sid, request); } if (record != null) { WebDataBinder updateBinder = binderFactory.createBinder(nativeRequest, record, name); updateBinder.bind(mpvs); mavContainer.addAllAttributes(updateBinder.getBindingResult().getModel()); return updateBinder.getTarget(); } else { String message = "Unable to find " + parameter.getParameterType().getSimpleName() + " with id=" + sid + " for update."; throw new DataAccessException(message); } } else if ("post".equals(method)) { mavContainer.addAllAttributes(binder.getBindingResult().getModel()); return binder.getTarget(); } else { throw new InvalidImplementationException( "@FormBind argument annotation can only be used on POST or PUT methods."); } } mavContainer.addAllAttributes(binder.getBindingResult().getModel()); return binder.getTarget(); }
From source file:org.springframework.messaging.handler.invocation.reactive.AbstractEncoderMethodReturnValueHandler.java
@SuppressWarnings("unchecked") private Flux<DataBuffer> encodeContent(@Nullable Object content, MethodParameter returnType, DataBufferFactory bufferFactory, @Nullable MimeType mimeType, Map<String, Object> hints) { ResolvableType returnValueType = ResolvableType.forMethodParameter(returnType); ReactiveAdapter adapter = getAdapterRegistry().getAdapter(returnValueType.resolve(), content); Publisher<?> publisher;/*from ww w .j a v a 2s .com*/ ResolvableType elementType; if (adapter != null) { publisher = adapter.toPublisher(content); boolean isUnwrapped = KotlinDetector.isKotlinReflectPresent() && KotlinDetector.isKotlinType(returnType.getContainingClass()) && KotlinDelegate.isSuspend(returnType.getMethod()) && !COROUTINES_FLOW_CLASS_NAME.equals(returnValueType.toClass().getName()); ResolvableType genericType = isUnwrapped ? returnValueType : returnValueType.getGeneric(); elementType = getElementType(adapter, genericType); } else { publisher = Mono.justOrEmpty(content); elementType = (returnValueType.toClass() == Object.class && content != null ? ResolvableType.forInstance(content) : returnValueType); } if (elementType.resolve() == void.class || elementType.resolve() == Void.class) { return Flux.from(publisher).cast(DataBuffer.class); } Encoder<?> encoder = getEncoder(elementType, mimeType); return Flux.from((Publisher) publisher) .map(value -> encodeValue(value, elementType, encoder, bufferFactory, mimeType, hints)); }
From source file:org.springframework.web.method.annotation.ModelFactory.java
/** * Derive the model attribute name for the given return value based on: * <ol>/*www.j a v a 2 s. com*/ * <li>the method {@code ModelAttribute} annotation value * <li>the declared return type if it is more specific than {@code Object} * <li>the actual return value type * </ol> * @param returnValue the value returned from a method invocation * @param returnType a descriptor for the return type of the method * @return the derived name (never {@code null} or empty String) */ public static String getNameForReturnValue(@Nullable Object returnValue, MethodParameter returnType) { ModelAttribute ann = returnType.getMethodAnnotation(ModelAttribute.class); if (ann != null && StringUtils.hasText(ann.value())) { return ann.value(); } else { Method method = returnType.getMethod(); Assert.state(method != null, "No handler method"); Class<?> containingClass = returnType.getContainingClass(); Class<?> resolvedType = GenericTypeResolver.resolveReturnType(method, containingClass); return Conventions.getVariableNameForReturnType(method, resolvedType, returnValue); } }
From source file:org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodArgumentResolver.java
/** * Create the method argument value of the expected parameter type by reading * from the given HttpInputMessage./*from ww w. j ava 2 s. c om*/ * @param <T> the expected type of the argument value to be created * @param inputMessage the HTTP input message representing the current request * @param parameter the method parameter descriptor * @param targetType the target type, not necessarily the same as the method * parameter type, e.g. for {@code HttpEntity<String>}. * @return the created method argument value * @throws IOException if the reading from the request fails * @throws HttpMediaTypeNotSupportedException if no suitable message converter is found */ @SuppressWarnings("unchecked") @Nullable protected <T> Object readWithMessageConverters(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType) throws IOException, HttpMediaTypeNotSupportedException, HttpMessageNotReadableException { MediaType contentType; boolean noContentType = false; try { contentType = inputMessage.getHeaders().getContentType(); } catch (InvalidMediaTypeException ex) { throw new HttpMediaTypeNotSupportedException(ex.getMessage()); } if (contentType == null) { noContentType = true; contentType = MediaType.APPLICATION_OCTET_STREAM; } Class<?> contextClass = parameter.getContainingClass(); Class<T> targetClass = (targetType instanceof Class ? (Class<T>) targetType : null); if (targetClass == null) { ResolvableType resolvableType = ResolvableType.forMethodParameter(parameter); targetClass = (Class<T>) resolvableType.resolve(); } HttpMethod httpMethod = (inputMessage instanceof HttpRequest ? ((HttpRequest) inputMessage).getMethod() : null); Object body = NO_VALUE; EmptyBodyCheckingHttpInputMessage message; try { message = new EmptyBodyCheckingHttpInputMessage(inputMessage); for (HttpMessageConverter<?> converter : this.messageConverters) { Class<HttpMessageConverter<?>> converterType = (Class<HttpMessageConverter<?>>) converter .getClass(); GenericHttpMessageConverter<?> genericConverter = (converter instanceof GenericHttpMessageConverter ? (GenericHttpMessageConverter<?>) converter : null); if (genericConverter != null ? genericConverter.canRead(targetType, contextClass, contentType) : (targetClass != null && converter.canRead(targetClass, contentType))) { if (logger.isDebugEnabled()) { logger.debug( "Read [" + targetType + "] as \"" + contentType + "\" with [" + converter + "]"); } if (message.hasBody()) { HttpInputMessage msgToUse = getAdvice().beforeBodyRead(message, parameter, targetType, converterType); body = (genericConverter != null ? genericConverter.read(targetType, contextClass, msgToUse) : ((HttpMessageConverter<T>) converter).read(targetClass, msgToUse)); body = getAdvice().afterBodyRead(body, msgToUse, parameter, targetType, converterType); } else { body = getAdvice().handleEmptyBody(null, message, parameter, targetType, converterType); } break; } } } catch (IOException ex) { throw new HttpMessageNotReadableException("I/O error while reading input message", ex); } if (body == NO_VALUE) { if (httpMethod == null || !SUPPORTED_METHODS.contains(httpMethod) || (noContentType && !message.hasBody())) { return null; } throw new HttpMediaTypeNotSupportedException(contentType, this.allSupportedMediaTypes); } return body; }
From source file:org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdviceChain.java
@SuppressWarnings("unchecked") public <T> T invoke(T body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {/*from w w w. ja va 2 s . c om*/ if (this.advice != null) { if (logger.isDebugEnabled()) { logger.debug("Invoking ResponseBodyAdvice chain for body=" + body); } for (Object advice : this.advice) { if (advice instanceof ControllerAdviceBean) { ControllerAdviceBean adviceBean = (ControllerAdviceBean) advice; if (!adviceBean.isApplicableToBeanType(returnType.getContainingClass())) { continue; } advice = adviceBean.resolveBean(); } if (advice instanceof ResponseBodyAdvice) { ResponseBodyAdvice<T> typedAdvice = (ResponseBodyAdvice<T>) advice; if (typedAdvice.supports(returnType, selectedConverterType)) { body = typedAdvice.beforeBodyWrite(body, returnType, selectedContentType, selectedConverterType, request, response); } } else { throw new IllegalStateException("Expected ResponseBodyAdvice: " + advice); } } if (logger.isDebugEnabled()) { logger.debug("After ResponseBodyAdvice chain body=" + body); } } return body; }
From source file:org.springframework.web.servlet.mvc.method.annotation.ResponseBodyInterceptorChain.java
public <T> T invoke(T body, MediaType contentType, Class<? extends HttpMessageConverter<T>> converterType, MethodParameter returnType, ServerHttpRequest request, ServerHttpResponse response) { if (this.interceptors != null) { if (logger.isDebugEnabled()) { logger.debug("Invoking ResponseBody interceptor chain for body=" + body); }// ww w . ja v a2s. c om for (Object interceptor : this.interceptors) { if (interceptor instanceof ControllerAdviceBean) { ControllerAdviceBean adviceBean = (ControllerAdviceBean) interceptor; if (!adviceBean.isApplicableToBeanType(returnType.getContainingClass())) { continue; } interceptor = adviceBean.resolveBean(); } Assert.state(interceptor instanceof ResponseBodyInterceptor); body = ((ResponseBodyInterceptor) interceptor).beforeBodyWrite(body, contentType, converterType, returnType, request, response); } if (logger.isDebugEnabled()) { logger.debug("After interceptor chain body=" + body); } } return body; }