org.springframework.web.multipart.support.MissingServletRequestPartException Java Examples

The following examples show how to use org.springframework.web.multipart.support.MissingServletRequestPartException. 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: WxArgumentResolver.java    From FastBootWeixin with Apache License 2.0 8 votes vote down vote up
@Override
protected void handleMissingValue(String name, MethodParameter parameter, NativeWebRequest request)
        throws Exception {

    HttpServletRequest servletRequest = request.getNativeRequest(HttpServletRequest.class);
    if (MultipartResolutionDelegate.isMultipartArgument(parameter)) {
        if (!MultipartResolutionDelegate.isMultipartRequest(servletRequest)) {
            throw new MultipartException("Current request is not a multipart request");
        } else {
            throw new MissingServletRequestPartException(name);
        }
    } else {
        throw new MissingServletRequestParameterException(name,
                parameter.getNestedParameterType().getSimpleName());
    }
}
 
Example #2
Source File: RequestParamMethodArgumentResolver.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
protected void handleMissingValue(String name, MethodParameter parameter, NativeWebRequest request)
		throws Exception {

	HttpServletRequest servletRequest = request.getNativeRequest(HttpServletRequest.class);
	if (MultipartResolutionDelegate.isMultipartArgument(parameter)) {
		if (servletRequest == null || !MultipartResolutionDelegate.isMultipartRequest(servletRequest)) {
			throw new MultipartException("Current request is not a multipart request");
		}
		else {
			throw new MissingServletRequestPartException(name);
		}
	}
	else {
		throw new MissingServletRequestParameterException(name,
				parameter.getNestedParameterType().getSimpleName());
	}
}
 
Example #3
Source File: RequestParamMethodArgumentResolver.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
protected void handleMissingValue(String name, MethodParameter parameter, NativeWebRequest request)
		throws Exception {

	HttpServletRequest servletRequest = request.getNativeRequest(HttpServletRequest.class);
	if (MultipartResolutionDelegate.isMultipartArgument(parameter)) {
		if (!MultipartResolutionDelegate.isMultipartRequest(servletRequest)) {
			throw new MultipartException("Current request is not a multipart request");
		}
		else {
			throw new MissingServletRequestPartException(name);
		}
	}
	else {
		throw new MissingServletRequestParameterException(name,
				parameter.getNestedParameterType().getSimpleName());
	}
}
 
Example #4
Source File: RequestPartMethodArgumentResolverTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void resolveRequestPartRequired() throws Exception {
	try {
		testResolveArgument(null, paramValidRequestPart);
		fail("Expected exception");
	}
	catch (MissingServletRequestPartException ex) {
		assertEquals("requestPart", ex.getRequestPartName());
	}
}
 
Example #5
Source File: RequestParamMethodArgumentResolver.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
protected void handleMissingValue(String name, MethodParameter parameter, NativeWebRequest request)
		throws Exception {

	HttpServletRequest servletRequest = request.getNativeRequest(HttpServletRequest.class);
	if (MultipartResolutionDelegate.isMultipartArgument(parameter)) {
		if (servletRequest == null || !MultipartResolutionDelegate.isMultipartRequest(servletRequest)) {
			throw new MultipartException("Current request is not a multipart request");
		}
		else {
			throw new MissingServletRequestPartException(name);
		}
	}
	else {
		throw new MissingServletRequestParameterException(name,
				parameter.getNestedParameterType().getSimpleName());
	}
}
 
Example #6
Source File: OneOffSpringWebMvcFrameworkExceptionHandlerListenerTest.java    From backstopper with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldHandleException_returns_MALFORMED_REQUEST_for_MissingServletRequestPartException() {
    // given
    String partName = UUID.randomUUID().toString();
    MissingServletRequestPartException ex = new MissingServletRequestPartException(partName);

    ApiError expectedResult = new ApiErrorWithMetadata(
        testProjectApiErrors.getMalformedRequestApiError(),
        Pair.of("missing_required_part", partName)
    );

    // when
    ApiExceptionHandlerListenerResult result = listener.shouldHandleException(ex);

    // then
    validateResponse(result, true, singletonList(expectedResult));
}
 
Example #7
Source File: OneOffSpringWebMvcFrameworkExceptionHandlerListener.java    From backstopper with Apache License 2.0 5 votes vote down vote up
@Override
protected @NotNull ApiExceptionHandlerListenerResult handleSpringMvcOrWebfluxSpecificFrameworkExceptions(
    @NotNull Throwable ex
) {
    List<Pair<String, String>> extraDetailsForLogging = new ArrayList<>();
    
    if (ex instanceof ServletRequestBindingException) {
        return handleServletRequestBindingException((ServletRequestBindingException)ex, extraDetailsForLogging);
    }

    if (ex instanceof HttpMediaTypeNotAcceptableException) {
        return handleError(projectApiErrors.getNoAcceptableRepresentationApiError(), extraDetailsForLogging);
    }

    if (ex instanceof HttpMediaTypeNotSupportedException) {
        return handleError(projectApiErrors.getUnsupportedMediaTypeApiError(), extraDetailsForLogging);
    }

    if (ex instanceof HttpRequestMethodNotSupportedException) {
        return handleError(projectApiErrors.getMethodNotAllowedApiError(), extraDetailsForLogging);
    }

    if (ex instanceof MissingServletRequestPartException) {
        MissingServletRequestPartException detailsEx = (MissingServletRequestPartException)ex;
        return handleError(
            new ApiErrorWithMetadata(
                projectApiErrors.getMalformedRequestApiError(),
                Pair.of("missing_required_part", (Object)detailsEx.getRequestPartName())
            ),
            extraDetailsForLogging
        );
    }

    // This exception is not handled here.
    return ApiExceptionHandlerListenerResult.ignoreResponse();
}
 
Example #8
Source File: RequestParamMethodArgumentResolverTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test(expected = MissingServletRequestPartException.class)
public void missingMultipartFile() throws Exception {
	request.setMethod("POST");
	request.setContentType("multipart/form-data");
	MethodParameter param = this.testMethod.annotPresent(RequestParam.class).arg(MultipartFile.class);
	resolver.resolveArgument(param, null, webRequest, null);
	fail("Expected exception: no such part found");
}
 
Example #9
Source File: ServletWebErrorHandler.java    From errors-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
/**
 * Only handles {@link ServletException}s and {@link HttpMessageNotReadableException}s.
 *
 * @param exception The exception to examine.
 * @return {@code true} when can handle the {@code exception}, {@code false} otherwise.
 */
@Override
public boolean canHandle(Throwable exception) {
    return exception instanceof HttpMediaTypeNotAcceptableException ||
        exception instanceof HttpMediaTypeNotSupportedException ||
        exception instanceof HttpRequestMethodNotSupportedException ||
        exception instanceof MissingServletRequestParameterException ||
        exception instanceof MissingServletRequestPartException ||
        exception instanceof NoHandlerFoundException ||
        exception instanceof HttpMessageNotReadableException;
}
 
Example #10
Source File: CurrentAccountMethodArgumentResolver.java    From XUpdateService with Apache License 2.0 5 votes vote down vote up
@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
    Account account = (Account) nativeWebRequest.getAttribute(Constants.CURRENT_ACCOUNT, RequestAttributes.SCOPE_REQUEST);
    if (account != null) {
        return account;
    }
    throw new MissingServletRequestPartException(Constants.CURRENT_ACCOUNT);
}
 
Example #11
Source File: CustomRestExceptionHandler.java    From xxproject with Apache License 2.0 5 votes vote down vote up
@Override
protected ResponseEntity<Object> handleMissingServletRequestPart(final MissingServletRequestPartException ex, final HttpHeaders headers, final HttpStatus status, final WebRequest request) {
    logger.info(ex.getClass().getName());
    //
    final String error = ex.getRequestPartName() + " part is missing";
    final ApiError apiError = new ApiError(HttpStatus.BAD_REQUEST, ex.getLocalizedMessage(), error);
    return new ResponseEntity<Object>(apiError, new HttpHeaders(), apiError.getStatus());
}
 
Example #12
Source File: BaseController.java    From j360-dubbo-app-all with Apache License 2.0 5 votes vote down vote up
@ExceptionHandler({ServletRequestBindingException.class,
        HttpMediaTypeNotAcceptableException.class,
        HttpMediaTypeNotSupportedException.class,
        HttpMessageNotReadableException.class,
        HttpRequestMethodNotSupportedException.class,
        MissingServletRequestParameterException.class,
        MissingServletRequestPartException.class,
        TypeMismatchException.class
})
@ResponseBody
public ApiResponse ServletRequestBindingExHandler(Exception ex) {
    return createExResult(new ValidationException(ex));
}
 
Example #13
Source File: DefaultHandlerExceptionResolverTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void handleMissingServletRequestPartException() throws Exception {
	MissingServletRequestPartException ex = new MissingServletRequestPartException("name");
	ModelAndView mav = exceptionResolver.resolveException(request, response, null, ex);
	assertNotNull("No ModelAndView returned", mav);
	assertTrue("No Empty ModelAndView returned", mav.isEmpty());
	assertEquals("Invalid status code", 400, response.getStatus());
	assertEquals("Required request part 'name' is not present.", response.getErrorMessage());
}
 
Example #14
Source File: RequestPartMethodArgumentResolverTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void resolveRequestPartRequired() throws Exception {
	try {
		testResolveArgument(null, paramValidRequestPart);
		fail("Expected exception");
	}
	catch (MissingServletRequestPartException ex) {
		assertEquals("requestPart", ex.getRequestPartName());
	}
}
 
Example #15
Source File: ServletWebErrorHandlerTest.java    From errors-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
private Object[] provideParamsForCanHandle() {
    return p(
        p(null, false),
        p(new RuntimeException(), false),
        p(new NoHandlerFoundException(null, null, null), true),
        p(new HttpMessageNotReadableException("", mock(HttpInputMessage.class)), true),
        p(new MissingServletRequestParameterException("name", "String"), true),
        p(new HttpMediaTypeNotAcceptableException(""), true),
        p(new HttpMediaTypeNotSupportedException(""), true),
        p(new HttpRequestMethodNotSupportedException(""), true),
        p(new MissingServletRequestPartException("file"), true)
    );
}
 
Example #16
Source File: MissingServletRequestPartAdviceTrait.java    From problem-spring-web with MIT License 5 votes vote down vote up
@API(status = INTERNAL)
@ExceptionHandler
default ResponseEntity<Problem> handleMissingServletRequestPart(
        final MissingServletRequestPartException exception,
        final NativeWebRequest request) {
    return create(Status.BAD_REQUEST, exception, request);
}
 
Example #17
Source File: AbstractRestExceptionHandler.java    From sinavi-jfw with Apache License 2.0 5 votes vote down vote up
/**
 * {@link MissingServletRequestPartException}をハンドリングします。
 * @param e {@link MissingServletRequestPartException}
 * @return {@link ErrorMessage}
 *         HTTPステータス 400 でレスポンスを返却します。
 */
@ExceptionHandler(MissingServletRequestPartException.class)
@ResponseBody
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
@Override
public ErrorMessage handle(MissingServletRequestPartException e) {
    if (L.isDebugEnabled()) {
        L.debug(R.getString("D-SPRINGMVC-REST-HANDLER#0011"), e);
    }
    ErrorMessage error = createClientErrorMessage(HttpStatus.BAD_REQUEST);
    warn(error, e);
    return error;
}
 
Example #18
Source File: RestDefaultExceptionHandlerTest.java    From sinavi-jfw with Apache License 2.0 5 votes vote down vote up
@Test
public void MissingServletRequestPartExceptionをハンドリングできる() {
    MissingServletRequestPartException ex = new MissingServletRequestPartException("partName");
    ErrorMessage message = this.exceptionHandlerSupport.handle(ex);
    assertThat(message, notNullValue());
    assertThat(message.getStatus(), is(400));
    assertThat(message.getMessage(), is("不正なリクエストです。"));
}
 
Example #19
Source File: RestExceptionHandler.java    From jakduk-api with MIT License 5 votes vote down vote up
/**
 * 파라미터 검증 실패.
 *
 * multipart/form-data 에서 key가 file이 아닐때.
 */
@Override
protected ResponseEntity<Object> handleMissingServletRequestPart(MissingServletRequestPartException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {

    ServiceError serviceError = ServiceError.FORM_VALIDATION_FAILED;
    RestErrorResponse restErrorResponse = new RestErrorResponse(serviceError);

    try {
        log.warn(ObjectMapperUtils.writeValueAsString(restErrorResponse), ex);
    } catch (JsonProcessingException ignore) {
        log.warn(ex.getLocalizedMessage(), ex);
    }

    return new ResponseEntity<>(restErrorResponse, HttpStatus.valueOf(serviceError.getHttpStatus()));
}
 
Example #20
Source File: RestHandlerExceptionResolverBuilder.java    From spring-rest-exception-handler with Apache License 2.0 5 votes vote down vote up
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;
    }
 
Example #21
Source File: SpringExceptionHandler.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
@ExceptionHandler({
  MissingServletRequestParameterException.class,
  ServletRequestBindingException.class,
  TypeMismatchException.class,
  HttpMessageNotReadableException.class,
  MethodArgumentNotValidException.class,
  MissingServletRequestPartException.class,
  BindException.class,
  ConstraintViolationException.class
})
public final Object handleSpringBadRequestException(Exception e, HandlerMethod handlerMethod) {
  return logAndHandleException(e, BAD_REQUEST, handlerMethod);
}
 
Example #22
Source File: CustomRestExceptionHandler.java    From tutorials with MIT License 5 votes vote down vote up
@Override
protected ResponseEntity<Object> handleMissingServletRequestPart(final MissingServletRequestPartException ex, final HttpHeaders headers, final HttpStatus status, final WebRequest request) {
    logger.info(ex.getClass().getName());
    //
    final String error = ex.getRequestPartName() + " part is missing";
    final ApiError apiError = new ApiError(HttpStatus.BAD_REQUEST, ex.getLocalizedMessage(), error);
    return new ResponseEntity<Object>(apiError, new HttpHeaders(), apiError.getStatus());
}
 
Example #23
Source File: RequestPartMethodArgumentResolverTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void resolveRequestPartRequired() throws Exception {
	try {
		testResolveArgument(null, paramValidRequestPart);
		fail("Expected exception");
	}
	catch (MissingServletRequestPartException ex) {
		assertEquals("requestPart", ex.getRequestPartName());
	}
}
 
Example #24
Source File: DefaultHandlerExceptionResolverTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void handleMissingServletRequestPartException() throws Exception {
	MissingServletRequestPartException ex = new MissingServletRequestPartException("name");
	ModelAndView mav = exceptionResolver.resolveException(request, response, null, ex);
	assertNotNull("No ModelAndView returned", mav);
	assertTrue("No Empty ModelAndView returned", mav.isEmpty());
	assertEquals("Invalid status code", 400, response.getStatus());
	assertTrue(response.getErrorMessage().contains("request part"));
	assertTrue(response.getErrorMessage().contains("name"));
	assertTrue(response.getErrorMessage().contains("not present"));
}
 
Example #25
Source File: DefaultHandlerExceptionResolverTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void handleMissingServletRequestPartException() throws Exception {
	MissingServletRequestPartException ex = new MissingServletRequestPartException("name");
	ModelAndView mav = exceptionResolver.resolveException(request, response, null, ex);
	assertNotNull("No ModelAndView returned", mav);
	assertTrue("No Empty ModelAndView returned", mav.isEmpty());
	assertEquals("Invalid status code", 400, response.getStatus());
	assertTrue(response.getErrorMessage().contains("request part"));
	assertTrue(response.getErrorMessage().contains("name"));
	assertTrue(response.getErrorMessage().contains("not present"));
}
 
Example #26
Source File: RequestParamMethodArgumentResolverTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test(expected = MissingServletRequestPartException.class)
public void missingMultipartFile() throws Exception {
	request.setMethod("POST");
	request.setContentType("multipart/form-data");
	MethodParameter param = this.testMethod.annotPresent(RequestParam.class).arg(MultipartFile.class);
	resolver.resolveArgument(param, null, webRequest, null);
	fail("Expected exception: no such part found");
}
 
Example #27
Source File: ResponseEntityExceptionHandlerTests.java    From java-technology-stack with MIT License 4 votes vote down vote up
@Test
public void missingServletRequestPart() {
	Exception ex = new MissingServletRequestPartException("partName");
	testException(ex);
}
 
Example #28
Source File: RequestPartMethodArgumentResolver.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Override
@Nullable
public Object resolveArgument(MethodParameter parameter, @Nullable ModelAndViewContainer mavContainer,
		NativeWebRequest request, @Nullable WebDataBinderFactory binderFactory) throws Exception {

	HttpServletRequest servletRequest = request.getNativeRequest(HttpServletRequest.class);
	Assert.state(servletRequest != null, "No HttpServletRequest");

	RequestPart requestPart = parameter.getParameterAnnotation(RequestPart.class);
	boolean isRequired = ((requestPart == null || requestPart.required()) && !parameter.isOptional());

	String name = getPartName(parameter, requestPart);
	parameter = parameter.nestedIfOptional();
	Object arg = null;

	Object mpArg = MultipartResolutionDelegate.resolveMultipartArgument(name, parameter, servletRequest);
	if (mpArg != MultipartResolutionDelegate.UNRESOLVABLE) {
		arg = mpArg;
	}
	else {
		try {
			HttpInputMessage inputMessage = new RequestPartServletServerHttpRequest(servletRequest, name);
			arg = readWithMessageConverters(inputMessage, parameter, parameter.getNestedGenericParameterType());
			if (binderFactory != null) {
				WebDataBinder binder = binderFactory.createBinder(request, arg, name);
				if (arg != null) {
					validateIfApplicable(binder, parameter);
					if (binder.getBindingResult().hasErrors() && isBindExceptionRequired(binder, parameter)) {
						throw new MethodArgumentNotValidException(parameter, binder.getBindingResult());
					}
				}
				if (mavContainer != null) {
					mavContainer.addAttribute(BindingResult.MODEL_KEY_PREFIX + name, binder.getBindingResult());
				}
			}
		}
		catch (MissingServletRequestPartException | MultipartException ex) {
			if (isRequired) {
				throw ex;
			}
		}
	}

	if (arg == null && isRequired) {
		if (!MultipartResolutionDelegate.isMultipartRequest(servletRequest)) {
			throw new MultipartException("Current request is not a multipart request");
		}
		else {
			throw new MissingServletRequestPartException(name);
		}
	}
	return adaptArgumentIfNecessary(arg, parameter);
}
 
Example #29
Source File: ResponseEntityExceptionHandlerTests.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Test
public void missingServletRequestPart() {
	Exception ex = new MissingServletRequestPartException("partName");
	testException(ex);
}
 
Example #30
Source File: ExceptionTranslatorTestController.java    From cubeai with Apache License 2.0 4 votes vote down vote up
@GetMapping("/test/missing-servlet-request-part")
public void missingServletRequestPartException() throws Exception {
    throw new MissingServletRequestPartException("missing Servlet request part");
}