org.springframework.http.HttpInputMessage Java Examples

The following examples show how to use org.springframework.http.HttpInputMessage. 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: YahooHistoMessageConverter.java    From cloudstreetmarket.com with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected QuoteWrapper readInternal(Class<? extends QuoteWrapper> clazz, HttpInputMessage httpInputMessage) throws IOException, HttpMessageNotReadableException {
    CSVReader reader = new CSVReader(new InputStreamReader(httpInputMessage.getBody()));
    List<String[]> rows = reader.readAll();
    QuoteWrapper quoteWrapper = new QuoteWrapper();
    for (String[] row : rows) {

    	quoteWrapper.add(new YahooQuote(row[0], 
    								row[1], 
    								parseDouble(row[2]), 
    								parseDouble(row[3]), 
    								parseDouble(row[4]), 
    								parseDouble(row[5]), 
    								parsePercent(row[6]), 
    								parseDouble(row[7]), 
    								parseDouble(row[8]), 
    								parseDouble(row[9]), 
    								parseDouble(row[10]), 
    								parseInt(row[11]), 
    								row[12], 
    								row[13]));
    }

    return quoteWrapper;
}
 
Example #2
Source File: RequestResponseBodyMethodProcessorMockTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void resolveArgument() throws Exception {
	MediaType contentType = MediaType.TEXT_PLAIN;
	servletRequest.addHeader("Content-Type", contentType.toString());

	String body = "Foo";
	servletRequest.setContent(body.getBytes(StandardCharsets.UTF_8));

	given(stringMessageConverter.canRead(String.class, contentType)).willReturn(true);
	given(stringMessageConverter.read(eq(String.class), isA(HttpInputMessage.class))).willReturn(body);

	Object result = processor.resolveArgument(paramRequestBodyString, mavContainer,
			webRequest, new ValidatingBinderFactory());

	assertEquals("Invalid argument", body, result);
	assertFalse("The requestHandled flag shouldn't change", mavContainer.isRequestHandled());
}
 
Example #3
Source File: HttpMessageConverterExtractorTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void generics() throws IOException {
	GenericHttpMessageConverter<String> converter = mock(GenericHttpMessageConverter.class);
	HttpHeaders responseHeaders = new HttpHeaders();
	MediaType contentType = MediaType.TEXT_PLAIN;
	responseHeaders.setContentType(contentType);
	String expected = "Foo";
	ParameterizedTypeReference<List<String>> reference = new ParameterizedTypeReference<List<String>>() {};
	Type type = reference.getType();
	extractor = new HttpMessageConverterExtractor<List<String>>(type, createConverterList(converter));
	given(response.getRawStatusCode()).willReturn(HttpStatus.OK.value());
	given(response.getHeaders()).willReturn(responseHeaders);
	given(response.getBody()).willReturn(new ByteArrayInputStream(expected.getBytes()));
	given(converter.canRead(type, null, contentType)).willReturn(true);
	given(converter.read(eq(type), eq(null), any(HttpInputMessage.class))).willReturn(expected);

	Object result = extractor.extractData(response);
	assertEquals(expected, result);
}
 
Example #4
Source File: AbstractMessageConverterMethodArgumentResolver.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
public EmptyBodyCheckingHttpInputMessage(HttpInputMessage inputMessage) throws IOException {
	this.headers = inputMessage.getHeaders();
	InputStream inputStream = inputMessage.getBody();
	if (inputStream == null) {
		this.body = null;
	}
	else if (inputStream.markSupported()) {
		inputStream.mark(1);
		this.body = (inputStream.read() != -1 ? inputStream : null);
		inputStream.reset();
	}
	else {
		PushbackInputStream pushbackInputStream = new PushbackInputStream(inputStream);
		int b = pushbackInputStream.read();
		if (b == -1) {
			this.body = null;
		}
		else {
			this.body = pushbackInputStream;
			pushbackInputStream.unread(b);
		}
	}
	this.method = ((HttpRequest) inputMessage).getMethod();
}
 
Example #5
Source File: PropertiesHttpMessageConverter.java    From SpringAll with MIT License 6 votes vote down vote up
@Override
protected Properties readInternal(Class<? extends Properties> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
    Properties properties = new Properties();
    // 获取请求头
    HttpHeaders headers = inputMessage.getHeaders();
    // 获取 content-type
    MediaType contentType = headers.getContentType();
    // 获取编码
    Charset charset = null;
    if (contentType != null) {
        charset = contentType.getCharset();
    }

    charset = charset == null ? Charset.forName("UTF-8") : charset;

    // 获取请求体
    InputStream body = inputMessage.getBody();
    InputStreamReader inputStreamReader = new InputStreamReader(body, charset);

    properties.load(inputStreamReader);
    return properties;
}
 
Example #6
Source File: HttpMessageConverterExtractorTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test  // SPR-13592
@SuppressWarnings("unchecked")
public void converterThrowsIOException() throws IOException {
	HttpMessageConverter<String> converter = mock(HttpMessageConverter.class);
	HttpHeaders responseHeaders = new HttpHeaders();
	MediaType contentType = MediaType.TEXT_PLAIN;
	responseHeaders.setContentType(contentType);
	extractor = new HttpMessageConverterExtractor<>(String.class, createConverterList(converter));
	given(response.getRawStatusCode()).willReturn(HttpStatus.OK.value());
	given(response.getHeaders()).willReturn(responseHeaders);
	given(response.getBody()).willReturn(new ByteArrayInputStream("Foobar".getBytes()));
	given(converter.canRead(String.class, contentType)).willReturn(true);
	given(converter.read(eq(String.class), any(HttpInputMessage.class))).willThrow(IOException.class);
	assertThatExceptionOfType(RestClientException.class).isThrownBy(() ->
			extractor.extractData(response))
		.withMessageContaining("Error while extracting response for type [class java.lang.String] and content type [text/plain]")
		.withCauseInstanceOf(IOException.class);
}
 
Example #7
Source File: MockHttpServletRequestBuilder.java    From java-technology-stack with MIT License 6 votes vote down vote up
private MultiValueMap<String, String> parseFormData(final MediaType mediaType) {
	HttpInputMessage message = new HttpInputMessage() {
		@Override
		public InputStream getBody() {
			return (content != null ? new ByteArrayInputStream(content) : StreamUtils.emptyInput());
		}
		@Override
		public HttpHeaders getHeaders() {
			HttpHeaders headers = new HttpHeaders();
			headers.setContentType(mediaType);
			return headers;
		}
	};

	try {
		return new FormHttpMessageConverter().read(null, message);
	}
	catch (IOException ex) {
		throw new IllegalStateException("Failed to parse form data in request body", ex);
	}
}
 
Example #8
Source File: MockHttpServletRequestBuilder.java    From spring-analysis-note with MIT License 6 votes vote down vote up
private MultiValueMap<String, String> parseFormData(final MediaType mediaType) {
	HttpInputMessage message = new HttpInputMessage() {
		@Override
		public InputStream getBody() {
			return (content != null ? new ByteArrayInputStream(content) : StreamUtils.emptyInput());
		}
		@Override
		public HttpHeaders getHeaders() {
			HttpHeaders headers = new HttpHeaders();
			headers.setContentType(mediaType);
			return headers;
		}
	};

	try {
		return new FormHttpMessageConverter().read(null, message);
	}
	catch (IOException ex) {
		throw new IllegalStateException("Failed to parse form data in request body", ex);
	}
}
 
Example #9
Source File: Fastjson2HttpMessageConverter.java    From dpCms with Apache License 2.0 6 votes vote down vote up
@Override
protected Object readInternal(Class<? extends Object> clazz, HttpInputMessage inputMessage) throws IOException,  HttpMessageNotReadableException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    InputStream in = inputMessage.getBody();
    byte[] buf = new byte[1024];
    for (;;) {
        int len = in.read(buf);
        if (len == -1) {
            break;
        }
        if (len > 0) {
            baos.write(buf, 0, len);
        }
    }
    byte[] bytes = baos.toByteArray();
    return JSON.parseObject(bytes, 0, bytes.length, charset.newDecoder(), clazz);
}
 
Example #10
Source File: SourceHttpMessageConverter.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
protected T readInternal(Class<? extends T> clazz, HttpInputMessage inputMessage)
		throws IOException, HttpMessageNotReadableException {

	InputStream body = inputMessage.getBody();
	if (DOMSource.class == clazz) {
		return (T) readDOMSource(body);
	}
	else if (SAXSource.class == clazz) {
		return (T) readSAXSource(body);
	}
	else if (StAXSource.class == clazz) {
		return (T) readStAXSource(body);
	}
	else if (StreamSource.class == clazz || Source.class == clazz) {
		return (T) readStreamSource(body);
	}
	else {
		throw new HttpMessageConversionException("Could not read class [" + clazz +
				"]. Only DOMSource, SAXSource, StAXSource, and StreamSource are supported.");
	}
}
 
Example #11
Source File: HttpEntityMethodProcessorMockTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void shouldResolveHttpEntityArgument() throws Exception {
	String body = "Foo";

	MediaType contentType = TEXT_PLAIN;
	servletRequest.addHeader("Content-Type", contentType.toString());
	servletRequest.setContent(body.getBytes(StandardCharsets.UTF_8));

	given(stringHttpMessageConverter.canRead(String.class, contentType)).willReturn(true);
	given(stringHttpMessageConverter.read(eq(String.class), isA(HttpInputMessage.class))).willReturn(body);

	Object result = processor.resolveArgument(paramHttpEntity, mavContainer, webRequest, null);

	assertTrue(result instanceof HttpEntity);
	assertFalse("The requestHandled flag shouldn't change", mavContainer.isRequestHandled());
	assertEquals("Invalid argument", body, ((HttpEntity<?>) result).getBody());
}
 
Example #12
Source File: YahooQuoteMessageConverter.java    From cloudstreetmarket.com with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected QuoteWrapper readInternal(Class<? extends QuoteWrapper> clazz, HttpInputMessage httpInputMessage) throws IOException, HttpMessageNotReadableException {
    CSVReader reader = new CSVReader(new InputStreamReader(httpInputMessage.getBody()));
    List<String[]> rows = reader.readAll();
    QuoteWrapper quoteWrapper = new QuoteWrapper();
    for (String[] row : rows) {
    	quoteWrapper.add(new YahooQuote(row[0], 
    								row[1], 
    								parseDouble(row[2]), 
    								parseDouble(row[3]), 
    								parseDouble(row[4]), 
    								parseDouble(row[5]), 
    								parsePercent(row[6]), 
    								parseDouble(row[7]), 
    								parseDouble(row[8]), 
    								parseDouble(row[9]), 
    								parseDouble(row[10]), 
    								parseInt(row[11]), 
    								row[12], 
    								row[13]));
    }

    return quoteWrapper;
}
 
Example #13
Source File: ContentRequestMatchers.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Parse the body as form data and compare to the given {@code MultiValueMap}.
 * @since 4.3
 */
public RequestMatcher formData(final MultiValueMap<String, String> expectedContent) {
	return request -> {
		HttpInputMessage inputMessage = new HttpInputMessage() {
			@Override
			public InputStream getBody() throws IOException {
				MockClientHttpRequest mockRequest = (MockClientHttpRequest) request;
				return new ByteArrayInputStream(mockRequest.getBodyAsBytes());
			}
			@Override
			public HttpHeaders getHeaders() {
				return request.getHeaders();
			}
		};
		FormHttpMessageConverter converter = new FormHttpMessageConverter();
		assertEquals("Request content", expectedContent, converter.read(null, inputMessage));
	};
}
 
Example #14
Source File: RequestResponseBodyMethodProcessorMockTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void resolveArgument() throws Exception {
	MediaType contentType = MediaType.TEXT_PLAIN;
	servletRequest.addHeader("Content-Type", contentType.toString());

	String body = "Foo";
	servletRequest.setContent(body.getBytes(StandardCharsets.UTF_8));

	given(stringMessageConverter.canRead(String.class, contentType)).willReturn(true);
	given(stringMessageConverter.read(eq(String.class), isA(HttpInputMessage.class))).willReturn(body);

	Object result = processor.resolveArgument(paramRequestBodyString, mavContainer,
			webRequest, new ValidatingBinderFactory());

	assertEquals("Invalid argument", body, result);
	assertFalse("The requestHandled flag shouldn't change", mavContainer.isRequestHandled());
}
 
Example #15
Source File: ResourceHttpMessageConverter.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
protected Resource readInternal(Class<? extends Resource> clazz, HttpInputMessage inputMessage)
		throws IOException, HttpMessageNotReadableException {

	if (this.supportsReadStreaming && InputStreamResource.class == clazz) {
		return new InputStreamResource(inputMessage.getBody()) {
			@Override
			public String getFilename() {
				return inputMessage.getHeaders().getContentDisposition().getFilename();
			}
		};
	}
	else if (Resource.class == clazz || ByteArrayResource.class.isAssignableFrom(clazz)) {
		byte[] body = StreamUtils.copyToByteArray(inputMessage.getBody());
		return new ByteArrayResource(body) {
			@Override
			@Nullable
			public String getFilename() {
				return inputMessage.getHeaders().getContentDisposition().getFilename();
			}
		};
	}
	else {
		throw new HttpMessageNotReadableException("Unsupported resource class: " + clazz, inputMessage);
	}
}
 
Example #16
Source File: AbstractWireFeedHttpMessageConverter.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
protected T readInternal(Class<? extends T> clazz, HttpInputMessage inputMessage)
		throws IOException, HttpMessageNotReadableException {

	WireFeedInput feedInput = new WireFeedInput();
	MediaType contentType = inputMessage.getHeaders().getContentType();
	Charset charset = (contentType != null && contentType.getCharset() != null ?
			contentType.getCharset() : DEFAULT_CHARSET);
	try {
		Reader reader = new InputStreamReader(inputMessage.getBody(), charset);
		return (T) feedInput.build(reader);
	}
	catch (FeedException ex) {
		throw new HttpMessageNotReadableException("Could not read WireFeed: " + ex.getMessage(), ex, inputMessage);
	}
}
 
Example #17
Source File: WxApiResponseExtractor.java    From FastBootWeixin with Apache License 2.0 5 votes vote down vote up
public <T> T extractData(ResponseEntity<HttpInputMessage> responseEntity, Class<T> returnType) {
    // 本来应该有response数据为空的判断的,其实这里已经被前一步的restTemplate获取中判断过了,这里只用判断body为空即可
    if (returnType == null || void.class == returnType || Void.class == returnType || responseEntity.getBody() == null) {
        return null;
    }
    /* 先不管文件
    if (WxWebUtils.isMutlipart(returnType)) {
        return null;
    }
    不是不管文件,而是可以被messageConverter处理了
    */
    WxApiMessageConverterExtractor<T> delegate = delegates.get(returnType);
    if (delegate == null) {
        delegate = new WxApiMessageConverterExtractor(returnType, converters);
        delegates.put(returnType, delegate);
    }
    // 这里遇到了个坑,很长时间没玩过IO了,这个坑就和IO相关,每次提取数据时都抛出IO异常,IO已关闭
    // 本来以为是我的error判断那里提前读了IO导致后来IO关闭了,调试后发现真正原因,因为
    // ResponseEntity<HttpInputMessage> responseEntity = wxApiInvoker.exchange(requestEntity, HttpInputMessage.class);
    // 上面代码执行结束后,有个finally,就是用于关闭response的,也就是说,一旦执行结束就无法再执行提取数据的操作了
    // 所以我只能把WxHttpInputMessageConverter里返回的inputStream包装一下了
    // 这里还涉及一个问题,是否有必要把所有消息都返回inputStream?当然没有必要,只要特定几种类型返回InputStream
    // 其他类型直接转换即可。
    try {
        return delegate.extractData(responseEntity);
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
        throw new WxApiResponseException("提取数据时发生IO异常", responseEntity);
    }
}
 
Example #18
Source File: RequestBodyAdviceAdapter.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * The default implementation returns the body that was passed in.
 */
@Override
public Object handleEmptyBody(Object body, HttpInputMessage inputMessage,
		MethodParameter parameter, Type targetType,
		Class<? extends HttpMessageConverter<?>> converterType) {

	return body;
}
 
Example #19
Source File: ResourceHttpMessageConverter.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected Resource readInternal(Class<? extends Resource> clazz, HttpInputMessage inputMessage)
		throws IOException, HttpMessageNotReadableException {

	if (InputStreamResource.class == clazz) {
		return new InputStreamResource(inputMessage.getBody());
	}
	else if (clazz.isAssignableFrom(ByteArrayResource.class)) {
		byte[] body = StreamUtils.copyToByteArray(inputMessage.getBody());
		return new ByteArrayResource(body);
	}
	else {
		throw new IllegalStateException("Unsupported resource class: " + clazz);
	}
}
 
Example #20
Source File: WithSignMessageConverter.java    From MeetingFilm with Apache License 2.0 5 votes vote down vote up
@Override
public Object read(Type type, Class<?> contextClass, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {

    InputStream in = inputMessage.getBody();
    Object o = JSON.parseObject(in, super.getFastJsonConfig().getCharset(), BaseTransferEntity.class, super.getFastJsonConfig().getFeatures());

    //先转化成原始的对象
    BaseTransferEntity baseTransferEntity = (BaseTransferEntity) o;

    //校验签名
    String token = HttpKit.getRequest().getHeader(jwtProperties.getHeader()).substring(7);
    String md5KeyFromToken = jwtTokenUtil.getMd5KeyFromToken(token);

    String object = baseTransferEntity.getObject();
    String json = dataSecurityAction.unlock(object);
    String encrypt = MD5Util.encrypt(object + md5KeyFromToken);

    if (encrypt.equals(baseTransferEntity.getSign())) {
        System.out.println("签名校验成功!");
    } else {
        System.out.println("签名校验失败,数据被改动过!");
        throw new GunsException(BizExceptionEnum.SIGN_ERROR);
    }

    //校验签名后再转化成应该的对象
    return JSON.parseObject(json, type);
}
 
Example #21
Source File: WithSignMessageConverter.java    From MeetingFilm with Apache License 2.0 5 votes vote down vote up
@Override
public Object read(Type type, Class<?> contextClass, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {

    InputStream in = inputMessage.getBody();
    Object o = JSON.parseObject(in, super.getFastJsonConfig().getCharset(), BaseTransferEntity.class, super.getFastJsonConfig().getFeatures());

    //先转化成原始的对象
    BaseTransferEntity baseTransferEntity = (BaseTransferEntity) o;

    //校验签名
    String token = HttpKit.getRequest().getHeader(jwtProperties.getHeader()).substring(7);
    String md5KeyFromToken = jwtTokenUtil.getMd5KeyFromToken(token);

    String object = baseTransferEntity.getObject();
    String json = dataSecurityAction.unlock(object);
    String encrypt = MD5Util.encrypt(object + md5KeyFromToken);

    if (encrypt.equals(baseTransferEntity.getSign())) {
        System.out.println("签名校验成功!");
    } else {
        System.out.println("签名校验失败,数据被改动过!");
        throw new GunsException(BizExceptionEnum.SIGN_ERROR);
    }

    //校验签名后再转化成应该的对象
    return JSON.parseObject(json, type);
}
 
Example #22
Source File: ByteArrayHttpMessageConverter.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public byte[] readInternal(Class<? extends byte[]> clazz, HttpInputMessage inputMessage) throws IOException {
	long contentLength = inputMessage.getHeaders().getContentLength();
	ByteArrayOutputStream bos =
			new ByteArrayOutputStream(contentLength >= 0 ? (int) contentLength : StreamUtils.BUFFER_SIZE);
	StreamUtils.copy(inputMessage.getBody(), bos);
	return bos.toByteArray();
}
 
Example #23
Source File: AbstractJackson2HttpMessageConverter.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public Object read(Type type, @Nullable Class<?> contextClass, HttpInputMessage inputMessage)
		throws IOException, HttpMessageNotReadableException {

	JavaType javaType = getJavaType(type, contextClass);
	return readJavaType(javaType, inputMessage);
}
 
Example #24
Source File: FormContentFilter.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Nullable
private MultiValueMap<String, String> parseIfNecessary(HttpServletRequest request) throws IOException {
	if (!shouldParse(request)) {
		return null;
	}

	HttpInputMessage inputMessage = new ServletServerHttpRequest(request) {
		@Override
		public InputStream getBody() throws IOException {
			return request.getInputStream();
		}
	};
	return this.formConverter.read(null, inputMessage);
}
 
Example #25
Source File: RequestResponseBodyAdviceChain.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter,
		Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {

	for (RequestBodyAdvice advice : getMatchingAdvice(parameter, RequestBodyAdvice.class)) {
		if (advice.supports(parameter, targetType, converterType)) {
			body = advice.afterBodyRead(body, inputMessage, parameter, targetType, converterType);
		}
	}
	return body;
}
 
Example #26
Source File: RestTemplateTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void getForEntity() throws Exception {
	given(converter.canRead(String.class, null)).willReturn(true);
	MediaType textPlain = new MediaType("text", "plain");
	given(converter.getSupportedMediaTypes()).willReturn(Collections.singletonList(textPlain));
	given(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.GET)).willReturn(request);
	HttpHeaders requestHeaders = new HttpHeaders();
	given(request.getHeaders()).willReturn(requestHeaders);
	given(request.execute()).willReturn(response);
	given(errorHandler.hasError(response)).willReturn(false);
	String expected = "Hello World";
	HttpHeaders responseHeaders = new HttpHeaders();
	responseHeaders.setContentType(textPlain);
	responseHeaders.setContentLength(10);
	given(response.getStatusCode()).willReturn(HttpStatus.OK);
	given(response.getHeaders()).willReturn(responseHeaders);
	given(response.getBody()).willReturn(new ByteArrayInputStream(expected.getBytes()));
	given(converter.canRead(String.class, textPlain)).willReturn(true);
	given(converter.read(eq(String.class), any(HttpInputMessage.class))).willReturn(expected);
	given(response.getStatusCode()).willReturn(HttpStatus.OK);
	HttpStatus status = HttpStatus.OK;
	given(response.getStatusCode()).willReturn(status);
	given(response.getStatusText()).willReturn(status.getReasonPhrase());

	ResponseEntity<String> result = template.getForEntity("http://example.com", String.class);
	assertEquals("Invalid GET result", expected, result.getBody());
	assertEquals("Invalid Accept header", textPlain.toString(), requestHeaders.getFirst("Accept"));
	assertEquals("Invalid Content-Type header", textPlain, result.getHeaders().getContentType());
	assertEquals("Invalid status code", HttpStatus.OK, result.getStatusCode());

	verify(response).close();
}
 
Example #27
Source File: RequestResponseBodyAdviceChain.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
@Nullable
public Object handleEmptyBody(@Nullable Object body, HttpInputMessage inputMessage, MethodParameter parameter,
		Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {

	for (RequestBodyAdvice advice : getMatchingAdvice(parameter, RequestBodyAdvice.class)) {
		if (advice.supports(parameter, targetType, converterType)) {
			body = advice.handleEmptyBody(body, inputMessage, parameter, targetType, converterType);
		}
	}
	return body;
}
 
Example #28
Source File: CsvHttpMessageConverterTest.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
void testReadInternal() throws IOException {
  assertThrows(
      UnsupportedOperationException.class,
      () ->
          csvHttpMessageConverter.readInternal(
              EntityCollection.class, mock(HttpInputMessage.class)));
}
 
Example #29
Source File: ProtobufHttpMessageConverter.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
protected Message readInternal(Class<? extends Message> clazz, HttpInputMessage inputMessage)
		throws IOException, HttpMessageNotReadableException {

	MediaType contentType = inputMessage.getHeaders().getContentType();
	if (contentType == null) {
		contentType = PROTOBUF;
	}
	Charset charset = contentType.getCharset();
	if (charset == null) {
		charset = DEFAULT_CHARSET;
	}

	Message.Builder builder = getMessageBuilder(clazz);
	if (PROTOBUF.isCompatibleWith(contentType)) {
		builder.mergeFrom(inputMessage.getBody(), this.extensionRegistry);
	}
	else if (TEXT_PLAIN.isCompatibleWith(contentType)) {
		InputStreamReader reader = new InputStreamReader(inputMessage.getBody(), charset);
		TextFormat.merge(reader, this.extensionRegistry, builder);
	}
	else if (this.protobufFormatSupport != null) {
		this.protobufFormatSupport.merge(
				inputMessage.getBody(), charset, contentType, this.extensionRegistry, builder);
	}
	return builder.build();
}
 
Example #30
Source File: UTF8StringHttpMessageConverter.java    From maven-framework-project with MIT License 5 votes vote down vote up
@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));
}