List of usage examples for javax.servlet.http HttpServletResponse SC_REQUEST_ENTITY_TOO_LARGE
int SC_REQUEST_ENTITY_TOO_LARGE
To view the source code for javax.servlet.http HttpServletResponse SC_REQUEST_ENTITY_TOO_LARGE.
Click Source Link
From source file:com.themodernway.server.core.servlet.ContentUploadServlet.java
@Override public void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { try {// www.j a va 2s . c om final IFolderItem fold = getRoot(); if (null == fold) { if (logger().isErrorEnabled()) { logger().error(LoggingOps.THE_MODERN_WAY_MARKER, "Can't find storage root."); } sendErrorCode(request, response, HttpServletResponse.SC_NOT_FOUND); return; } if (false == fold.isWritable()) { if (logger().isErrorEnabled()) { logger().error(LoggingOps.THE_MODERN_WAY_MARKER, "Can't write storage root."); } sendErrorCode(request, response, HttpServletResponse.SC_NOT_FOUND); return; } final String path = getPathNormalized(toTrimOrElse(request.getPathInfo(), FileUtils.SINGLE_SLASH)); if (null == path) { if (logger().isErrorEnabled()) { logger().error(LoggingOps.THE_MODERN_WAY_MARKER, "Can't find path info."); } sendErrorCode(request, response, HttpServletResponse.SC_NOT_FOUND); return; } final ServletFileUpload upload = new ServletFileUpload(getDiskFileItemFactory()); upload.setSizeMax(getFileSizeLimit()); final List<FileItem> items = upload.parseRequest(request); for (final FileItem item : items) { if (false == item.isFormField()) { if (item.getSize() > fold.getFileSizeLimit()) { item.delete(); if (logger().isErrorEnabled()) { logger().error(LoggingOps.THE_MODERN_WAY_MARKER, "File size exceeds limit."); } sendErrorCode(request, response, HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE); return; } final IFileItem file = fold.file(FileUtils.concat(path, item.getName())); if (null != file) { try (InputStream read = item.getInputStream()) { fold.create(file.getPath(), read); } catch (final IOException e) { item.delete(); final IServletExceptionHandler handler = getServletExceptionHandler(); if ((null == handler) || (false == handler.handle(request, response, getServletResponseErrorCodeManagerOrDefault(), e))) { if (logger().isErrorEnabled()) { logger().error(LoggingOps.THE_MODERN_WAY_MARKER, "Can't write file.", e); } sendErrorCode(request, response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } return; } } else { item.delete(); if (logger().isErrorEnabled()) { logger().error(LoggingOps.THE_MODERN_WAY_MARKER, "Can't find file."); } sendErrorCode(request, response, HttpServletResponse.SC_NOT_FOUND); return; } } item.delete(); } } catch (IOException | FileUploadException e) { final IServletExceptionHandler handler = getServletExceptionHandler(); if ((null == handler) || (false == handler.handle(request, response, getServletResponseErrorCodeManagerOrDefault(), e))) { if (logger().isErrorEnabled()) { logger().error(LoggingOps.THE_MODERN_WAY_MARKER, "captured overall exception for security.", e); } sendErrorCode(request, response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } } }
From source file:com.thoughtworks.go.agent.UrlBasedArtifactsRepositoryTest.java
@Test public void uploadShouldBeGivenFileSize() throws IOException { when(httpService.upload(any(String.class), eq(tempFile.length()), any(File.class), any(Properties.class))) .thenReturn(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE); try {// ww w .jav a 2 s .c o m artifactsRepository.upload(console, tempFile, "dest", "build42"); fail("should have thrown request entity too large error"); } catch (RuntimeException e) { verify(httpService).upload(eq("http://baseurl/artifacts/dest?attempt=1&buildId=build42"), eq(tempFile.length()), any(File.class), any(Properties.class)); } }
From source file:org.ednovo.gooru.web.spring.exception.GooruExceptionResolver.java
@Override public ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {/*from ww w .j av a2s .c o m*/ ErrorObject errorObject = null; boolean isLogError = false; if (ex instanceof AccessDeniedException) { errorObject = new ErrorObject(403, ex.getMessage()); response.setStatus(403); logger.error("input parameters --- " + getRequestInfo(request).toString()); } else if (ex instanceof BadCredentialsException) { errorObject = new ErrorObject(400, ex.getMessage()); response.setStatus(400); } else if (ex instanceof BadRequestException) { errorObject = new ErrorObject(400, ((BadRequestException) ex).getErrorCode() != null ? "400-" + ((BadRequestException) ex).getErrorCode() : "400", ex.getMessage()); response.setStatus(400); } else if (ex instanceof UnauthorizedException) { errorObject = new ErrorObject(401, ((UnauthorizedException) ex).getErrorCode() != null ? "401-" + ((UnauthorizedException) ex).getErrorCode() : "401", ex.getMessage()); response.setStatus(401); } else if (ex instanceof SizeLimitExceededException) { response.setStatus(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE); errorObject = new ErrorObject(413, ex.getMessage()); } else if (ex instanceof S3ServiceException) { response.setStatus(500); errorObject = new ErrorObject(500, "Internal Server Error"); logger.info("Error in Resolver -- " + ((S3ServiceException) ex).getErrorMessage()); } else if (ex instanceof NotFoundException) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); isLogError = true; errorObject = new ErrorObject(404, ex.getMessage()); } else if (ex instanceof NotImplementedException || ex instanceof NotAllowedException) { response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED); errorObject = new ErrorObject(405, ex.getMessage()); } else if (ex instanceof MethodFailureException) { response.setStatus(420); errorObject = new ErrorObject(420, ex.getMessage()); logger.error("Error in Resolver -- ", ex); logger.error("input parameters --- " + getRequestInfo(request).toString()); } else { errorObject = new ErrorObject(500, "Internal Server Error"); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); logger.error("Error in Resolver -- ", ex); logger.error("input parameters --- " + getRequestInfo(request).toString()); } if (!isLogError) { logger.debug("Error in Resolver -- ", ex); logger.debug("input parameters --- " + getRequestInfo(request).toString()); } ModelAndView jsonModel = new ModelAndView("rest/model"); String errorJsonResponse = new JSONSerializer().exclude("*.class").serialize(errorObject); if (ex instanceof UnauthorizedException) { response.setHeader("Unauthorized", errorJsonResponse); } jsonModel.addObject("model", errorJsonResponse); return jsonModel; }
From source file:com.thoughtworks.go.agent.UrlBasedArtifactsRepository.java
@Override public void upload(StreamConsumer console, File file, String destPath, String buildId) { if (!file.exists()) { String message = "Failed to find " + file.getAbsolutePath(); consumeLineWithPrefix(console, message); throw bomb(message); }//from w w w . j a v a2 s . co m int publishingAttempts = 0; Throwable lastException = null; while (publishingAttempts < PUBLISH_MAX_RETRIES) { File tmpDir = null; try { publishingAttempts++; tmpDir = FileUtil.createTempFolder(); File dataToUpload = new File(tmpDir, file.getName() + ".zip"); zipUtil.zip(file, dataToUpload, Deflater.BEST_SPEED); long size; if (file.isDirectory()) { size = FileUtils.sizeOfDirectory(file); } else { size = file.length(); } consumeLineWithPrefix(console, format("Uploading artifacts from %s to %s", file.getAbsolutePath(), getDestPath(destPath))); String normalizedDestPath = normalizePath(destPath); String url = getUploadUrl(buildId, normalizedDestPath, publishingAttempts); int statusCode = httpService.upload(url, size, dataToUpload, artifactChecksums(file, normalizedDestPath)); if (statusCode == HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE) { String message = format( "Artifact upload for file %s (Size: %s) was denied by the server. This usually happens when server runs out of disk space.", file.getAbsolutePath(), size); consumeLineWithPrefix(console, message); LOGGER.error( "[Artifact Upload] Artifact upload was denied by the server. This usually happens when server runs out of disk space."); publishingAttempts = PUBLISH_MAX_RETRIES; throw bomb(message + ". HTTP return code is " + statusCode); } if (statusCode < HttpServletResponse.SC_OK || statusCode >= HttpServletResponse.SC_MULTIPLE_CHOICES) { throw bomb( "Failed to upload " + file.getAbsolutePath() + ". HTTP return code is " + statusCode); } return; } catch (Throwable e) { String message = "Failed to upload " + file.getAbsolutePath(); LOGGER.error(message, e); consumeLineWithPrefix(console, message); lastException = e; } finally { FileUtil.deleteFolder(tmpDir); } } if (lastException != null) { throw new RuntimeException(lastException); } }
From source file:com.google.nigori.server.NigoriServlet.java
private String getJsonAsString(HttpServletRequest req, int maxLength) throws ServletException { if (maxLength != 0 && req.getContentLength() > maxLength) { return null; }/*from www . j a va2 s .com*/ String charsetName = req.getCharacterEncoding(); if (charsetName == null) { charsetName = MessageLibrary.CHARSET; } try { BufferedReader in = new BufferedReader(new InputStreamReader(req.getInputStream(), charsetName)); StringBuilder json = new StringBuilder(); char[] buffer = new char[64 * 1024]; int charsRemaining = maxJsonQueryLength; int charsRead; while ((charsRead = in.read(buffer)) != -1) { charsRemaining -= charsRead; if (charsRemaining < 0) { throw new ServletException(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE, "Json request exceeds server maximum length of " + maxLength); } json.append(buffer, 0, charsRead); } return json.toString(); } catch (IOException ioe) { throw new ServletException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal error receiving data from client."); } }
From source file:com.thoughtworks.go.publishers.GoArtifactsManipulator.java
public void publish(DefaultGoPublisher goPublisher, String destPath, File source, JobIdentifier jobIdentifier) { if (!source.exists()) { String message = "Failed to find " + source.getAbsolutePath(); goPublisher.taggedConsumeLineWithPrefix(PUBLISH_ERR, message); bomb(message);//from w w w .j a v a 2 s .co m } int publishingAttempts = 0; Throwable lastException = null; while (publishingAttempts < PUBLISH_MAX_RETRIES) { File tmpDir = null; try { publishingAttempts++; tmpDir = FileUtil.createTempFolder(); File dataToUpload = new File(tmpDir, source.getName() + ".zip"); zipUtil.zip(source, dataToUpload, Deflater.BEST_SPEED); long size = 0; if (source.isDirectory()) { size = FileUtils.sizeOfDirectory(source); } else { size = source.length(); } goPublisher.taggedConsumeLineWithPrefix(PUBLISH, "Uploading artifacts from " + source.getAbsolutePath() + " to " + getDestPath(destPath)); String normalizedDestPath = FilenameUtils.separatorsToUnix(destPath); String url = urlService.getUploadUrlOfAgent(jobIdentifier, normalizedDestPath, publishingAttempts); int statusCode = httpService.upload(url, size, dataToUpload, artifactChecksums(source, normalizedDestPath)); if (statusCode == HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE) { String message = String.format( "Artifact upload for file %s (Size: %s) was denied by the server. This usually happens when server runs out of disk space.", source.getAbsolutePath(), size); goPublisher.taggedConsumeLineWithPrefix(PUBLISH_ERR, message); LOGGER.error( "[Artifact Upload] Artifact upload was denied by the server. This usually happens when server runs out of disk space."); publishingAttempts = PUBLISH_MAX_RETRIES; bomb(message + ". HTTP return code is " + statusCode); } if (statusCode < HttpServletResponse.SC_OK || statusCode >= HttpServletResponse.SC_MULTIPLE_CHOICES) { bomb("Failed to upload " + source.getAbsolutePath() + ". HTTP return code is " + statusCode); } return; } catch (Throwable e) { String message = "Failed to upload " + source.getAbsolutePath(); LOGGER.error(message, e); goPublisher.taggedConsumeLineWithPrefix(PUBLISH_ERR, message); lastException = e; } finally { FileUtils.deleteQuietly(tmpDir); } } if (lastException != null) { throw new RuntimeException(lastException); } }
From source file:org.xchain.framework.filter.MultipartFormDataFilter.java
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws java.io.IOException, javax.servlet.ServletException { if (log.isDebugEnabled()) { log.debug("Processing multipart form data."); }//from w ww . jav a 2s .c o m HttpServletRequest httpServletRequest = (HttpServletRequest) request; HttpServletResponse httpServletResponse = (HttpServletResponse) response; // check the content type. String contentType = httpServletRequest.getHeader("Content-Type"); // if this is a multipart form data request, then wrap the request object. if (contentType != null && contentType.startsWith("multipart/form-data") && !(request instanceof MultipartFormDataServletRequest)) { try { request = new MultipartFormDataServletRequest(httpServletRequest, maxSize, sizeThreashold, repositoryPath); } catch (FileUploadException fue) { if (fue instanceof FileUploadBase.SizeLimitExceededException) { log.debug("File to large.", fue); httpServletResponse.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE); return; } // From the apache commons fileupload api: Deprecated. As of commons-fileupload 1.2, the presence of a content-length header is no longer required. // else if( fue instanceof FileUploadBase.UnknownSizeException ) { // httpServletResponse.sendError(HttpServletResponse.SC_LENGTH_REQUIRED); // return; // } else if (fue instanceof FileUploadBase.InvalidContentTypeException) { log.debug("Invalid content type.", fue); httpServletResponse.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE); return; } else { if (log.isDebugEnabled()) log.debug("File upload failed.", fue); throw new ServletException("Could not upload file.", fue); } } } log.debug("Passing to next filter."); // do the chain. filterChain.doFilter(request, response); }
From source file:org.dspace.app.webui.util.JSPManager.java
/** * Display a "file upload was too large" error message. Passing in information * about the size of the file uploaded, and the maximum file size limit so * the user knows why they encountered an error. * @param request/*from w w w . j av a2 s. c om*/ * @param response * @param message * @param actualSize * @param permittedSize * @throws ServletException * @throws IOException */ public static void showFileSizeLimitExceededError(HttpServletRequest request, HttpServletResponse response, String message, long actualSize, long permittedSize) throws ServletException, IOException { request.setAttribute("error.message", message); request.setAttribute("actualSize", actualSize); request.setAttribute("permittedSize", permittedSize); response.setStatus(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE); showJSP(request, response, "/error/exceeded-size.jsp"); }
From source file:com.thoughtworks.go.publishers.GoArtifactsManipulatorTest.java
@Test public void uploadShouldBeGivenFileSize() throws IOException { when(httpService.upload(any(String.class), eq(tempFile.length()), any(File.class), any(Properties.class))) .thenReturn(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE); try {/*w w w .j av a 2s. com*/ goArtifactsManipulatorStub.publish(goPublisher, "dest", tempFile, jobIdentifier); fail("should have thrown request entity too large error"); } catch (RuntimeException e) { verify(httpService).upload(any(String.class), eq(tempFile.length()), any(File.class), any(Properties.class)); } }
From source file:org.brekka.paveway.web.servlet.UploadServlet.java
@Override protected void doPost(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { UploadingFilesContext filesContext = getFilesContext(req); String fileName = null;/*from w ww . ja va 2 s . c om*/ String contentDispositionStr = req.getHeader(ContentDisposition.HEADER); if (contentDispositionStr != null) { String encoding = req.getCharacterEncoding(); if (encoding == null) { encoding = "UTF-8"; } ContentDisposition contentDisposition = ContentDisposition.valueOf(contentDispositionStr, encoding); fileName = contentDisposition.getFilename(); } String accept = req.getHeader("Accept"); String contentType = req.getHeader("Content-Type"); String contentLengthStr = req.getHeader("Content-Length"); String contentRangeStr = req.getHeader(ContentRange.HEADER); FileItemFactory factory; try { if (contentType.equals("multipart/form-data")) { if (fileName == null) { // Handles a standard file upload factory = new EncryptedFileItemFactory(0, null, getPavewayService(), filesContext.getPolicy()); handle(factory, filesContext, req, resp); } else { throw new UnsupportedOperationException("This mode is no longer supported"); } } else { ContentRange contentRange; if (contentRangeStr == null && contentLengthStr == null) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Content-Range or Content-Length must be specified"); return; } else if (contentRangeStr != null) { contentRange = ContentRange.valueOf(contentRangeStr); } else if (contentLengthStr != null) { Long contentLength = Long.valueOf(contentLengthStr); contentRange = new ContentRange(0, contentLength.longValue() - 1, contentLength.longValue()); } else { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Only one of Content-Range or Content-Length must be specified"); return; } UUID id = processUpload(fileName, contentRange, contentType, req); if (accept != null && accept.contains("application/json")) { resp.setContentType("application/json"); resp.getWriter().printf("{\"id\": \"%s\"}", id); } } } catch (PavewayException e) { switch ((PavewayErrorCode) e.getErrorCode()) { case PW700: resp.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE); return; case PW701: resp.sendError(HttpServletResponse.SC_CONFLICT); return; default: throw e; } } catch (FileUploadException e) { throw new PavewayException(PavewayErrorCode.PW800, e, ""); } resp.setStatus(HttpServletResponse.SC_OK); }