@ExceptionHandler(MultipartException.class) @ResponseStatus(HttpStatus.PAYLOAD_TOO_LARGE) public ModelAndView handleMultipartError(HttpServletRequest req, MultipartException exception) throws Exception { ModelAndView mav = new ModelAndView(); mav.addObject("page", new Page("mzTabValidator", versionNumber, gaId)); mav.addObject("error", exception); mav.addObject("url", req.getRequestURL()); mav.addObject("timestamp", new Date().toString()); mav.addObject("status", 413); mav.setViewName("error"); return mav; }
@ExceptionHandler({MultipartException.class}) public ModelAndView handleMaxSizeException(Exception excptn, HttpServletRequest request) { ModelAndView model = new ModelAndView("sessionexpired"); if (excptn instanceof MultipartException) { MultipartException mEx = (MultipartException) excptn; if (excptn instanceof MaxUploadSizeExceededException) { log.info("MaxUploadSizeExceededException for file : "); model.addObject("ERROR_MESSAGE_HEADER", "File Size exceeded Limit"); model.addObject("ERROR_MESSAGE_BODY", "Please upload files under the stipulated size limit."); } else { model.addObject("ERROR_MESSAGE_HEADER", "Internal Server Error"); model.addObject("errors", "Unexpected error: " + excptn.getMessage()); } } else { model.addObject("ERROR_MESSAGE_HEADER", "Internal Server Error"); model.addObject("errors", "Unexpected error: " + excptn.getMessage()); } return model; }
@Override public InputStream getBody() throws IOException { if (this.multipartRequest instanceof StandardMultipartHttpServletRequest) { try { return this.multipartRequest.getPart(this.partName).getInputStream(); } catch (Exception ex) { throw new MultipartException("Could not parse multipart servlet request", ex); } } else { MultipartFile file = this.multipartRequest.getFile(this.partName); if (file != null) { return file.getInputStream(); } else { String paramValue = this.multipartRequest.getParameter(this.partName); return new ByteArrayInputStream(paramValue.getBytes(FORM_CHARSET)); } } }
private void parseRequest(HttpServletRequest request) { try { Collection<Part> parts = request.getParts(); this.multipartParameterNames = new LinkedHashSet<String>(parts.size()); MultiValueMap<String, MultipartFile> files = new LinkedMultiValueMap<String, MultipartFile>(parts.size()); for (Part part : parts) { String filename = extractFilename(part.getHeader(CONTENT_DISPOSITION)); if (filename != null) { files.add(part.getName(), new StandardMultipartFile(part, filename)); } else { this.multipartParameterNames.add(part.getName()); } } setMultipartFiles(files); } catch (Exception ex) { throw new MultipartException("Could not parse multipart servlet request", ex); } }
@Override public HttpHeaders getMultipartHeaders(String paramOrFileName) { try { Part part = getPart(paramOrFileName); if (part != null) { HttpHeaders headers = new HttpHeaders(); for (String headerName : part.getHeaderNames()) { headers.put(headerName, new ArrayList<String>(part.getHeaders(headerName))); } return headers; } else { return null; } } catch (Exception ex) { throw new MultipartException("Could not access multipart servlet request", ex); } }
@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()); } }
@Override public MultipartActionRequest resolveMultipart(ActionRequest request) throws MultipartException { if (request.getAttribute("fail") != null) { throw new MaxUploadSizeExceededException(1000); } if (request instanceof MultipartActionRequest) { throw new IllegalStateException("Already a multipart request"); } if (request.getAttribute("resolved") != null) { throw new IllegalStateException("Already resolved"); } request.setAttribute("resolved", Boolean.TRUE); MultiValueMap<String, MultipartFile> files = new LinkedMultiValueMap<String, MultipartFile>(); files.set("someFile", new MockMultipartFile("someFile", "someContent".getBytes())); Map<String, String[]> params = new HashMap<String, String[]>(); params.put("someParam", new String[] {"someParam"}); return new DefaultMultipartActionRequest(request, files, params, Collections.<String, String>emptyMap()); }
/** * Convert the request into a multipart request, and make multipart resolver available. * <p>If no multipart resolver is set, simply use the existing request. * @param request current HTTP request * @return the processed request (multipart wrapper if necessary) * @see MultipartResolver#resolveMultipart */ protected HttpServletRequest checkMultipart(HttpServletRequest request) throws MultipartException { if (this.multipartResolver != null && this.multipartResolver.isMultipart(request)) { if (WebUtils.getNativeRequest(request, MultipartHttpServletRequest.class) != null) { logger.debug("Request is already a MultipartHttpServletRequest - if not in a forward, " + "this typically results from an additional MultipartFilter in web.xml"); } else if (request.getAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE) instanceof MultipartException) { logger.debug("Multipart resolution failed for current request before - " + "skipping re-resolution for undisturbed error rendering"); } else { return this.multipartResolver.resolveMultipart(request); } } // If not returned before: return original request. return request; }
@Override public InputStream getBody() throws IOException { if (this.multipartRequest instanceof StandardMultipartHttpServletRequest) { try { return this.multipartRequest.getPart(this.partName).getInputStream(); } catch (Exception ex) { throw new MultipartException("Could not parse multipart servlet request", ex); } } else { MultipartFile file = this.multipartRequest.getFile(this.partName); if (file != null) { return file.getInputStream(); } else { String paramValue = this.multipartRequest.getParameter(this.partName); return new ByteArrayInputStream(paramValue.getBytes(determineEncoding())); } } }
private void parseRequest(HttpServletRequest request) { try { Collection<Part> parts = request.getParts(); this.multipartParameterNames = new LinkedHashSet<String>(parts.size()); MultiValueMap<String, MultipartFile> files = new LinkedMultiValueMap<String, MultipartFile>(parts.size()); for (Part part : parts) { String disposition = part.getHeader(CONTENT_DISPOSITION); String filename = extractFilename(disposition); if (filename == null) { filename = extractFilenameWithCharset(disposition); } if (filename != null) { files.add(part.getName(), new StandardMultipartFile(part, filename)); } else { this.multipartParameterNames.add(part.getName()); } } setMultipartFiles(files); } catch (Exception ex) { throw new MultipartException("Could not parse multipart servlet request", ex); } }
public HttpHeaders getMultipartHeaders(String paramOrFileName) { try { Part part = getPart(paramOrFileName); if (part != null) { HttpHeaders headers = new HttpHeaders(); for (String headerName : part.getHeaderNames()) { headers.put(headerName, new ArrayList<String>(part.getHeaders(headerName))); } return headers; } else { return null; } } catch (Exception ex) { throw new MultipartException("Could not access multipart servlet request", ex); } }
@Override public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { if(ex instanceof AccessDeniedException) { return this.deniedHandler(request, response); } String ip = request.getRemoteAddr(); if(ex instanceof MultipartException) { log.warn("MultipartException with this client " + ip + ". We can assume that the client has canceled his request (because of a double-click / double-submit of the form for example).", ex); } else { log.error("Uncaught exception with this client " + ip, ex); } // hack for logging uploads failed if(request.getServletPath().matches("/postecandidatures/[0-9]*/addFile")) { String posteCandidatureId = request.getServletPath().replaceAll("/postecandidatures/([0-9]*)/addFile", "$1"); PosteCandidature posteCandidature = PosteCandidature.findPosteCandidature(Long.valueOf(posteCandidatureId)); logService.logActionFile(LogService.UPLOAD_FAILED_ACTION, posteCandidature, null, request, new Date()); } //response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); ModelAndView modelAndview = new ModelAndView("uncaughtException"); modelAndview.addObject("exception", ex); return modelAndview; }
@Test public void should_find_cause_from_exception_and_return_appropriate_code() { final FileUploadBase.FileSizeLimitExceededException fileSizeLimitExceededException = new FileUploadBase.FileSizeLimitExceededException("Too Big", 1234, 1024); final MultipartException multipartException = new MultipartException("Limit exceeded", fileSizeLimitExceededException); final ErrorStatusCodeAndMessage statusCodeAndMessage = resolver.resolveStatusCodeAndMessage(multipartException, "It broke", 500); assertThat(statusCodeAndMessage.getStatusCode(), equalTo(413)); }
@Override public String getMultipartContentType(String paramOrFileName) { try { Part part = getPart(paramOrFileName); return (part != null ? part.getContentType() : null); } catch (Exception ex) { throw new MultipartException("Could not access multipart servlet request", ex); } }
@ExceptionHandler(MultipartException.class) public ResponseEntity<UploadImagesDTO> handleMultipartException(Exception e){ UploadImagesDTO dto = new UploadImagesDTO("", false); if(e.getCause() instanceof IllegalStateException && e.getCause().getCause() instanceof FileUploadBase.SizeLimitExceededException) { return ResponseEntity .status(HttpStatus.PAYLOAD_TOO_LARGE) .body(dto); } else { e.printStackTrace(); return ResponseEntity .status(HttpStatus.INTERNAL_SERVER_ERROR) .body(dto); } }
@RequestMapping(value="/tagIdCheck", method=RequestMethod.GET, produces = "application/json;charset=UTF-8") @ResponseBody public EsupNfcTagLog tagIdCheck(@RequestParam(required=false) String csn) { log.debug("tagIdCheck with csn = " + csn); if(csn==null) { throw new MultipartException("csn or desfireId should not be null"); } EsupNfcTagLog esupNfcTagLog = null; Card card = null; try { card = Card.findCardsByCsn(csn).getSingleResult(); } catch(Exception e){ log.info("card not found ", e); } if(card!=null) { esupNfcTagLog = new EsupNfcTagLog(); esupNfcTagLog.setCsn(card.getCsn()); esupNfcTagLog.setEppn(card.getEppn()); esupNfcTagLog.setFirstname(card.getUser().getFirstname()); esupNfcTagLog.setLastname(card.getUser().getName()); log.info("tagIdCheck OK " + esupNfcTagLog); } else { log.info("tagIdCheck failed, " + csn + " not retrieved"); } return esupNfcTagLog; }
@ExceptionHandler(MultipartException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public Map<String,String> uploadErrorHandler(MultipartException e) throws Exception { Map message = new HashMap(); if (e.getCause().getMessage().contains("org.apache.tomcat.common.http.fileupload.FileUploadBase$FileSizeLimitExceededException")){ message.put("error","文件大小不应该超过" + maxSize); }else{ message.put("error","文件上传错误"); } return message; }
@ExceptionHandler(value = Exception.class) public ModelAndView jsonErrorHandler(HttpServletRequest request, HttpServletResponse response, Exception e) throws Exception { //错误数据 JsonResponse json = new JsonResponse(); if (e instanceof BusinessException) { json.setStatus(ResponseStatus.BUSINESS_FAILED); json.setMessage(e.getMessage()); } else if (e instanceof ValidateException) { json.setStatus(ResponseStatus.VALIDATE_ERR); json.setMessage(e.getMessage()); } else if (e instanceof LoginTimeoutException) { json.setStatus(ResponseStatus.LOGIN_TIME_OUT); json.setMessage(e.getMessage()); } else if (e instanceof NoPrivilegeException) { json.setStatus(ResponseStatus.NO_PRIVILEGE); json.setMessage(e.getMessage()); } else if (e instanceof MultipartException && e.getMessage().contains("FileSizeLimitExceededException")) { json.setStatus(ResponseStatus.BUSINESS_FAILED); json.setMessage(maxFileSizeErrorMsg); } else { json.setStatus(ResponseStatus.SYSTEM_ERR); json.setMessage(DEFAULT_EXCEPTION_MESSAGE); } logger.info("系统异常如下:" + e); String servletPath = request.getServletPath(); //约定返回 json 数据的地址必须后缀 .json if (!StringUtil.isEmpty(servletPath) && servletPath.endsWith(".json")) { returnJsonData(response, json); return null; } ModelAndView resPage = new ModelAndView("error"); resPage.addObject("status", json.getStatus()); resPage.addObject("message", json.getMessage()); return resPage; }
@Override public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object obj, Exception ex) { // System.out.println("==============异常开始============="); logger.error("==============Start============="); // ex.printStackTrace(); // 打印异常log logger.error(ex.getClass(), ex); // System.out.println("==============异常结束============="); // 异常结束 logger.error("==============End============="); if (ex instanceof MultipartException) { try { response.setContentType(C.CONTENT_TYPE_HTML_UTF_8); PrintWriter out = response.getWriter(); out.println(String.format(FileHandlerController.getUploadScript(), false, L.RESOLVE_MULTIPART_EXCEPTION, "[]")); out.flush(); out.close(); } catch (Exception e) { e.printStackTrace(); } return null; } else { ModelAndView mv = new ModelAndView("common/error"); mv.addObject("exception", ex.toString().replaceAll("\n", "<br/>")); return mv; } }
@ExceptionHandler(MultipartException.class) @ResponseBody public ResponseEntity<Object> handleFileException(Exception ex, final HttpHeaders headers, WebRequest request) { ex.printStackTrace(); final AitException AitException = new AitException(HttpStatus.BAD_REQUEST, ex.getLocalizedMessage(), "Error al cargar informacion adicional"); return handleExceptionInternal(ex, AitException, headers, AitException.getStatus(), request); }
@Override protected MultipartParsingResult parseRequest(HttpServletRequest request) throws MultipartException { try { return super.parseRequest(request); } catch (MaxUploadSizeExceededException e) { request.setAttribute(MAX_UPLOAD_SIZE_EXCEEDED_KEY, e); return parseFileItems(Collections.<FileItem> emptyList(), null); } }
/** * Convert the request into a multipart request, and make multipart resolver available. * If no multipart resolver is set, simply use the existing request. * @param request current HTTP request * @return the processed request (multipart wrapper if necessary) */ protected ActionRequest checkMultipart(ActionRequest request) throws MultipartException { if (this.multipartResolver != null && this.multipartResolver.isMultipart(request)) { if (request instanceof MultipartActionRequest) { logger.debug("Request is already a MultipartActionRequest - probably in a forward"); } else { return this.multipartResolver.resolveMultipart(request); } } // If not returned before: return original request. return request; }
/** * 拦截 {@link MultipartException} 异常。 */ @ExceptionHandler(MultipartException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) @ResponseBody public Object handleException(MultipartException e, ServletWebRequest request) { return handleFileUploadException(e, HttpStatus.BAD_REQUEST.value(), "请选择您要上传的文件", request); }
@ExceptionHandler @ResponseBody @ResponseStatus(HttpStatus.BAD_REQUEST) ErrorListDto handleMultipartException(MultipartException exception) { FileSizeLimitExceededException fileSizeException = findFileSizeLimitExceededException(exception); if (fileSizeException != null) { return new ErrorListDto(new ErrorDto(fileSizeException.getFileName(), "global.error.import.file-size-limit-exceeded", String.valueOf(fileSizeException.getActualSize()), null)); } // return the message as it is return new ErrorListDto(new ErrorDto(null, exception.getLocalizedMessage(), null, null)); }
@Override public MultipartHttpServletRequest resolveMultipart(HttpServletRequest request) throws MultipartException { if(maxUploadSize>=0){ long requestSize = RequestUtils.getContentLength(request); if(requestSize!=-1 && requestSize>maxUploadSize){ throw new MaxUploadSizeExceededException(maxUploadSize); } } return super.resolveMultipart(request); }
public MultipartHttpServletRequest resolveMultipart( HttpServletRequest request) throws MultipartException { try { CosMultipartRequest multipartRequest = newMultipartRequest(request); if (logger.isDebugEnabled()) { Set<String> fileNames = multipartRequest.getFileNames(); for (String fileName : fileNames) { File file = multipartRequest.getFile(fileName); logger.debug("Found multipart file '" + fileName + "' of size " + (file != null ? file.length() : 0) + " bytes with original filename [" + multipartRequest.getOriginalFileName(fileName) + "]" + (file != null ? "stored at [" + file.getAbsolutePath() + "]" : "empty")); } } return new CosMultipartHttpServletRequest(request, multipartRequest); } catch (IOException ex) { // Unfortunately, COS always throws an IOException, // so we need to check the error message here! if (ex.getMessage().indexOf("exceeds limit") != -1) { throw new MaxUploadSizeExceededException(this.maxUploadSize, ex); } else { throw new MultipartException( "Could not parse multipart request", ex); } } }
@ExceptionHandler(MultipartException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) @ResponseBody public ErrorResponseDto handleMultipartException(Exception exception, HttpServletRequest request) { return globalExceptionMapping.handleOtherException(exception, request); }
/** * Convert the request into a multipart request, and make multipart resolver available. * <p>If no multipart resolver is set, simply use the existing request. * @param request current HTTP request * @return the processed request (multipart wrapper if necessary) * @see MultipartResolver#resolveMultipart */ protected HttpServletRequest checkMultipart(HttpServletRequest request) throws MultipartException { if (this.multipartResolver != null && this.multipartResolver.isMultipart(request)) { if (request instanceof MultipartHttpServletRequest) { logger.debug("Request is already a MultipartHttpServletRequest - if not in a forward, " + "this typically results from an additional MultipartFilter in web.xml"); } else { return this.multipartResolver.resolveMultipart(request); } } // If not returned before: return original request. return request; }
/** * Method override in order to be able to catch the size exceeded exception and send back an * appropriate http code to the caller. */ @Override protected MultipartParsingResult parseRequest(HttpServletRequest request) { try { return super.parseRequest(request); } catch (MultipartException e) { throw new MaxUploadSizeExceededException(); } }
@Override public MultipartHttpServletRequest resolveMultipart(HttpServletRequest request) throws MultipartException { return new StandardMultipartHttpServletRequest(request, this.resolveLazily); }
private void assertIsMultipartRequest(HttpServletRequest request) { String contentType = request.getContentType(); if (contentType == null || !contentType.toLowerCase().startsWith("multipart/")) { throw new MultipartException("The current request is not a multipart request"); } }
@ExceptionHandler( MultipartException.class ) public ResponseEntity multipartExceptionHandler ( MultipartException e ) { LogUtils.getLogger().error( "error" , e ); return ResponseEntityPro.unauthorized( e.getMessage() ); }