@Override public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception ex) { if (ex instanceof MaxUploadSizeExceededException) { WebUtils.writeJson(httpServletResponse, "长传的文件大小超过" + ((MaxUploadSizeExceededException) ex).getMaxUploadSize() + "字节限制,上传失败!"); return null; } ModelAndView view = new ModelAndView(); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ex.printStackTrace(new PrintStream(byteArrayOutputStream)); String exception = byteArrayOutputStream.toString(); view.getModel().put("error", "URL:" + WebUtils.getWebUrlPath(httpServletRequest) + httpServletRequest.getRequestURI() + "\r\n\r\nERROR:" + exception); logger.error("[opencron]error:{}", ex.getLocalizedMessage()); view.setViewName("/error/500"); return view; }
@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 ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { FResult<String> result = null; if (ex instanceof HttpRequestMethodNotSupportedException) { HttpRequestMethodNotSupportedException newExp = (HttpRequestMethodNotSupportedException) ex; result = FResult.newFailure(HttpResponseCode.CLIENT_PARAM_INVALID, newExp.getMessage()); } else if (ex instanceof MaxUploadSizeExceededException) { result = FResult.newFailure(HttpResponseCode.CLIENT_PARAM_INVALID, "上传文件大小超出限制"); } else if (ex instanceof SizeLimitExceededException) { result = FResult.newFailure(HttpResponseCode.CLIENT_PARAM_INVALID, "上传文件大小超出限制"); } else { result = FResult.newFailure(HttpResponseCode.SERVER_ERROR, ex.getMessage()); } ServletUtil.responseOutWithJson(response, result); return null; }
@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()); }
/** * Implementation of the exception resolving method which will only handle the * {@link MaxUploadSizeExceededException}. * * @param request * the current HTTP request * @param response * the response * @param handler * the executed handler, which is null in case of an MaxUploadSizeExceededException * @param ex * the exception that got thrown * @return the model and view or null if the exception is not a MaxUploadSizeExceededException * or no view is defined */ @Override public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { if (ex instanceof MaxUploadSizeExceededException) { String errorMessage = MessageHelper.getText(request, "error.blogpost.upload.filesize.limit", new Object[] { getHumanReadableUploadSizeLimit() }); String targetPath = ClientUrlHelper.removeIds(request.getServletPath() + request.getPathInfo()); String view = null; if (requestMappings != null) { view = requestMappings.get(targetPath); } if (view != null) { MessageHelper.saveErrorMessage(request, errorMessage); MessageHelper.setMessageTarget(request, targetPath); return new ModelAndView(ControllerHelper.replaceModuleInViewName(view)); } return prepareAjaxModelAndView(request, response, errorMessage); } return null; }
@ExceptionHandler(MaxUploadSizeExceededException.class) public ModelAndView maxUploadSizeException(Exception ex) { ModelAndView view = new ModelAndView("views/file/error"); postExecute(view.getModel(), new PostAction() { @Override public void invoke(PostResult r) { MaxUploadSizeExceededException e = (MaxUploadSizeExceededException) ex; r.setError("上传的文件超过最大限制 %d 。", e.getMaxUploadSize()); } }); return view; }
@Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { try { super.doFilterInternal(request, response, filterChain); } catch (MaxUploadSizeExceededException e) { String msg = "文件超过限制:"+LangUtils.getCauseServiceException(e).getMessage(); logger.error(msg); if(RequestUtils.getResponseType(request)==ResponseType.JSON){ DataResult<?> dataResult = DataResults.error(msg).build(); ResponseUtils.renderObjectAsJson(response, dataResult); }else{ response.getWriter().print(msg); } } }
protected void checkFileTypes(List<MultipartFile> fileItems, UploadFileValidator validator){ List<String> allowed = validator!=null?Arrays.asList(validator.allowedPostfix()):Arrays.asList(DEFAULT_ALLOW_FILE_TYPES); for(MultipartFile item : fileItems){ String postfix = FileUtils.getExtendName(item.getOriginalFilename().toLowerCase()); if(validator==null){ if(!allowed.contains(postfix)) throw new ServiceException("It's not allowed file type. file: " + item.getOriginalFilename(), UplaodErrorCode.NOT_ALLOW_FILE); }else{ if(!allowed.contains(postfix)) throw new ServiceException(validator.allowedPostfixErrorMessage() + " file: " + item.getOriginalFilename(), UplaodErrorCode.NOT_ALLOW_FILE); if(item.getSize()>validator.maxUploadSize()) throw new MaxUploadSizeExceededException(validator.maxUploadSize()); } // throw new MaxUploadSizeExceededException(validator.maxUploadSize()); } }
@Override public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { // the stacktrace will be printed by spring's DispatcherServlet // we are only logging the request url and headeres here logger.warn("An exception occurred when invoking the following URL: " + request.getRequestURL() + " . Requester IP is " + request.getRemoteAddr() + ", User-Agent: " + request.getHeader("User-Agent")); if (ex instanceof MaxUploadSizeExceededException) { return new ModelAndView("error/maxFileSizeExceeded"); } response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return null; }
/** * 带文件大小限制的构造 * * @param file * MultipartFile * @param maxSize2KB * 限制文件大小 * @throws IOException */ public UploadEntityImp(MultipartFile file, long maxSizeByKB) throws MaxUploadSizeExceededException { this.file = file; if (file == null) { throw new NullPointerException("MultipartFil 不能为空!"); } fileSizeByKB = file.getSize() / 1024; if (fileSizeByKB > maxSizeByKB) { throw new MaxUploadSizeExceededException(maxSizeByKB * 1024); } // 获取该文件的文件名 originalFilename = file.getOriginalFilename(); // 获取文件后缀 fileSuffix = UploadUtil.getFileSuffix(originalFilename); if (fileSuffix == null || fileSuffix.length() == 0) { // 通过Mime类型获取文件类型 fileSuffix = ContentTypeUtil.getFileTypeByMimeType(file.getContentType()); } // 创建文件名 filename = UploadUtil.getFileName(); }
@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); } }
@Test public void multipartResolutionFailed() throws Exception { MockActionRequest request = new MockActionRequest(); MockActionResponse response = new MockActionResponse(); request.setPortletMode(PortletMode.EDIT); request.addUserRole("role1"); request.setAttribute("fail", Boolean.TRUE); complexDispatcherPortlet.processAction(request, response); String exception = response.getRenderParameter(DispatcherPortlet.ACTION_EXCEPTION_RENDER_PARAMETER); assertTrue(exception.startsWith(MaxUploadSizeExceededException.class.getName())); }
@Test public void multipartResolutionFailed() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/locale.do;abc=def"); request.addPreferredLocale(Locale.CANADA); request.addUserRole("role1"); request.setAttribute("fail", Boolean.TRUE); MockHttpServletResponse response = new MockHttpServletResponse(); complexDispatcherServlet.service(request, response); assertTrue("forwarded to failed", "failed0.jsp".equals(response.getForwardedUrl())); assertEquals(200, response.getStatus()); assertTrue("correct exception", request.getAttribute( SimpleMappingExceptionResolver.DEFAULT_EXCEPTION_ATTRIBUTE) instanceof MaxUploadSizeExceededException); }
@Override protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { if (returnJson) {//json返回 String callback = request.getParameter(callbackKey); if(ex instanceof NoLoginException){ logger.warn(ex.getMessage(), ex); writeJson(response, callback, BaseResponse.newInstance(String.valueOf(ResponseCode.NO_LOGIN.getCode()), ResponseCode.NO_LOGIN.getMsg()).setToken("")); }else if (ex instanceof BizException) { logger.warn(ex.getMessage(), ex); writeJson(response, callback, BaseResponse.newInstance(String.valueOf(ResponseCode.BIZ_ERROR.getCode()), ex.getMessage())); }else if (ex instanceof MaxUploadSizeExceededException) { writeScript(response, "alert('上传文件过大')"); response.setStatus(413); }else{ logger.error(ex.getMessage(), ex); writeJson(response, callback, BaseResponse.newInstance(String.valueOf(ResponseCode.EXCEPTION.getCode()), ResponseCode.EXCEPTION.getMsg())); } return new ModelAndView(); } else {//普通返回 return super.doResolveException(request, response, handler, ex); } }
@Override protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { if (returnJson) {//json返回 String callback = request.getParameter(callbackKey); if(ex instanceof NoLoginException){ logger.warn(ex.getMessage(), ex); writeJson(response, callback, BaseResponse.newInstance(String.valueOf(ResponseCode.NO_LOGIN.getCode()), ResponseCode.NO_LOGIN.getMsg())); }else if (ex instanceof BizException) { logger.warn(ex.getMessage(), ex); writeJson(response, callback, BaseResponse.newInstance(String.valueOf(ResponseCode.FAILURE.getCode()), ex.getMessage())); }else if (ex instanceof MaxUploadSizeExceededException) { writeScript(response, "alert('上传文件过大')"); response.setStatus(413); }else{ logger.error(ex.getMessage(), ex); writeJson(response, callback, BaseResponse.newInstance(String.valueOf(ResponseCode.EXCEPTION.getCode()), ResponseCode.EXCEPTION.getMsg())); } return new ModelAndView(); } else {//普通返回 return super.doResolveException(request, response, handler, ex); } }
/** * 上传文件超过最大限额 * @param e * @return */ @ExceptionHandler(MaxUploadSizeExceededException.class) @ResponseBody public String uploadError(HttpServletRequest request, MaxUploadSizeExceededException e) { log.error(request.getRequestURI()); Exceptions.printException(e); String errmsg = "<script type=\"text/javascript\">parent.imageMessage=\"上传文件过大!\";</script>"; return errmsg; }
/** * 拦截 {@link MaxUploadSizeExceededException} 异常。 */ @ExceptionHandler(MaxUploadSizeExceededException.class) @ResponseStatus(HttpStatus.PAYLOAD_TOO_LARGE) @ResponseBody public Object handleException(MaxUploadSizeExceededException e, ServletWebRequest request) { MaxUploadSizeExceededException ex = e; String maxDisplaySize = FileUtils.byteCountToDisplaySize(ex.getMaxUploadSize()); String message = "上传的文件最大不能超过 " + maxDisplaySize; return handleFileUploadException(e, HttpStatus.PAYLOAD_TOO_LARGE.value(), message, request); }
@Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { if (request != null && ServletFileUpload.isMultipartContent(request)) { ServletRequestContext ctx = new ServletRequestContext(request); long requestSize = ctx.contentLength(); if (requestSize > maxSize) { throw new MaxUploadSizeExceededException(maxSize); } } return true; }
@Override public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { logger.warn("An exception occurred when invoking the following URL: " + request.getRequestURL() + " . Requester IP is " + request.getRemoteAddr() + ", User-Agent: " + request.getHeader("User-Agent"), ex); if (ex instanceof MaxUploadSizeExceededException) { return new ModelAndView("error/maxFileSizeExceeded"); } response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return 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); } } }
protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { if (ex instanceof MaxUploadSizeExceededException) {// 图片上传超过最大限制的时候,会被调用 long fileSize = ((MaxUploadSizeExceededException) ex).getMaxUploadSize(); String error = "文件超过限制大小,最大限制为".concat("" + fileSize / (1024)).concat("KB"); String message = "{\"status\":\"0\",\"msg\":\"".concat(error).concat("\"}"); response.setContentType("text/html;charset=UTF-8"); setResponse(response, -1, message); return new ModelAndView(); } else { logger.info("\n----------------------------------------\nsome error happen\n----------------------------------------"); ex.printStackTrace(); return new ModelAndView("error"); } }
/** * Handle exception. * * @param ex the ex * @param request the request * @param response the response * @return the model and view */ @ExceptionHandler(MaxUploadSizeExceededException.class) public ModelAndView handleException(final Exception ex, final RenderRequest request, final RenderResponse response) { m_objLog.error(ex); final ModelAndView mv = new ModelAndView(DEFAULT_PAGE); // response.setParameter("tabId", "profile"); // response.setParameter("setModel", Boolean.FALSE.toString()); final ThemeDisplay themeDisplay = (ThemeDisplay) request .getAttribute(WebKeys.THEME_DISPLAY); final long orgId = CustomOrgServiceHandler .getOrgIdByLiferayUser(themeDisplay); RegistrationForm formData = null; if (orgId >= 0) { formData = CustomOrgServiceHandler.getOrganisationForEdit(orgId); } if (formData != null) { mv.addObject("orgData", formData); } mv.addObject("countries", CustomPersistanceServiceHandler.getDataList( E_CategoryType.COUNTRIES, true)); mv.addObject("userData", new ProfileForm()); mv.addObject("actionType", "edit"); mv.addObject("tabId", "profile"); SessionErrors.add(request, "org.form.addOrg.field.logoFile.exceed"); return mv; }
public void testMultipartResolutionFailed() throws Exception { MockActionRequest request = new MockActionRequest(); MockActionResponse response = new MockActionResponse(); request.setPortletMode(PortletMode.EDIT); request.addUserRole("role1"); request.setAttribute("fail", Boolean.TRUE); complexDispatcherPortlet.processAction(request, response); String exception = response.getRenderParameter(DispatcherPortlet.ACTION_EXCEPTION_RENDER_PARAMETER); assertTrue(exception.startsWith(MaxUploadSizeExceededException.class.getName())); }
public void testMultipartResolutionFailed() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/locale.do;abc=def"); request.addPreferredLocale(Locale.CANADA); request.addUserRole("role1"); request.setAttribute("fail", Boolean.TRUE); MockHttpServletResponse response = new MockHttpServletResponse(); complexDispatcherServlet.service(request, response); assertTrue("forwarded to failed", "failed0.jsp".equals(response.getForwardedUrl())); assertEquals(200, response.getStatus()); assertTrue("correct exception", request.getAttribute( SimpleMappingExceptionResolver.DEFAULT_EXCEPTION_ATTRIBUTE) instanceof MaxUploadSizeExceededException); }
@SuppressWarnings({ "unchecked", "rawtypes" }) public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { Map<Object, Object> model = new HashMap<Object, Object>(); if (ex instanceof MaxUploadSizeExceededException){ model.put("errors2", "File size should be less then "+ ((MaxUploadSizeExceededException)ex).getMaxUploadSize()+" byte."); }else{ model.put("errors2", "Unexpected error!!!: " + ex.getMessage()); ex.printStackTrace(); } model.put("profileImageFile", new ProfileImageFile()); return new ModelAndView("/settings", (Map) model); }
@SuppressWarnings({ "unchecked", "rawtypes" }) public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { Map<Object, Object> model = new HashMap<Object, Object>(); if (ex instanceof MaxUploadSizeExceededException){ model.put("errors", "File size should be less then 3mb"); }else{ model.put("errors", "Unexpected error: " + ex.getMessage()); } model.put("imageFile", new ImageFile()); return new ModelAndView("/upload", (Map) model); }
/** * This exception resolver displays the audit set page for file upload * when the MaxUploadSizeExceededException is thrown * * @param hsr * @param hsr1 * @param o * @param excptn * @return */ @Override @SuppressWarnings("unchecked") public ModelAndView doResolveException(HttpServletRequest hsr, HttpServletResponse hsr1, Object o, Exception excptn) { if (excptn instanceof MaxUploadSizeExceededException) { Map<String, String> model = new HashMap<String, String>(); model.put(TgolKeyStore.CONTRACT_ID_KEY, hsr.getParameter(TgolKeyStore.CONTRACT_ID_KEY)); return new ModelAndView(TgolKeyStore.MAX_FILE_SIZE_ERROR_VIEW_NAME, model); } return super.doResolveException(hsr, hsr1, o, excptn); }
@ExceptionHandler(MaxUploadSizeExceededException.class) @ResponseBody public ResponseEntity<ApiError> handleControllerException(HttpServletRequest request, Throwable ex) { return ResponseEntity.badRequest().body(new ApiError(ex.getLocalizedMessage())); }
@ExceptionHandler(MaxUploadSizeExceededException.class) @ResponseStatus(PAYLOAD_TOO_LARGE) @ResponseBody public JsonObject maxUploadSizeExceededException(MaxUploadSizeExceededException e) { return makeMsg(format("Upload file size is limit to %s.", fileSizeLimit)); }
@ExceptionHandler(MaxUploadSizeExceededException.class) public String handleMaxUploadSizeExceededException(final MaxUploadSizeExceededException e, WebRequest request) { logger.warn("Uploaded file to big from {}: ", request.getRemoteUser(), e); return fileUploadResponseFactory.createJsonErrorResponse(MessageKey.UPLOADED_FILE_TOO_LARGE); }
/** * Returns the file upload limit exception if any * @param request * @return the exception, or null if no exception occurred */ public static MaxUploadSizeExceededException limitException(HttpServletRequest request) { return (MaxUploadSizeExceededException) request.getAttribute(MAX_UPLOAD_SIZE_EXCEEDED_KEY); }