Example usage for javax.servlet.http HttpServletResponse SC_REQUEST_ENTITY_TOO_LARGE

List of usage examples for javax.servlet.http HttpServletResponse SC_REQUEST_ENTITY_TOO_LARGE

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse SC_REQUEST_ENTITY_TOO_LARGE.

Prototype

int SC_REQUEST_ENTITY_TOO_LARGE

To view the source code for javax.servlet.http HttpServletResponse SC_REQUEST_ENTITY_TOO_LARGE.

Click Source Link

Document

Status code (413) indicating that the server is refusing to process the request because the request entity is larger than the server is willing or able to process.

Usage

From source file:com.ait.tooling.server.core.servlet.FileUploadServlet.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    logger.info("STARTING UPLOAD");

    try {/*from  ww  w .ja  va2  s . co  m*/
        DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();

        ServletFileUpload fileUpload = new ServletFileUpload(fileItemFactory);

        fileUpload.setSizeMax(FILE_SIZE_LIMIT);

        List<FileItem> items = fileUpload.parseRequest(request);

        for (FileItem item : items) {
            if (item.isFormField()) {
                logger.info("Received form field");

                logger.info("Name: " + item.getFieldName());

                logger.info("Value: " + item.getString());
            } else {
                logger.info("Received file");

                logger.info("Name: " + item.getName());

                logger.info("Size: " + item.getSize());
            }
            if (false == item.isFormField()) {
                if (item.getSize() > FILE_SIZE_LIMIT) {
                    response.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE,
                            "File size exceeds limit");

                    return;
                }
                // Typically here you would process the file in some way:
                // InputStream in = item.getInputStream();
                // ...

                if (false == item.isInMemory()) {
                    item.delete();
                }
            }
        }
    } catch (Exception e) {
        logger.error("Throwing servlet exception for unhandled exception", e);

        throw new ServletException(e);
    }
}

From source file:org.logger.event.web.spring.exception.EventExceptionResolver.java

@Override
public ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
        Exception ex) {//  ww w  .  jav  a2s.c  om
    ErrorObject errorObject = null;
    ex.printStackTrace();
    logger.error("Error in Resolver : {}", ex);
    if (ex instanceof AccessDeniedException) {
        errorObject = new ErrorObject(403, ex.getMessage());
        response.setStatus(403);
    } 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, ((S3ServiceException) ex).getErrorMessage());
    } else {
        errorObject = new ErrorObject(500, ex.getMessage());
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }

    ModelAndView jsonModel = new ModelAndView("rest/model");
    jsonModel.addObject("model", new JSONSerializer().exclude("*.class").serialize(errorObject));
    return jsonModel;
}

From source file:org.eclipse.rap.addons.fileupload.internal.FileUploadProcessor.java

void handleFileUpload(HttpServletRequest request, HttpServletResponse response) throws IOException {
    try {/*from   w  w w  . ja  v a 2  s  .c o  m*/
        ServletFileUpload upload = createUpload();
        FileItemIterator iter = upload.getItemIterator(request);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            if (!item.isFormField()) {
                receive(item);
            }
        }
        if (tracker.isEmpty()) {
            String errorMessage = "No file upload data found in request";
            tracker.setException(new Exception(errorMessage));
            tracker.handleFailed();
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, errorMessage);
        } else {
            tracker.handleFinished();
        }
    } catch (Exception exception) {
        Throwable cause = exception.getCause();
        if (cause instanceof FileSizeLimitExceededException) {
            exception = (Exception) cause;
        }
        tracker.setException(exception);
        tracker.handleFailed();
        int errorCode = exception instanceof FileSizeLimitExceededException
                ? HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE
                : HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
        response.sendError(errorCode, exception.getMessage());
    }
}

From source file:com.xpn.xwiki.web.UploadAction.java

/**
 * {@inheritDoc}//from   w  ww .  j  a  v a  2 s.  c o  m
 * 
 * @see XWikiAction#action(XWikiContext)
 */
@Override
public boolean action(XWikiContext context) throws XWikiException {
    XWikiResponse response = context.getResponse();
    Object exception = context.get("exception");
    boolean ajax = ((Boolean) context.get("ajax")).booleanValue();
    // check Exception File upload is large
    if (exception != null) {
        if (exception instanceof XWikiException) {
            XWikiException exp = (XWikiException) exception;
            if (exp.getCode() == XWikiException.ERROR_XWIKI_APP_FILE_EXCEPTION_MAXSIZE) {
                response.setStatus(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE);
                ((VelocityContext) context.get("vcontext")).put("message",
                        "core.action.upload.failure.maxSize");
                context.put("message", "fileuploadislarge");
                return true;
            }
        }
    }

    // CSRF prevention
    if (!csrfTokenCheck(context)) {
        return false;
    }

    XWikiDocument doc = context.getDoc().clone();

    // The document is saved for each attachment in the group.
    FileUploadPlugin fileupload = (FileUploadPlugin) context.get("fileuploadplugin");
    Map<String, String> fileNames = new HashMap<String, String>();
    List<String> wrongFileNames = new ArrayList<String>();
    Map<String, String> failedFiles = new HashMap<String, String>();
    for (String fieldName : fileupload.getFileItemNames(context)) {
        try {
            if (fieldName.startsWith(FILE_FIELD_NAME)) {
                String fileName = getFileName(fieldName, fileupload, context);
                if (fileName != null) {
                    fileNames.put(fileName, fieldName);
                }
            }
        } catch (Exception ex) {
            wrongFileNames.add(fileupload.getFileName(fieldName, context));
        }
    }

    for (Entry<String, String> file : fileNames.entrySet()) {
        try {
            uploadAttachment(file.getValue(), file.getKey(), fileupload, doc, context);
        } catch (Exception ex) {
            LOGGER.warn("Saving uploaded file failed", ex);
            failedFiles.put(file.getKey(), ExceptionUtils.getRootCauseMessage(ex));
        }
    }

    LOGGER.debug("Found files to upload: " + fileNames);
    LOGGER.debug("Failed attachments: " + failedFiles);
    LOGGER.debug("Wrong attachment names: " + wrongFileNames);
    if (ajax) {
        try {
            response.getOutputStream().println("ok");
        } catch (IOException ex) {
            LOGGER.error("Unhandled exception writing output:", ex);
        }
        return false;
    }
    // Forward to the attachment page
    if (failedFiles.size() > 0 || wrongFileNames.size() > 0) {
        ((VelocityContext) context.get("vcontext")).put("message", "core.action.upload.failure");
        ((VelocityContext) context.get("vcontext")).put("failedFiles", failedFiles);
        ((VelocityContext) context.get("vcontext")).put("wrongFileNames", wrongFileNames);
        return true;
    }
    String redirect = fileupload.getFileItemAsString("xredirect", context);
    if (StringUtils.isEmpty(redirect)) {
        redirect = context.getDoc().getURL("attach", true, context);
    }
    sendRedirect(response, redirect);
    return false;
}

From source file:com.thoughtworks.go.agent.UrlBasedArtifactsRepositoryTest.java

@Test
public void shouldBombWithErrorWhenStatusCodeReturnedIsRequestEntityTooLarge()
        throws IOException, InterruptedException {
    long size = anyLong();
    when(httpService.upload(any(String.class), size, any(File.class), any(Properties.class)))
            .thenReturn(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE);

    try {//from  w  ww  .  j  a  va 2 s  .  com
        artifactsRepository.upload(console, tempFile, "some_dest", "build42");
        fail("should have thrown request entity too large error");
    } catch (RuntimeException e) {
        String expectedMessage = "Artifact upload for file " + tempFile.getAbsolutePath() + " (Size: " + size
                + ") was denied by the server. This usually happens when server runs out of disk space.";
        assertThat(e.getMessage(),
                is("java.lang.RuntimeException: " + expectedMessage + ".  HTTP return code is 413"));
        assertThat(console.output().contains(expectedMessage), is(true));
    }
}

From source file:com.thoughtworks.go.server.security.ArtifactSizeEnforcementFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse res = (HttpServletResponse) response;

    String headerValue = req.getHeader(HttpService.GO_ARTIFACT_PAYLOAD_SIZE);

    if (lastOperationTime.pastWaitingPeriod()) {
        synchronized (this) {
            if (lastOperationTime.pastWaitingPeriod()) {
                totalAvailableSpace = artifactsDirHolder.getArtifactsDir().getUsableSpace()
                        - systemEnvironment.getArtifactReposiotryFullLimit() * GoConstants.MEGA_BYTE;
                lastOperationTime.refresh();
            }/*  w ww .  j a  v a  2 s.  c o  m*/
        }
    }

    if (!StringUtils.isBlank(headerValue) && Long.valueOf(headerValue) * 2 > totalAvailableSpace) {
        Long artifactSize = Long.valueOf(headerValue);
        LOG.error(
                "[Artifact Upload] Artifact upload (Required Size {} * 2 = {}) was denied by the server because it has run out of disk space (Available Space {}).",
                artifactSize, artifactSize * 2, totalAvailableSpace);
        res.setStatus(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE);
    } else {
        chain.doFilter(req, response);
    }
}

From source file:org.eclipse.rap.rwt.supplemental.fileupload.internal.FileUploadProcessor.java

void handleFileUpload(HttpServletRequest request, HttpServletResponse response) throws IOException {
    try {/*  w  w w  . ja  v a 2 s. c o m*/
        DiskFileItem fileItem = readUploadedFileItem(request);
        if (fileItem != null) {
            String fileName = stripFileName(fileItem.getName());
            String contentType = fileItem.getContentType();
            long contentLength = fileItem.getSize();
            tracker.setFileName(fileName);
            tracker.setContentType(contentType);
            FileUploadReceiver receiver = handler.getReceiver();
            IFileUploadDetails details = new FileUploadDetails(fileName, contentType, contentLength);
            receiver.receive(fileItem.getInputStream(), details);
            tracker.handleFinished();
        } else {
            String errorMessage = NO_FILE_UPLOAD_DATA_FOUND_IN_REQUEST;
            tracker.setException(new Exception(errorMessage));
            tracker.handleFailed();
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, errorMessage);
        }
    } catch (FileSizeLimitExceededException exception) {
        // Note: Apache fileupload 1.2 will throw an exception after the
        // upload is finished.
        // Therefore we handle it in the progress listener and ignore this
        // kind of exceptions here
        // https://issues.apache.org/jira/browse/FILEUPLOAD-145
        response.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE, exception.getMessage());
    } catch (Exception exception) {
        tracker.setException(exception);
        tracker.handleFailed();
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, exception.getMessage());
    }
}

From source file:com.thoughtworks.go.server.newsecurity.filters.ArtifactSizeEnforcementFilter.java

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
        FilterChain filterChain) throws IOException, ServletException {
    String headerValue = request.getHeader(HttpService.GO_ARTIFACT_PAYLOAD_SIZE);
    if (isBlank(headerValue)) {
        filterChain.doFilter(request, response);
        return;/*from w  ww. j  a va2 s .  c  o  m*/
    }

    if (lastOperationTime.pastWaitingPeriod()) {
        synchronized (this) {
            if (lastOperationTime.pastWaitingPeriod()) {
                totalAvailableSpace = artifactsDirHolder.getArtifactsDir().getUsableSpace()
                        - systemEnvironment.getArtifactReposiotryFullLimit() * GoConstants.MEGA_BYTE;
                lastOperationTime.refresh();
            }
        }
    }

    if (Long.valueOf(headerValue) * 2 > totalAvailableSpace) {
        Long artifactSize = Long.valueOf(headerValue);
        LOG.error(
                "[Artifact Upload] Artifact upload (Required Size {} * 2 = {}) was denied by the server because it has run out of disk space (Available Space {}).",
                artifactSize, artifactSize * 2, totalAvailableSpace);
        response.setStatus(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE);
    } else {
        filterChain.doFilter(request, response);
    }
}

From source file:com.thoughtworks.go.publishers.GoArtifactsManipulatorTest.java

@Test
public void shouldBombWithErrorWhenStatusCodeReturnedIsRequestEntityTooLarge()
        throws IOException, InterruptedException {
    when(httpService.upload(any(String.class), eq(tempFile.length()), any(File.class), any(Properties.class)))
            .thenReturn(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE);

    CircularFifoQueue buffer = (CircularFifoQueue) ReflectionUtil
            .getField(ReflectionUtil.getField(goPublisher, "consoleOutputTransmitter"), "buffer");
    synchronized (buffer) {
        try {/*  ww w .  j a v  a 2 s  . c  o  m*/
            goArtifactsManipulatorStub.publish(goPublisher, "some_dest", tempFile, jobIdentifier);
            fail("should have thrown request entity too large error");
        } catch (RuntimeException e) {
            String expectedMessage = "Artifact upload for file " + tempFile.getAbsolutePath() + " (Size: "
                    + tempFile.length()
                    + ") was denied by the server. This usually happens when server runs out of disk space.";
            assertThat(e.getMessage(),
                    is("java.lang.RuntimeException: " + expectedMessage + ".  HTTP return code is 413"));
            assertThat(buffer.toString().contains(expectedMessage), is(true));
        }
    }
}

From source file:org.atomserver.server.servlet.BlockingFilter.java

private boolean contentNotBlockedByLength(HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    boolean isWrite = request.getMethod().equals("POST") || request.getMethod().equals("PUT");
    if (isWrite && settings.getMaxContentLength() >= 0) {
        if (request.getContentLength() > settings.getMaxContentLength()) {
            String message = "TOO MUCH DATA :: (Content length exceeds the maximum length allowed.) :: "
                    + request.getRequestURI();
            setError(response, HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE, message);
            return false;
        }//w w  w  . j  a v  a 2 s .  c om
    }
    return true;
}