下面列出了javax.validation.UnexpectedTypeException#org.springframework.web.HttpMediaTypeNotSupportedException 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@SuppressWarnings("unchecked")
private <T> T bodyInternal(Type bodyType, Class<?> bodyClass)
throws ServletException, IOException {
MediaType contentType =
this.headers.contentType().orElse(MediaType.APPLICATION_OCTET_STREAM);
for (HttpMessageConverter<?> messageConverter : this.messageConverters) {
if (messageConverter instanceof GenericHttpMessageConverter) {
GenericHttpMessageConverter<T> genericMessageConverter =
(GenericHttpMessageConverter<T>) messageConverter;
if (genericMessageConverter.canRead(bodyType, bodyClass, contentType)) {
return genericMessageConverter.read(bodyType, bodyClass, this.serverHttpRequest);
}
}
if (messageConverter.canRead(bodyClass, contentType)) {
HttpMessageConverter<T> theConverter =
(HttpMessageConverter<T>) messageConverter;
Class<? extends T> clazz = (Class<? extends T>) bodyClass;
return theConverter.read(clazz, this.serverHttpRequest);
}
}
throw new HttpMediaTypeNotSupportedException(contentType, this.allSupportedMediaTypes);
}
@SuppressWarnings("unchecked")
private <T> T bodyInternal(Type bodyType, Class<?> bodyClass)
throws ServletException, IOException {
HttpInputMessage inputMessage = new BuiltInputMessage();
MediaType contentType = headers().contentType().orElse(MediaType.APPLICATION_OCTET_STREAM);
for (HttpMessageConverter<?> messageConverter : this.messageConverters) {
if (messageConverter instanceof GenericHttpMessageConverter) {
GenericHttpMessageConverter<T> genericMessageConverter =
(GenericHttpMessageConverter<T>) messageConverter;
if (genericMessageConverter.canRead(bodyType, bodyClass, contentType)) {
return genericMessageConverter.read(bodyType, bodyClass, inputMessage);
}
}
if (messageConverter.canRead(bodyClass, contentType)) {
HttpMessageConverter<T> theConverter =
(HttpMessageConverter<T>) messageConverter;
Class<? extends T> clazz = (Class<? extends T>) bodyClass;
return theConverter.read(clazz, inputMessage);
}
}
throw new HttpMediaTypeNotSupportedException(contentType, Collections.emptyList());
}
@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());
}
}
@Override
@SuppressWarnings("unchecked")
protected String getStringRepresentation(OAStatisticsPage oaStatisticsPage, MediaType contentType) throws Exception {
Map<String, Object> jsonMap = oaStatisticsPage.getJsonMap();
JSONLDProfile jsonLdProfile = getJsonLdProfile(contentType, defaultContexts);
Format format = jsonLdProfile.getFormats().get(0);
if (format.equals(Format.COMPACTED)) {
jsonMap = JsonLdProcessor.compact(jsonMap, jsonLdProfile.getContexts(), jsonLdOptions);
} else if (format.equals(Format.EXPANDED)) {
List<Object> jsonList = JsonLdProcessor.expand(jsonMap, jsonLdOptions);
jsonMap = (Map<String, Object>) jsonList.get(0);
} else if (format.equals(Format.FLATTENED)) {
jsonMap = (Map<String, Object>) JsonLdProcessor.flatten(jsonMap, jsonLdProfile.getContexts(), jsonLdOptions);
} else {
throw new HttpMediaTypeNotSupportedException(contentType, getSupportedMediaTypes());
}
jsonMap = reorderJsonAttributes(jsonMap);
return JsonUtils.toPrettyString(jsonMap);
}
@Override
@SuppressWarnings("unchecked")
protected String getStringRepresentation(OAAnnotationPage oaAnnotationPage, MediaType contentType) throws Exception {
Map<String, Object> jsonMap = oaAnnotationPage.getJsonMap();
JSONLDProfile jsonLdProfile = getJsonLdProfile(contentType, defaultContexts);
Format format = jsonLdProfile.getFormats().get(0);
if (format.equals(Format.COMPACTED)) {
jsonMap = JsonLdProcessor.compact(jsonMap, jsonLdProfile.getContexts(), jsonLdOptions);
} else if (format.equals(Format.EXPANDED)) {
List<Object> jsonList = JsonLdProcessor.expand(jsonMap, jsonLdOptions);
jsonMap = (Map<String, Object>) jsonList.get(0);
} else if (format.equals(Format.FLATTENED)) {
jsonMap = (Map<String, Object>) JsonLdProcessor.flatten(jsonMap, jsonLdProfile.getContexts(), jsonLdOptions);
} else {
throw new HttpMediaTypeNotSupportedException(contentType, getSupportedMediaTypes());
}
jsonMap = reorderJsonAttributes(jsonMap);
return JsonUtils.toPrettyString(jsonMap);
}
@Override
@SuppressWarnings("unchecked")
protected String getStringRepresentation(W3CAnnotationHistory w3cAnnotationHistory, MediaType contentType) throws Exception {
Map<String, Object> jsonMap = w3cAnnotationHistory.getJsonMap();
JSONLDProfile jsonLdProfile = getJsonLdProfile(contentType, defaultContexts);
JSONLDProfile.Format format = jsonLdProfile.getFormats().get(0);
if (format.equals(JSONLDProfile.Format.COMPACTED)) {
jsonMap = JsonLdProcessor.compact(jsonMap, jsonLdProfile.getContexts(), jsonLdOptions);
} else if (format.equals(JSONLDProfile.Format.EXPANDED)) {
List<Object> jsonList = JsonLdProcessor.expand(jsonMap, jsonLdOptions);
jsonMap = (Map<String, Object>) jsonList.get(0);
} else if (format.equals(JSONLDProfile.Format.FLATTENED)) {
jsonMap = (Map<String, Object>) JsonLdProcessor.flatten(jsonMap, jsonLdProfile.getContexts(), jsonLdOptions);
} else {
throw new HttpMediaTypeNotSupportedException(contentType, getSupportedMediaTypes());
}
jsonMap = reorderJsonAttributes(jsonMap);
return JsonUtils.toPrettyString(jsonMap);
}
@Override
@SuppressWarnings("unchecked")
protected String getStringRepresentation(W3CBatchOperation w3cBatchOperation, MediaType contentType) throws Exception {
Map<String, Object> jsonMap = w3cBatchOperation.getJsonMap();
JSONLDProfile jsonLdProfile = getJsonLdProfile(contentType, defaultContexts);
Format format = jsonLdProfile.getFormats().get(0);
if (format.equals(Format.COMPACTED)) {
jsonMap = JsonLdProcessor.compact(jsonMap, jsonLdProfile.getContexts(), jsonLdOptions);
} else if (format.equals(Format.EXPANDED)) {
List<Object> jsonList = JsonLdProcessor.expand(jsonMap, jsonLdOptions);
jsonMap = (Map<String, Object>) jsonList.get(0);
} else if (format.equals(Format.FLATTENED)) {
jsonMap = (Map<String, Object>) JsonLdProcessor.flatten(jsonMap, jsonLdProfile.getContexts(), jsonLdOptions);
} else {
throw new HttpMediaTypeNotSupportedException(contentType, getSupportedMediaTypes());
}
jsonMap = reorderJsonAttributes(jsonMap);
return JsonUtils.toPrettyString(jsonMap);
}
@Override
@SuppressWarnings("unchecked")
protected String getStringRepresentation(W3CAnnotation w3cAnnotation, MediaType contentType) throws Exception {
Map<String, Object> jsonMap = w3cAnnotation.getJsonMap();
JSONLDProfile jsonLdProfile = getJsonLdProfile(contentType, defaultContexts);
Format format = jsonLdProfile.getFormats().get(0);
if (format.equals(Format.COMPACTED)) {
jsonMap = JsonLdProcessor.compact(jsonMap, jsonLdProfile.getContexts(), jsonLdOptions);
} else if (format.equals(Format.EXPANDED)) {
List<Object> jsonList = JsonLdProcessor.expand(jsonMap, jsonLdOptions);
jsonMap = (Map<String, Object>) jsonList.get(0);
} else if (format.equals(Format.FLATTENED)) {
jsonMap = (Map<String, Object>) JsonLdProcessor.flatten(jsonMap, jsonLdProfile.getContexts(), jsonLdOptions);
} else {
throw new HttpMediaTypeNotSupportedException(contentType, getSupportedMediaTypes());
}
jsonMap = reorderJsonAttributes(jsonMap);
return JsonUtils.toPrettyString(jsonMap);
}
@Override
@SuppressWarnings("unchecked")
protected String getStringRepresentation(W3CAnnotationPage w3cAnnotationPage, MediaType contentType) throws Exception {
Map<String, Object> jsonMap = w3cAnnotationPage.getJsonMap();
JSONLDProfile jsonLdProfile = getJsonLdProfile(contentType, defaultContexts);
Format format = jsonLdProfile.getFormats().get(0);
if (format.equals(Format.COMPACTED)) {
jsonMap = JsonLdProcessor.compact(jsonMap, jsonLdProfile.getContexts(), jsonLdOptions);
} else if (format.equals(Format.EXPANDED)) {
List<Object> jsonList = JsonLdProcessor.expand(jsonMap, jsonLdOptions);
jsonMap = (Map<String, Object>) jsonList.get(0);
} else if (format.equals(Format.FLATTENED)) {
jsonMap = (Map<String, Object>) JsonLdProcessor.flatten(jsonMap, jsonLdProfile.getContexts(), jsonLdOptions);
} else {
throw new HttpMediaTypeNotSupportedException(contentType, getSupportedMediaTypes());
}
jsonMap = reorderJsonAttributes(jsonMap);
return JsonUtils.toPrettyString(jsonMap);
}
@Override
@SuppressWarnings("unchecked")
protected String getStringRepresentation(W3CStatisticsPage w3cStatisticsPage, MediaType contentType) throws Exception {
Map<String, Object> jsonMap = w3cStatisticsPage.getJsonMap();
JSONLDProfile jsonLdProfile = getJsonLdProfile(contentType, defaultContexts);
Format format = jsonLdProfile.getFormats().get(0);
if (format.equals(Format.COMPACTED)) {
jsonMap = JsonLdProcessor.compact(jsonMap, jsonLdProfile.getContexts(), jsonLdOptions);
} else if (format.equals(Format.EXPANDED)) {
List<Object> jsonList = JsonLdProcessor.expand(jsonMap, jsonLdOptions);
jsonMap = (Map<String, Object>) jsonList.get(0);
} else if (format.equals(Format.FLATTENED)) {
jsonMap = (Map<String, Object>) JsonLdProcessor.flatten(jsonMap, jsonLdProfile.getContexts(), jsonLdOptions);
} else {
throw new HttpMediaTypeNotSupportedException(contentType, getSupportedMediaTypes());
}
jsonMap = reorderJsonAttributes(jsonMap);
return JsonUtils.toPrettyString(jsonMap);
}
@Override
protected <T> Object readWithMessageConverters(NativeWebRequest webRequest, MethodParameter parameter,
Type paramType) throws IOException, HttpMediaTypeNotSupportedException, HttpMessageNotReadableException {
HttpServletRequest servletRequest = webRequest.getNativeRequest(HttpServletRequest.class);
ServletServerHttpRequest inputMessage = new ServletServerHttpRequest(servletRequest);
Object arg = readWithMessageConverters(inputMessage, parameter, paramType);
if (arg == null) {
if (checkRequired(parameter)) {
throw new HttpMessageNotReadableException("Required request body is missing: " +
parameter.getMethod().toGenericString());
}
}
return arg;
}
@Override
@SuppressWarnings("unchecked")
protected String getStringRepresentation(OAAnnotation oaAnnotation, MediaType contentType) throws Exception {
Map<String, Object> jsonMap = oaAnnotation.getJsonMap();
JSONLDProfile jsonLdProfile = getJsonLdProfile(contentType, defaultContexts);
Format format = jsonLdProfile.getFormats().get(0);
if (format.equals(Format.COMPACTED)) {
jsonMap = JsonLdProcessor.compact(jsonMap, jsonLdProfile.getContexts(), jsonLdOptions);
} else if (format.equals(Format.EXPANDED)) {
List<Object> jsonList = JsonLdProcessor.expand(jsonMap, jsonLdOptions);
jsonMap = (Map<String, Object>) jsonList.get(0);
} else if (format.equals(Format.FLATTENED)) {
jsonMap = (Map<String, Object>) JsonLdProcessor.flatten(jsonMap, jsonLdProfile.getContexts(), jsonLdOptions);
} else {
throw new HttpMediaTypeNotSupportedException(contentType, getSupportedMediaTypes());
}
jsonMap = reorderJsonAttributes(jsonMap);
return JsonUtils.toPrettyString(jsonMap);
}
/**
* 415 - Unsupported Media Type
*/
@ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
@ExceptionHandler(HttpMediaTypeNotSupportedException.class)
public Map<String, Object> handleHttpMediaTypeNotSupportedException(HttpMediaTypeNotSupportedException e) {
logger.error("不支持当前媒体类型", e);
Map<String, Object> map = new HashMap<String, Object>();
map.put("rspCode", 415);
map.put("rspMsg", e.getMessage());
//发生异常进行日志记录,写入数据库或者其他处理,此处省略
return map;
}
/**
* 415 - Unsupported Media Type
*/
@ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
@ExceptionHandler(HttpMediaTypeNotSupportedException.class)
public String handleHttpMediaTypeNotSupportedException(HttpMediaTypeNotSupportedException e, Model model) {
logger.error("不支持当前媒体类型", e);
String message = "【不支持当前媒体类型】" + e.getMessage();
model.addAttribute("message", message);
model.addAttribute("code", 415);
return viewName;
}
/**
* 415 - Unsupported Media Type
*/
@ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
@ExceptionHandler(HttpMediaTypeNotSupportedException.class)
public String handleHttpMediaTypeNotSupportedException(HttpMediaTypeNotSupportedException e, Model model) {
logger.error("不支持当前媒体类型", e);
String message = "【不支持当前媒体类型】" + e.getMessage();
model.addAttribute("message", message);
model.addAttribute("code", 415);
return viewName;
}
/**
* 415 - Unsupported Media Type
*/
@ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
@ExceptionHandler(HttpMediaTypeNotSupportedException.class)
public Response handleHttpMediaTypeNotSupportedException(Exception e) {
String msg = "不支持当前媒体类型!";
log.error(msg, e);
return new Response().failure(msg);
}
@Override
protected HttpHeaders createHeaders(HttpMediaTypeNotSupportedException ex, HttpServletRequest req) {
HttpHeaders headers = super.createHeaders(ex, req);
List<MediaType> mediaTypes = ex.getSupportedMediaTypes();
if (!isEmpty(mediaTypes)) {
headers.setAccept(mediaTypes);
}
return headers;
}
/**
* 415 - Unsupported Media Type
*/
@ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
@ExceptionHandler(HttpMediaTypeNotSupportedException.class)
public String handleHttpMediaTypeNotSupportedException(HttpMediaTypeNotSupportedException e, Model model) {
log.error("不支持当前媒体类型", e);
String message = "【不支持当前媒体类型】" + e.getMessage();
model.addAttribute("message", message);
model.addAttribute("code", 415);
return viewName;
}
/**
* {@inheritDoc}
*
* Handle HttpMediaTypeNotSupportedException. This one triggers when JSON is invalid
* as well.
*/
@Override
protected ResponseEntity<Object> handleHttpMediaTypeNotSupported(HttpMediaTypeNotSupportedException ex,
HttpHeaders headers, HttpStatus status, WebRequest request) {
final StringBuilder builder = new StringBuilder();
builder.append(ex.getContentType());
builder.append(" media type is not supported. Supported media types are ");
ex.getSupportedMediaTypes().forEach(mediaType -> builder.append(mediaType).append(", "));
return buildResponseEntity(
new ApiError(HttpStatus.UNSUPPORTED_MEDIA_TYPE, builder.substring(0, builder.length() - 2), ex));
}
@Override
protected <T> Object readWithMessageConverters(NativeWebRequest webRequest, MethodParameter parameter,
Type paramType) throws IOException, HttpMediaTypeNotSupportedException, HttpMessageNotReadableException {
HttpServletRequest servletRequest = webRequest.getNativeRequest(HttpServletRequest.class);
Assert.state(servletRequest != null, "No HttpServletRequest");
ServletServerHttpRequest inputMessage = new ServletServerHttpRequest(servletRequest);
Object arg = readWithMessageConverters(inputMessage, parameter, paramType);
if (arg == null && checkRequired(parameter)) {
throw new HttpMessageNotReadableException("Required request body is missing: " +
parameter.getExecutable().toGenericString(), inputMessage);
}
return arg;
}
@Test(expected = HttpMediaTypeNotSupportedException.class)
public void bodyUnacceptable() throws Exception {
MockHttpServletRequest servletRequest = new MockHttpServletRequest("GET", "/");
servletRequest.setContentType(MediaType.TEXT_PLAIN_VALUE);
servletRequest.setContent("foo".getBytes(UTF_8));
DefaultServerRequest request =
new DefaultServerRequest(servletRequest, Collections.emptyList());
request.body(String.class);
}
private Map<Class, RestExceptionHandler> getDefaultHandlers() {
Map<Class, RestExceptionHandler> map = new HashMap<>();
map.put( NoSuchRequestHandlingMethodException.class, new NoSuchRequestHandlingMethodExceptionHandler() );
map.put( HttpRequestMethodNotSupportedException.class, new HttpRequestMethodNotSupportedExceptionHandler() );
map.put( HttpMediaTypeNotSupportedException.class, new HttpMediaTypeNotSupportedExceptionHandler() );
map.put( MethodArgumentNotValidException.class, new MethodArgumentNotValidExceptionHandler() );
if (ClassUtils.isPresent("javax.validation.ConstraintViolationException", getClass().getClassLoader())) {
map.put( ConstraintViolationException.class, new ConstraintViolationExceptionHandler() );
}
addHandlerTo( map, HttpMediaTypeNotAcceptableException.class, NOT_ACCEPTABLE );
addHandlerTo( map, MissingServletRequestParameterException.class, BAD_REQUEST );
addHandlerTo( map, ServletRequestBindingException.class, BAD_REQUEST );
addHandlerTo( map, ConversionNotSupportedException.class, INTERNAL_SERVER_ERROR );
addHandlerTo( map, TypeMismatchException.class, BAD_REQUEST );
addHandlerTo( map, HttpMessageNotReadableException.class, UNPROCESSABLE_ENTITY );
addHandlerTo( map, HttpMessageNotWritableException.class, INTERNAL_SERVER_ERROR );
addHandlerTo( map, MissingServletRequestPartException.class, BAD_REQUEST );
addHandlerTo(map, Exception.class, INTERNAL_SERVER_ERROR);
// this class didn't exist before Spring 4.0
try {
Class clazz = Class.forName("org.springframework.web.servlet.NoHandlerFoundException");
addHandlerTo(map, clazz, NOT_FOUND);
} catch (ClassNotFoundException ex) {
// ignore
}
return map;
}
@Test
public void handleHttpMediaTypeNotSupported() {
List<MediaType> acceptable = Arrays.asList(MediaType.APPLICATION_ATOM_XML, MediaType.APPLICATION_XML);
Exception ex = new HttpMediaTypeNotSupportedException(MediaType.APPLICATION_JSON, acceptable);
ResponseEntity<Object> responseEntity = testException(ex);
assertEquals(acceptable, responseEntity.getHeaders().getAccept());
}
@Test(expected = HttpMediaTypeNotSupportedException.class)
public void resolveArgumentCannotRead() throws Exception {
MediaType contentType = MediaType.TEXT_PLAIN;
servletRequest.addHeader("Content-Type", contentType.toString());
servletRequest.setContent("payload".getBytes(StandardCharsets.UTF_8));
given(stringMessageConverter.canRead(String.class, contentType)).willReturn(false);
processor.resolveArgument(paramRequestBodyString, mavContainer, webRequest, null);
}
@Test
public void shouldFailResolvingWhenConverterCannotRead() throws Exception {
MediaType contentType = TEXT_PLAIN;
servletRequest.setMethod("POST");
servletRequest.addHeader("Content-Type", contentType.toString());
given(stringHttpMessageConverter.getSupportedMediaTypes()).willReturn(Collections.singletonList(contentType));
given(stringHttpMessageConverter.canRead(String.class, contentType)).willReturn(false);
assertThatExceptionOfType(HttpMediaTypeNotSupportedException.class).isThrownBy(() ->
processor.resolveArgument(paramHttpEntity, mavContainer, webRequest, null));
}
@Test
public void shouldFailResolvingWhenContentTypeNotSupported() throws Exception {
servletRequest.setMethod("POST");
servletRequest.setContent("some content".getBytes(StandardCharsets.UTF_8));
assertThatExceptionOfType(HttpMediaTypeNotSupportedException.class).isThrownBy(() ->
processor.resolveArgument(paramHttpEntity, mavContainer, webRequest, null));
}
@Test(expected = HttpMediaTypeNotSupportedException.class)
public void resolveArgumentNotReadable() throws Exception {
MediaType contentType = MediaType.TEXT_PLAIN;
servletRequest.setMethod("POST");
servletRequest.addHeader("Content-Type", contentType.toString());
given(messageConverter.getSupportedMediaTypes()).willReturn(Collections.singletonList(contentType));
given(messageConverter.canRead(String.class, contentType)).willReturn(false);
processor.resolveArgument(paramHttpEntity, mavContainer, webRequest, null);
fail("Expected exception");
}
@ExceptionHandler(value = HttpMediaTypeNotSupportedException.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public FebsResponse handleHttpMediaTypeNotSupportedException(HttpMediaTypeNotSupportedException e) {
String message = "该方法不支持" + StringUtils.substringBetween(e.getMessage(), "'", "'") + "媒体类型";
log.error(message);
return new FebsResponse().message(message);
}
@ExceptionHandler(HttpMediaTypeNotSupportedException.class)
@ResponseStatus(code = HttpStatus.UNSUPPORTED_MEDIA_TYPE)
public ResponseEntity<ErrorMessage> handleHttpMediaTypeNotSupported(HttpMediaTypeNotSupportedException ex
) {
String unsupported = "Unsupported content type: " + ex.getContentType();
String supported = "Supported content types: " + MediaType.toString(ex.getSupportedMediaTypes());
ErrorMessage errorMessage = new ErrorMessage(unsupported, supported);
return new ResponseEntity(errorMessage, HttpStatus.UNSUPPORTED_MEDIA_TYPE);
}
@ExceptionHandler(HttpMediaTypeNotSupportedException.class)
@ResponseStatus(code = HttpStatus.UNSUPPORTED_MEDIA_TYPE)
public ResponseEntity<ErrorMessage> handleHttpMediaTypeNotSupported(HttpMediaTypeNotSupportedException ex
) {
String unsupported = "Unsupported content type: " + ex.getContentType();
String supported = "Supported content types: " + MediaType.toString(ex.getSupportedMediaTypes());
ErrorMessage errorMessage = new ErrorMessage(unsupported, supported);
return new ResponseEntity(errorMessage, HttpStatus.UNSUPPORTED_MEDIA_TYPE);
}