@Override public JSONEntity read(Class<? extends JSONEntity> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException { // First read the string String jsonString = JSONEntityHttpMessageConverter.readToString( inputMessage.getBody(), inputMessage.getHeaders().getContentType().getCharSet()); try { return EntityFactory.createEntityFromJSONString(jsonString, clazz); } catch (JSONObjectAdapterException e) { // Try to convert entity type to a concrete type and try again. See PLFM-2079. try { JSONObject jsonObject = new JSONObject(jsonString); if (jsonObject.has(ENTITY_TYPE)) { // get the entity type so we can replace it with concrete type String type = jsonObject.getString(ENTITY_TYPE); jsonObject.remove(ENTITY_TYPE); jsonObject.put(CONCRETE_TYPE, type); jsonString = jsonObject.toString(); // try again return EntityFactory.createEntityFromJSONString(jsonString, clazz); } else { // Something else went wrong throw new HttpMessageNotReadableException(e.getMessage(), e); } } catch (JSONException e1) { throw new HttpMessageNotReadableException(e1.getMessage(), e); } catch (JSONObjectAdapterException e2) { throw new HttpMessageNotReadableException(e2.getMessage(), e); } } }
/** Resolves the given {@link RequestBody @RequestBody} annotation. */ @SuppressWarnings("unchecked") protected Object resolveRequestBody( MethodParameter methodParam, NativeWebRequest webRequest, Object handler) throws Exception { HttpInputMessage inputMessage = createHttpInputMessage(webRequest); Class paramType = methodParam.getParameterType(); MediaType contentType = inputMessage.getHeaders().getContentType(); if (contentType == null) { StringBuilder builder = new StringBuilder(ClassUtils.getShortName(methodParam.getParameterType())); String paramName = methodParam.getParameterName(); if (paramName != null) { builder.append(' '); builder.append(paramName); } throw new HttpMediaTypeNotSupportedException( "Cannot extract @RequestBody parameter (" + builder.toString() + "): no Content-Type found"); } List<MediaType> allSupportedMediaTypes = new ArrayList<MediaType>(); if (this.messageConverters != null) { for (HttpMessageConverter<?> messageConverter : this.messageConverters) { allSupportedMediaTypes.addAll(messageConverter.getSupportedMediaTypes()); if (messageConverter.canRead(paramType, contentType)) { return messageConverter.read(paramType, inputMessage); } } } throw new HttpMediaTypeNotSupportedException(contentType, allSupportedMediaTypes); }
@SuppressWarnings({"unchecked", "rawtypes"}) private ModelAndView handleResponseError( ModelAndView exception, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpInputMessage inputMessage = new ServletServerHttpRequest(request); List<MediaType> acceptedMediaTypes = inputMessage.getHeaders().getAccept(); if (acceptedMediaTypes.isEmpty()) { acceptedMediaTypes = Collections.singletonList(MediaType.ALL); } MediaType.sortByQualityValue(acceptedMediaTypes); HttpOutputMessage outputMessage = new ServletServerHttpResponse(response); Class<?> returnValueType = exception.getClass(); List<HttpMessageConverter<?>> messageConverters = super.getMessageConverters(); if (messageConverters != null) { for (MediaType acceptedMediaType : acceptedMediaTypes) { for (HttpMessageConverter messageConverter : messageConverters) { if (messageConverter.canWrite(returnValueType, acceptedMediaType)) { messageConverter.write(exception, acceptedMediaType, outputMessage); return new ModelAndView(); } } } } if (logger.isWarnEnabled()) { logger.warn( "Could not find HttpMessageConverter that supports return type [" + returnValueType + "] and " + acceptedMediaTypes); } return null; }
@Override protected String readInternal(Class<? extends String> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException { MediaType contentType = inputMessage.getHeaders().getContentType(); Charset charset = contentType.getCharSet() != null ? contentType.getCharSet() : DEFAULT_CHARSET; return FileCopyUtils.copyToString(new InputStreamReader(inputMessage.getBody(), charset)); }
@Override public BufferedImage read(Class<? extends BufferedImage> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException { ImageInputStream imageInputStream = null; ImageReader imageReader = null; try { imageInputStream = createImageInputStream(inputMessage.getBody()); MediaType contentType = inputMessage.getHeaders().getContentType(); Iterator<ImageReader> imageReaders = ImageIO.getImageReadersByMIMEType(contentType.toString()); if (imageReaders.hasNext()) { imageReader = imageReaders.next(); ImageReadParam irp = imageReader.getDefaultReadParam(); process(irp); imageReader.setInput(imageInputStream, true); return imageReader.read(0, irp); } else { throw new HttpMessageNotReadableException( "Could not find javax.imageio.ImageReader for Content-Type [" + contentType + "]"); } } finally { if (imageReader != null) { imageReader.dispose(); } if (imageInputStream != null) { try { imageInputStream.close(); } catch (IOException ex) { // ignore } } } }
private HttpEntity<?> resolveHttpEntityRequest( MethodParameter methodParam, NativeWebRequest webRequest) throws Exception { HttpInputMessage inputMessage = createHttpInputMessage(webRequest); Class<?> paramType = getHttpEntityType(methodParam); Object body = readWithMessageConverters(methodParam, inputMessage, paramType); return new HttpEntity<Object>(body, inputMessage.getHeaders()); }
public Object resolveArgument( MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws IOException, HttpMediaTypeNotSupportedException { HttpInputMessage inputMessage = createInputMessage(webRequest); Class<?> paramType = getHttpEntityType(parameter); Object body = readWithMessageConverters(webRequest, parameter, paramType); return new HttpEntity<Object>(body, inputMessage.getHeaders()); }
@Override public Object read(Type type, Class<?> contextClass, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException { try { TumblrResponse tumblrResponse = objectMapper.readValue(inputMessage.getBody(), TumblrResponse.class); checkResponse(tumblrResponse); Object result; if (TumblrResponse.class.equals(type)) { // don't parse the response json, callee is going to process is manually result = tumblrResponse; } else { // parse the response json into an instance of the given class JavaType javaType = getJavaType(type, contextClass); String response = tumblrResponse.getResponseJson(); result = objectMapper.readValue(response, javaType); } return result; } catch (JsonParseException ex) { throw new HttpMessageNotReadableException("Could not read JSON: " + ex.getMessage(), ex); } catch (EOFException ex) { throw new HttpMessageNotReadableException("Could not read JSON: " + ex.getMessage(), ex); } catch (Exception e) { e.printStackTrace(); throw new IOException(e); } }
private Object readJavaType(JavaType javaType, HttpInputMessage inputMessage) { try { if (inputMessage instanceof MappingJacksonInputMessage) { Class<?> deserializationView = ((MappingJacksonInputMessage) inputMessage).getDeserializationView(); if (deserializationView != null) { return this.objectMapper .readerWithView(deserializationView) .forType(javaType) .readValue(inputMessage.getBody()); } } return this.objectMapper.readValue(inputMessage.getBody(), javaType); } catch (IOException ex) { throw new HttpMessageNotReadableException("Could not read document: " + ex.getMessage(), ex); } }
@Override protected OAuth2AccessToken readInternal( Class<? extends OAuth2AccessToken> clazz, HttpInputMessage response) throws IOException, HttpMessageNotReadableException { MediaType contentType = response.getHeaders().getContentType(); if (contentType != null && JSON_MEDIA_TYPE.includes(contentType)) { try { return getSerializationService().deserializeJsonAccessToken(response.getBody()); } catch (SerializationException e) { throw new OAuth2Exception( "Error getting the access token, and unable to read the details of the error in the JSON response.", e); } } else { // the spec currently says json is required, but facebook, for example, still returns // form-encoded. MultiValueMap<String, String> map = FORM_MESSAGE_CONVERTER.read(null, response); return getSerializationService().deserializeAccessToken(map.toSingleValueMap()); } }
/** * Creates the method argument value of the expected parameter type by reading from the given * HttpInputMessage. * * @param <T> the expected type of the argument value to be created * @param inputMessage the HTTP input message representing the current request * @param methodParam the method argument * @param paramType the type of the argument value to be created * @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") protected <T> Object readWithMessageConverters( HttpInputMessage inputMessage, MethodParameter methodParam, Type paramType) throws IOException, HttpMediaTypeNotSupportedException { MediaType contentType = inputMessage.getHeaders().getContentType(); if (contentType == null) { contentType = MediaType.APPLICATION_OCTET_STREAM; } Class<T> paramClass = (paramType instanceof Class) ? (Class) paramType : null; for (HttpMessageConverter<?> messageConverter : this.messageConverters) { if (messageConverter instanceof GenericHttpMessageConverter) { GenericHttpMessageConverter genericMessageConverter = (GenericHttpMessageConverter) messageConverter; if (genericMessageConverter.canRead(paramType, contentType)) { if (logger.isDebugEnabled()) { logger.debug( "Reading [" + paramType + "] as \"" + contentType + "\" using [" + messageConverter + "]"); } return (T) genericMessageConverter.read(paramType, inputMessage); } } if (paramClass != null) { if (messageConverter.canRead(paramClass, contentType)) { if (logger.isDebugEnabled()) { logger.debug( "Reading [" + paramClass.getName() + "] as \"" + contentType + "\" using [" + messageConverter + "]"); } return ((HttpMessageConverter<T>) messageConverter).read(paramClass, inputMessage); } } } throw new HttpMediaTypeNotSupportedException(contentType, allSupportedMediaTypes); }
private Object success(Class<?> clazz, HttpInputMessage inputMessage) throws JsonParseException, IOException { // Note, parsing code used from ektorp project JsonParser jp = objectMapper.getJsonFactory().createJsonParser(inputMessage.getBody()); if (jp.nextToken() != JsonToken.START_OBJECT) { throw new RuntimeException("Expected data to start with an Object"); } Map<String, Integer> fields = readHeaderFields(jp); List result; if (fields.containsKey(TOTAL_ROWS_FIELD_NAME)) { int totalRows = fields.get(TOTAL_ROWS_FIELD_NAME); if (totalRows == 0) { return Collections.emptyList(); } result = new ArrayList(totalRows); } else { result = new ArrayList(); } ParseState state = new ParseState(); Object first = parseFirstRow(jp, state, clazz); if (first == null) { return Collections.emptyList(); } else { result.add(first); } while (jp.getCurrentToken() != null) { skipToField(jp, state.docFieldName, state); if (atEndOfRows(jp)) { return result; } result.add(jp.readValueAs(clazz)); endRow(jp, state); } return result; }
@SuppressWarnings({"unchecked", "rawtypes"}) private Object readWithMessageConverters( MethodParameter methodParam, HttpInputMessage inputMessage, Class<?> paramType) throws Exception { MediaType contentType = inputMessage.getHeaders().getContentType(); if (contentType == null) { StringBuilder builder = new StringBuilder(ClassUtils.getShortName(methodParam.getParameterType())); String paramName = methodParam.getParameterName(); if (paramName != null) { builder.append(' '); builder.append(paramName); } throw new HttpMediaTypeNotSupportedException( "Cannot extract parameter (" + builder.toString() + "): no Content-Type found"); } List<MediaType> allSupportedMediaTypes = new ArrayList<MediaType>(); if (this.messageConverters != null) { for (HttpMessageConverter<?> messageConverter : this.messageConverters) { allSupportedMediaTypes.addAll(messageConverter.getSupportedMediaTypes()); if (messageConverter.canRead(paramType, contentType)) { if (logger.isDebugEnabled()) { logger.debug( "Reading [" + paramType.getName() + "] as \"" + contentType + "\" using [" + messageConverter + "]"); } return messageConverter.read((Class) paramType, inputMessage); } } } throw new HttpMediaTypeNotSupportedException(contentType, allSupportedMediaTypes); }