org.springframework.web.HttpMediaTypeNotSupportedException Java Examples

The following examples show how to use org.springframework.web.HttpMediaTypeNotSupportedException. 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: JSONLDW3CAnnotationMessageConverter.java    From elucidate-server with MIT License 6 votes vote down vote up
@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);
}
 
Example #2
Source File: JSONLDW3CBatchOperationMessageConverter.java    From elucidate-server with MIT License 6 votes vote down vote up
@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);
}
 
Example #3
Source File: JSONLDW3CAnnotationHistoryMessageConverter.java    From elucidate-server with MIT License 6 votes vote down vote up
@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);
}
 
Example #4
Source File: JSONLDOAAnnotationPageMessageConverter.java    From elucidate-server with MIT License 6 votes vote down vote up
@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);
}
 
Example #5
Source File: JSONLDOAStatisticsPageMessageConverter.java    From elucidate-server with MIT License 6 votes vote down vote up
@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);
}
 
Example #6
Source File: JSONLDW3CStatisticsPageMessageConverter.java    From elucidate-server with MIT License 6 votes vote down vote up
@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);
}
 
Example #7
Source File: HttpEntityMethodProcessor.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@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());
	}
}
 
Example #8
Source File: RequestResponseBodyMethodProcessor.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@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;
}
 
Example #9
Source File: JSONLDW3CAnnotationPageMessageConverter.java    From elucidate-server with MIT License 6 votes vote down vote up
@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);
}
 
Example #10
Source File: DefaultServerRequestBuilder.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@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());
}
 
Example #11
Source File: DefaultServerRequest.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@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);
}
 
Example #12
Source File: JSONLDOAAnnotationMessageConverter.java    From elucidate-server with MIT License 6 votes vote down vote up
@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);
}
 
Example #13
Source File: RequestResponseBodyMethodProcessorMockTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test(expected = HttpMediaTypeNotSupportedException.class)
public void resolveArgumentCannotRead() throws Exception {
	MediaType contentType = MediaType.TEXT_PLAIN;
	servletRequest.addHeader("Content-Type", contentType.toString());
	servletRequest.setContent("payload".getBytes(Charset.forName("UTF-8")));

	given(messageConverter.canRead(String.class, contentType)).willReturn(false);

	processor.resolveArgument(paramRequestBodyString, mavContainer, webRequest, null);
}
 
Example #14
Source File: CustomRestExceptionHandler.java    From xxproject with Apache License 2.0 5 votes vote down vote up
@Override
protected ResponseEntity<Object> handleHttpMediaTypeNotSupported(final HttpMediaTypeNotSupportedException ex, final HttpHeaders headers, final HttpStatus status, final WebRequest request) {
    logger.info(ex.getClass().getName());
    //
    final StringBuilder builder = new StringBuilder();
    builder.append(ex.getContentType());
    builder.append(" media type is not supported. Supported media types are ");
    ex.getSupportedMediaTypes().forEach(t -> builder.append(t + " "));

    final ApiError apiError = new ApiError(HttpStatus.UNSUPPORTED_MEDIA_TYPE, ex.getLocalizedMessage(), builder.substring(0, builder.length() - 2));
    return new ResponseEntity<Object>(apiError, new HttpHeaders(), apiError.getStatus());
}
 
Example #15
Source File: GlobalDefaultExceptionHandler.java    From unified-dispose-springboot with Apache License 2.0 5 votes vote down vote up
/**
 * HttpMediaTypeNotSupportedException 415 异常处理
 */
@ExceptionHandler(HttpMediaTypeNotSupportedException.class)
public Result handlerHttpMediaTypeNotSupportedException(
        HttpMediaTypeNotSupportedException e) throws Throwable {
    errorDispose(e);
    outPutErrorWarn(HttpMediaTypeNotSupportedException.class,
            CommonErrorCode.UNSUPPORTED_MEDIA_TYPE, e);
    return Result.ofFail(CommonErrorCode.UNSUPPORTED_MEDIA_TYPE);
}
 
Example #16
Source File: ExceptionAspect.java    From bookshop with MIT License 5 votes vote down vote up
/**
 * 415 - Unsupported Media Type
 */
@ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
@ExceptionHandler({ HttpMediaTypeNotSupportedException.class })
public Response handleHttpMediaTypeNotSupportedException(Exception e) {
    log.error("content_type_not_supported...", e);
    return new Response().failure("content_type_not_supported");
}
 
Example #17
Source File: ResponseEntityExceptionHandler.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Customize the response for HttpMediaTypeNotSupportedException.
 * <p>This method sets the "Accept" header and delegates to
 * {@link #handleExceptionInternal}.
 * @param ex the exception
 * @param headers the headers to be written to the response
 * @param status the selected response status
 * @param request the current request
 * @return a {@code ResponseEntity} instance
 */
protected ResponseEntity<Object> handleHttpMediaTypeNotSupported(HttpMediaTypeNotSupportedException ex,
		HttpHeaders headers, HttpStatus status, WebRequest request) {

	List<MediaType> mediaTypes = ex.getSupportedMediaTypes();
	if (!CollectionUtils.isEmpty(mediaTypes)) {
		headers.setAccept(mediaTypes);
	}

	return handleExceptionInternal(ex, null, headers, status, request);
}
 
Example #18
Source File: ExceptionAdvice.java    From EasyReport with Apache License 2.0 5 votes vote down vote up
/**
 * 415 - Unsupported Media Type
 */
@ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
@ExceptionHandler(HttpMediaTypeNotSupportedException.class)
public ResponseResult handleHttpMediaTypeNotSupportedException(final Exception e) {
    log.error(HttpStatus.UNSUPPORTED_MEDIA_TYPE.getReasonPhrase(), e);
    return ResponseResult.failure(SystemErrorCode.UNSUPPORTED_MEDIA_TYPE, e);
}
 
Example #19
Source File: RestExceptionHandler.java    From spring-boot-exception-handling with MIT License 5 votes vote down vote up
/**
 * Handle HttpMediaTypeNotSupportedException. This one triggers when JSON is invalid as well.
 *
 * @param ex      HttpMediaTypeNotSupportedException
 * @param headers HttpHeaders
 * @param status  HttpStatus
 * @param request WebRequest
 * @return the ApiError object
 */
@Override
protected ResponseEntity<Object> handleHttpMediaTypeNotSupported(
        HttpMediaTypeNotSupportedException ex,
        HttpHeaders headers,
        HttpStatus status,
        WebRequest request) {
    StringBuilder builder = new StringBuilder();
    builder.append(ex.getContentType());
    builder.append(" media type is not supported. Supported media types are ");
    ex.getSupportedMediaTypes().forEach(t -> builder.append(t).append(", "));
    return buildResponseEntity(new ApiError(HttpStatus.UNSUPPORTED_MEDIA_TYPE, builder.substring(0, builder.length() - 2), ex));
}
 
Example #20
Source File: RestExceptionHandler.java    From spring-glee-o-meter with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Handle HttpMediaTypeNotSupportedException. This one triggers when JSON is invalid as well.
 *
 * @param ex      HttpMediaTypeNotSupportedException
 * @param headers HttpHeaders
 * @param status  HttpStatus
 * @param request WebRequest
 * @return the ApiError object
 */
@Override
protected ResponseEntity<Object> handleHttpMediaTypeNotSupported(
        HttpMediaTypeNotSupportedException ex,
        HttpHeaders headers,
        HttpStatus status,
        WebRequest request) {
    StringBuilder builder = new StringBuilder();
    builder.append(ex.getContentType());
    builder.append(" media type is not supported. Supported media types are ");
    ex.getSupportedMediaTypes().forEach(t -> builder.append(t).append(", "));
    return buildResponseEntity(new ApiError(HttpStatus.UNSUPPORTED_MEDIA_TYPE, builder.substring(0, builder.length() - 2), ex));
}
 
Example #21
Source File: DefaultExceptionHandler.java    From spring-rest-server with GNU Lesser General Public License v3.0 5 votes vote down vote up
@RequestMapping(produces = {Versions.V1_0, Versions.V2_0})
@ExceptionHandler(HttpMediaTypeNotSupportedException.class)
@ResponseStatus(value = HttpStatus.UNSUPPORTED_MEDIA_TYPE)
public @ResponseBody Map<String, Object> handleUnsupportedMediaTypeException(HttpMediaTypeNotSupportedException ex) throws IOException {
    Map<String, Object>  map = Maps.newHashMap();
    map.put("error", "Unsupported Media Type");
    map.put("cause", ex.getLocalizedMessage());
    map.put("supported", ex.getSupportedMediaTypes());
    return map;
}
 
Example #22
Source File: RestControllerExceptionTranslator.java    From hsweb-framework with Apache License 2.0 5 votes vote down vote up
/**
 * ContentType不支持异常
 * 比如:@RequestBody注解,需要Content-Type: application/json, 但是请求未指定使用的默认的 Content-Type: application/x-www-form-urlencoded
 */
@ExceptionHandler(HttpMediaTypeNotSupportedException.class)
@ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
ResponseMessage handleException(HttpMediaTypeNotSupportedException exception) {
    return ResponseMessage.error(HttpStatus.UNSUPPORTED_MEDIA_TYPE.value(),
            "不支持的请求类型:" + exception.getContentType().toString())
            .result(exception.getSupportedMediaTypes()
                    .stream()
                    .map(MediaType::toString)
                    .collect(Collectors.toList()));
}
 
Example #23
Source File: HttpEntityMethodProcessorMockTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void shouldFailResolvingWhenContentTypeNotSupported() throws Exception {
	servletRequest.setMethod("POST");
	servletRequest.setContent("some content".getBytes(StandardCharsets.UTF_8));
	this.thrown.expect(HttpMediaTypeNotSupportedException.class);
	processor.resolveArgument(paramHttpEntity, mavContainer, webRequest, null);
}
 
Example #24
Source File: HttpEntityMethodProcessorMockTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@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);

	this.thrown.expect(HttpMediaTypeNotSupportedException.class);
	processor.resolveArgument(paramHttpEntity, mavContainer, webRequest, null);
}
 
Example #25
Source File: ResponseEntityExceptionHandlerTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example #26
Source File: HttpEntityMethodProcessorMockTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test(expected = HttpMediaTypeNotSupportedException.class)
public void resolveArgumentNoContentType() throws Exception {
	servletRequest.setMethod("POST");
	servletRequest.setContent("some content".getBytes(Charset.forName("UTF-8")));
	processor.resolveArgument(paramHttpEntity, mavContainer, webRequest, null);
	fail("Expected exception");
}
 
Example #27
Source File: ConsumesRequestCondition.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean matchMediaType(HttpServletRequest request) throws HttpMediaTypeNotSupportedException {
	try {
		MediaType contentType = StringUtils.hasLength(request.getContentType()) ?
				MediaType.parseMediaType(request.getContentType()) :
				MediaType.APPLICATION_OCTET_STREAM;
				return getMediaType().includes(contentType);
	}
	catch (InvalidMediaTypeException ex) {
		throw new HttpMediaTypeNotSupportedException(
				"Can't parse Content-Type [" + request.getContentType() + "]: " + ex.getMessage());
	}
}
 
Example #28
Source File: ResponseEntityExceptionHandlerTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@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());
}
 
Example #29
Source File: ResponseEntityExceptionHandler.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Customize the response for HttpMediaTypeNotSupportedException.
 * <p>This method sets the "Accept" header and delegates to
 * {@link #handleExceptionInternal}.
 * @param ex the exception
 * @param headers the headers to be written to the response
 * @param status the selected response status
 * @param request the current request
 * @return a {@code ResponseEntity} instance
 */
protected ResponseEntity<Object> handleHttpMediaTypeNotSupported(HttpMediaTypeNotSupportedException ex,
		HttpHeaders headers, HttpStatus status, WebRequest request) {

	List<MediaType> mediaTypes = ex.getSupportedMediaTypes();
	if (!CollectionUtils.isEmpty(mediaTypes)) {
		headers.setAccept(mediaTypes);
	}

	return handleExceptionInternal(ex, null, headers, status, request);
}
 
Example #30
Source File: GlobalHandlerExceptionResolver.java    From fast-family-master with Apache License 2.0 5 votes vote down vote up
@ResponseStatus(value = HttpStatus.UNSUPPORTED_MEDIA_TYPE)
@ExceptionHandler(HttpMediaTypeNotSupportedException.class)
public Response handleHttpMediaTypeNotSupportedException(
        HttpMediaTypeNotSupportedException e) {
    logError("httpMediaTypeNotSupportedException", e.getMessage(), e);
    return Response
            .fail(415,
                    String.format("媒体类型%s错误", e.getContentType()));
}