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.zimbra.cs.zimlet.ProxyServlet.java

private void doProxy(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    ZimbraLog.clearContext();// w w w  .  ja  va 2 s  . c o m
    boolean isAdmin = isAdminRequest(req);
    AuthToken authToken = isAdmin ? getAdminAuthTokenFromCookie(req, resp, true)
            : getAuthTokenFromCookie(req, resp, true);
    if (authToken == null) {
        String zAuthToken = req.getParameter(QP_ZAUTHTOKEN);
        if (zAuthToken != null) {
            try {
                authToken = AuthProvider.getAuthToken(zAuthToken);
                if (authToken.isExpired()) {
                    resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "authtoken expired");
                    return;
                }
                if (!authToken.isRegistered()) {
                    resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "authtoken is invalid");
                    return;
                }
                if (isAdmin && !authToken.isAdmin()) {
                    resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "permission denied");
                    return;
                }
            } catch (AuthTokenException e) {
                resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "unable to parse authtoken");
                return;
            }
        }
    }
    if (authToken == null) {
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "no authtoken cookie");
        return;
    }

    // get the posted body before the server read and parse them.
    byte[] body = copyPostedData(req);

    // sanity check
    String target = req.getParameter(TARGET_PARAM);
    if (target == null) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    // check for permission
    URL url = new URL(target);
    if (!isAdmin && !checkPermissionOnTarget(url, authToken)) {
        resp.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    // determine whether to return the target inline or store it as an upload
    String uploadParam = req.getParameter(UPLOAD_PARAM);
    boolean asUpload = uploadParam != null && (uploadParam.equals("1") || uploadParam.equalsIgnoreCase("true"));

    HttpMethod method = null;
    try {
        HttpClient client = ZimbraHttpConnectionManager.getExternalHttpConnMgr().newHttpClient();
        HttpProxyUtil.configureProxy(client);
        String reqMethod = req.getMethod();
        if (reqMethod.equalsIgnoreCase("GET")) {
            method = new GetMethod(target);
        } else if (reqMethod.equalsIgnoreCase("POST")) {
            PostMethod post = new PostMethod(target);
            if (body != null)
                post.setRequestEntity(new ByteArrayRequestEntity(body, req.getContentType()));
            method = post;
        } else if (reqMethod.equalsIgnoreCase("PUT")) {
            PutMethod put = new PutMethod(target);
            if (body != null)
                put.setRequestEntity(new ByteArrayRequestEntity(body, req.getContentType()));
            method = put;
        } else if (reqMethod.equalsIgnoreCase("DELETE")) {
            method = new DeleteMethod(target);
        } else {
            ZimbraLog.zimlet.info("unsupported request method: " + reqMethod);
            resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            return;
        }

        // handle basic auth
        String auth, user, pass;
        auth = req.getParameter(AUTH_PARAM);
        user = req.getParameter(USER_PARAM);
        pass = req.getParameter(PASS_PARAM);
        if (auth != null && user != null && pass != null) {
            if (!auth.equals(AUTH_BASIC)) {
                ZimbraLog.zimlet.info("unsupported auth type: " + auth);
                resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
                return;
            }
            HttpState state = new HttpState();
            state.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, pass));
            client.setState(state);
            method.setDoAuthentication(true);
        }

        Enumeration headers = req.getHeaderNames();
        while (headers.hasMoreElements()) {
            String hdr = (String) headers.nextElement();
            ZimbraLog.zimlet.debug("incoming: " + hdr + ": " + req.getHeader(hdr));
            if (canProxyHeader(hdr)) {
                ZimbraLog.zimlet.debug("outgoing: " + hdr + ": " + req.getHeader(hdr));
                if (hdr.equalsIgnoreCase("x-host"))
                    method.getParams().setVirtualHost(req.getHeader(hdr));
                else
                    method.addRequestHeader(hdr, req.getHeader(hdr));
            }
        }

        try {
            if (!(reqMethod.equalsIgnoreCase("POST") || reqMethod.equalsIgnoreCase("PUT"))) {
                method.setFollowRedirects(true);
            }
            HttpClientUtil.executeMethod(client, method);
        } catch (HttpException ex) {
            ZimbraLog.zimlet.info("exception while proxying " + target, ex);
            resp.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        int status = method.getStatusLine() == null ? HttpServletResponse.SC_INTERNAL_SERVER_ERROR
                : method.getStatusCode();

        // workaround for Alexa Thumbnails paid web service, which doesn't bother to return a content-type line
        Header ctHeader = method.getResponseHeader("Content-Type");
        String contentType = ctHeader == null || ctHeader.getValue() == null ? DEFAULT_CTYPE
                : ctHeader.getValue();

        InputStream targetResponseBody = method.getResponseBodyAsStream();

        if (asUpload) {
            String filename = req.getParameter(FILENAME_PARAM);
            if (filename == null || filename.equals(""))
                filename = new ContentType(contentType).getParameter("name");
            if ((filename == null || filename.equals(""))
                    && method.getResponseHeader("Content-Disposition") != null)
                filename = new ContentDisposition(method.getResponseHeader("Content-Disposition").getValue())
                        .getParameter("filename");
            if (filename == null || filename.equals(""))
                filename = "unknown";

            List<Upload> uploads = null;

            if (targetResponseBody != null) {
                try {
                    Upload up = FileUploadServlet.saveUpload(targetResponseBody, filename, contentType,
                            authToken.getAccountId());
                    uploads = Arrays.asList(up);
                } catch (ServiceException e) {
                    if (e.getCode().equals(MailServiceException.UPLOAD_REJECTED))
                        status = HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE;
                    else
                        status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
                }
            }

            resp.setStatus(status);
            FileUploadServlet.sendResponse(resp, status, req.getParameter(FORMAT_PARAM), null, uploads, null);
        } else {
            resp.setStatus(status);
            resp.setContentType(contentType);
            for (Header h : method.getResponseHeaders())
                if (canProxyHeader(h.getName()))
                    resp.addHeader(h.getName(), h.getValue());
            if (targetResponseBody != null)
                ByteUtil.copy(targetResponseBody, true, resp.getOutputStream(), true);
        }
    } finally {
        if (method != null)
            method.releaseConnection();
    }
}

From source file:org.ebayopensource.turmeric.policy.adminui.server.PlcImportServlet.java

/**
 * Parses the input stream./*from www.ja v a2  s .c o m*/
 * 
 * @param request
 *            the request
 * @param response
 *            the response
 * @return the byte array output stream
 * @throws ServletException
 *             the servlet exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public ByteArrayOutputStream parseInputStream(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    ServletFileUpload upload = new ServletFileUpload();
    ByteArrayOutputStream out = new ByteArrayOutputStream();

    try {
        FileItemIterator iter = upload.getItemIterator(request);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            InputStream stream = item.openStream();
            // Process the input stream
            int len;
            byte[] buffer = new byte[8192];
            while ((len = stream.read(buffer, 0, buffer.length)) != -1) {
                out.write(buffer, 0, len);
            }

            int maxFileSize = 10 * (1024 * 1024); // 10 megs max
            if (out.size() > maxFileSize) {
                response.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE,
                        "Max allowed file size: 10 Mb");
            }

        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return out;
}

From source file:org.openrepose.common.auth.openstack.AuthenticationServiceClient.java

@Override
public String getBase64EndpointsStringForHeaders(String userToken, String format, String tracingHeader)
        throws AuthServiceException {
    final Map<String, String> headers = new HashMap<>();

    //defaulting to json format
    if ("xml".equalsIgnoreCase(format)) {
        format = MediaType.APPLICATION_XML;
    } else {//w w w.jav  a  2s . c  o  m
        format = MediaType.APPLICATION_JSON;
    }

    String rawEndpointsData;
    try {
        //telling the service what format to send the endpoints to us in
        headers.put(ACCEPT_HEADER, format);
        headers.put(AUTH_TOKEN_HEADER, getAdminToken(tracingHeader, false));
        if (tracingHeader != null) {
            headers.put(CommonHttpHeader.TRACE_GUID.toString(), tracingHeader);
        }

        ServiceClientResponse serviceClientResponse = akkaServiceClient.get(ENDPOINTS_PREFIX + userToken,
                targetHostUri + TOKENS + userToken + ENDPOINTS, headers);

        switch (serviceClientResponse.getStatus()) {
        case HttpServletResponse.SC_OK:
            rawEndpointsData = convertStreamToBase64String(serviceClientResponse.getData());
            break;
        case HttpServletResponse.SC_UNAUTHORIZED:
            LOG.error("Unable to get endpoints for user: " + serviceClientResponse.getStatus()
                    + " :admin token expired. Retrieving new admin token and retrying endpoints retrieval...");

            headers.put(AUTH_TOKEN_HEADER, getAdminToken(tracingHeader, true));
            serviceClientResponse = akkaServiceClient.get(ENDPOINTS_PREFIX + userToken,
                    targetHostUri + TOKENS + userToken + ENDPOINTS, headers);

            if (serviceClientResponse.getStatus() == HttpServletResponse.SC_ACCEPTED) {
                rawEndpointsData = convertStreamToBase64String(serviceClientResponse.getData());
            } else {
                delegationMessage.set("Unable to get endpoints for user: " + userToken
                        + " with configured admin credentials");
                LOG.error("Still unable to get endpoints: " + serviceClientResponse.getStatus());
                throw new AuthServiceException(
                        "Unable to retrieve service catalog for user with configured Admin credentials");
            }
            break;
        case HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE:
        case FilterDirector.SC_TOO_MANY_REQUESTS: // (413 | 429)
            delegationMessage.set("Unable to get endpoints for token: " + userToken + ". Status code: "
                    + serviceClientResponse.getStatus());
            throw buildAuthServiceOverLimitException(serviceClientResponse);
        default:
            delegationMessage.set("Unable to get endpoints for token: " + userToken + ". Status code: "
                    + serviceClientResponse.getStatus());
            LOG.error("Unable to get endpoints for token. Status code: " + serviceClientResponse.getStatus());
            throw new AuthServiceException("Unable to retrieve service catalog for user. Response from "
                    + targetHostUri + ": " + serviceClientResponse.getStatus());
        }
    } catch (AkkaServiceClientException e) {
        throw new AuthServiceException("Unable to get endpoints.", e);
    }

    return rawEndpointsData;
}

From source file:org.openrepose.common.auth.openstack.AuthenticationServiceClient.java

@Override
public AuthGroups getGroups(String userId, String tracingHeader) throws AuthServiceException {
    final Map<String, String> headers = new HashMap<>();

    AuthGroups authGroups;/* www  .  j  av  a2  s.  c  om*/

    try {
        headers.put(ACCEPT_HEADER, MediaType.APPLICATION_XML);
        headers.put(AUTH_TOKEN_HEADER, getAdminToken(tracingHeader, false));
        if (tracingHeader != null) {
            headers.put(CommonHttpHeader.TRACE_GUID.toString(), tracingHeader);
        }

        ServiceClientResponse serviceResponse = akkaServiceClient.get(GROUPS_PREFIX + userId,
                targetHostUri + "/users/" + userId + "/RAX-KSGRP", headers);

        switch (serviceResponse.getStatus()) {
        case HttpServletResponse.SC_OK:
            authGroups = getAuthGroups(serviceResponse);
            break;
        case HttpServletResponse.SC_UNAUTHORIZED:
            LOG.error("Unable to get groups for user: " + serviceResponse.getStatus()
                    + " :admin token expired. Retrieving new admin token and retrying groups retrieval...");

            headers.put(AUTH_TOKEN_HEADER, getAdminToken(tracingHeader, true));

            serviceResponse = akkaServiceClient.get(GROUPS_PREFIX + userId,
                    targetHostUri + "/users/" + userId + "/RAX-KSGRP", headers);

            if (serviceResponse.getStatus() == HttpServletResponse.SC_ACCEPTED) {
                authGroups = getAuthGroups(serviceResponse);
            } else {
                delegationMessage.set("Unable to get groups for user id: " + userId + ". Status code: "
                        + serviceResponse.getStatus());
                LOG.error("Still unable to get groups: " + serviceResponse.getStatus());
                throw new AuthServiceException("Unable to retrieve groups for user. Response from "
                        + targetHostUri + ": " + serviceResponse.getStatus());

            }
            break;
        case HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE:
        case FilterDirector.SC_TOO_MANY_REQUESTS: // (413 | 429)
            delegationMessage.set("Unable to get groups for user id: " + userId + ". Status code: "
                    + serviceResponse.getStatus());
            throw buildAuthServiceOverLimitException(serviceResponse);
        default:
            delegationMessage.set("Unable to get groups for user id: " + userId + ". Status code: "
                    + serviceResponse.getStatus());
            LOG.error("Unable to get groups for user id: " + userId + " Status code: "
                    + serviceResponse.getStatus());
            throw new AuthServiceException("Unable to retrieve groups for user. Response from " + targetHostUri
                    + ": " + serviceResponse.getStatus());
        }
    } catch (AkkaServiceClientException e) {
        throw new AuthServiceException("Unable to get groups.", e);
    }

    return authGroups;
}

From source file:org.openrepose.common.auth.openstack.AuthenticationServiceClient.java

private String getAdminToken(String tracingHeader, boolean force) throws AuthServiceException {

    String adminToken = !force && currentAdminToken != null && currentAdminToken.isValid()
            ? currentAdminToken.getToken()
            : null;/*  w  ww  .ja v  a 2 s  .  co m*/

    try {
        if (adminToken == null) {
            Map<String, String> headerMap = new HashMap<>();
            if (!StringUtilities.isEmpty(tracingHeader)) {
                headerMap.put(CommonHttpHeader.TRACE_GUID.toString(), tracingHeader);
            }
            final ServiceClientResponse serviceResponse = akkaServiceClient.post(AdminToken.CACHE_KEY,
                    targetHostUri + "/tokens", headerMap, requestBody, MediaType.APPLICATION_XML_TYPE);

            switch (serviceResponse.getStatus()) {
            case HttpServletResponse.SC_OK:
                final AuthenticateResponse authenticateResponse = openStackCoreResponseUnmarshaller
                        .unmarshall(serviceResponse.getData(), AuthenticateResponse.class);

                Token token = authenticateResponse.getToken();
                currentAdminToken = new AdminToken(token.getId(), token.getExpires().toGregorianCalendar());
                adminToken = currentAdminToken.getToken();
                break;
            case HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE:
            case FilterDirector.SC_TOO_MANY_REQUESTS: // (413 | 429)
                delegationMessage.set("Unable to get admin token. Status code: " + serviceResponse.getStatus());
                throw buildAuthServiceOverLimitException(serviceResponse);
            default:
                delegationMessage.set("Unable to get admin token. Status code: " + serviceResponse.getStatus());
                LOG.error(
                        "Unable to get admin token.  Verify admin credentials. " + serviceResponse.getStatus());
                currentAdminToken = null;
                throw new AuthServiceException("Unable to retrieve admin token ");
            }
        }
    } catch (AkkaServiceClientException e) {
        throw new AuthServiceException("Unable to retrieve admin token.", e);
    }

    return adminToken;
}

From source file:com.juicioenlinea.application.servlets.particular.DemandaServlet.java

private void create(HttpServletRequest request, HttpServletResponse response) throws IOException {
    HttpSession session = request.getSession(false);
    Particular demandante = (Particular) session.getAttribute("usuario");

    StringBuilder sb = new StringBuilder();
    sb.append("<response>");

    if (request.getContentLengthLong() > 104857600) {
        response.setStatus(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE);
        sb.append("<message>");
        sb.append(new Messages().getClientMessage("error", 7));
        sb.append("</message>");
    } else {/* w  w  w .  ja  v a2  s . co m*/
        // Campos formulario
        UploadFile uf = new UploadFile(request);

        String numeroDemanda = ToolBox.createNumeroDemanda();
        String nombre = uf.getFormField("nombre");
        String descripcion = uf.getFormField("descripcion");
        int estado = 1;
        System.out.println("Archivos: " + uf.getFiles().size());
        // Validamos datos
        if (numeroDemanda == null || numeroDemanda.equals("") || nombre == null || nombre.equals("")
                || descripcion == null || descripcion.equals("") || uf.getFiles().size() < 1) {

            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            sb.append("<message>");
            sb.append(new Messages().getClientMessage("error", 1));
            sb.append("</message>");
        } else {
            // Tiempo
            Date fechaCreacion = ToolBox.dateFormat(new Date());

            // Obtenemos 3 magistrados con menos demandas asignadas
            MagistradoDAO madao = new MagistradoDAO();
            Set<Magistrado> magistrados = madao.get3Magistrado();

            if (magistrados == null || magistrados.size() < 3) {
                magistrados = madao.readAll3();
            }

            // Objetos de TIEMPO
            Tiempo tiempo = new Tiempo();
            tiempo.setFechaCreacion(fechaCreacion);
            TiempoDAO tidao = new TiempoDAO();

            // Objeto de DEMANDA
            Demanda demanda = new Demanda();
            demanda.setParticularByIdParticularDemandante(demandante);
            demanda.setTiempo(tiempo);
            demanda.setNumeroDemanda(numeroDemanda);
            demanda.setNombreDemanda(nombre);
            demanda.setDescripcion(descripcion);
            demanda.setEstado(estado);
            demanda.setMagistrados(magistrados);

            DemandaDAO dedao = new DemandaDAO();
            if (!tidao.create(tiempo) || !dedao.create(demanda)) {
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                sb.append("<message>");
                sb.append(new Messages().getClientMessage("error", 4));
                sb.append("</message>");
            } else {
                // Guardamos los documentos
                String sala = "s1";
                String uri = request.getScheme() + "://" + request.getServerName() + ":"
                        + request.getServerPort() + "/" + this.getServletContext().getContextPath();

                for (FileItem fi : uf.getFiles()) {
                    // Documentos
                    Documento documento = new Documento();
                    documento.setDemanda(demanda);
                    documento.setParticular(demandante);
                    documento.setFechaCarga(ToolBox.dateFormat(new Date()));
                    documento.setRuta(
                            uf.saveFile(fi, this.getServletContext().getRealPath(""), sala, numeroDemanda));
                    documento.setEstado(1);
                    documento.setNombre(fi.getName());

                    DocumentoDAO dodao = new DocumentoDAO();

                    if (!dodao.create(documento)) {
                        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                        sb.append("<message>");
                        sb.append(new Messages().getClientMessage("error", 7));
                        sb.append("</message>");
                        break;
                    }
                }

                //Mail mail = new Mail(demandante.getCatalogousuarios().getCorreo(), "Demanda creada", "Nmero de demanda: " + numeroDemanda);
                Mail mail = new Mail("eddy_wallace@hotmail.com", "Demanda creada",
                        "Nmero de demanda: " + numeroDemanda);

                if (!mail.sendMail()) {
                    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                    sb.append("<message>");
                    sb.append(new Messages().getClientMessage("error", 8));
                    sb.append("</message>");

                    sb.append("<redirect>");
                    sb.append(uri).append("/aplicacion/particular/Demanda?action=demandasHechas");
                    sb.append("</redirect>");
                } else {
                    sb.append("<message>");
                    sb.append(new Messages().getClientMessage("ok", 5));
                    sb.append("</message>");

                    sb.append("<redirect>");
                    sb.append(uri).append("/aplicacion/particular/Demanda?action=demandasHechas");
                    sb.append("</redirect>");
                }
            }
        }
    }

    sb.append("</response>");
    PrintWriter pw = response.getWriter();
    pw.write(sb.toString());
}

From source file:com.zimbra.cs.service.FileUploadServlet.java

@SuppressWarnings("unchecked")
List<Upload> handleMultipartUpload(HttpServletRequest req, HttpServletResponse resp, String fmt, Account acct,
        boolean limitByFileUploadMaxSize, AuthToken at, boolean csrfCheckComplete)
        throws IOException, ServiceException {
    List<FileItem> items = null;
    String reqId = null;/*from   w  w w  .ja v a  2s.  c  o m*/

    ServletFileUpload upload = getUploader2(limitByFileUploadMaxSize);
    try {
        items = upload.parseRequest(req);

        if (!csrfCheckComplete && !CsrfUtil.checkCsrfInMultipartFileUpload(items, at)) {
            drainRequestStream(req);
            mLog.info("CSRF token validation failed for account: %s, Auth token is CSRF enabled",
                    acct.getName());
            sendResponse(resp, HttpServletResponse.SC_UNAUTHORIZED, fmt, null, null, items);
            return Collections.emptyList();
        }
    } catch (FileUploadBase.SizeLimitExceededException e) {
        // at least one file was over max allowed size
        mLog.info("Exceeded maximum upload size of " + upload.getSizeMax() + " bytes: " + e);
        drainRequestStream(req);
        sendResponse(resp, HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE, fmt, reqId, null, items);
        return Collections.emptyList();
    } catch (FileUploadBase.InvalidContentTypeException e) {
        // at least one file was of a type not allowed
        mLog.info("File upload failed", e);
        drainRequestStream(req);
        sendResponse(resp, HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE, fmt, reqId, null, items);
        return Collections.emptyList();
    } catch (FileUploadException e) {
        // parse of request failed for some other reason
        mLog.info("File upload failed", e);
        drainRequestStream(req);
        sendResponse(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, fmt, reqId, null, items);
        return Collections.emptyList();
    }

    String charset = "utf-8";
    LinkedList<String> names = new LinkedList<String>();
    HashMap<FileItem, String> filenames = new HashMap<FileItem, String>();
    if (items != null) {
        for (Iterator<FileItem> it = items.iterator(); it.hasNext();) {
            FileItem fi = it.next();
            if (fi == null)
                continue;

            if (fi.isFormField()) {
                if (fi.getFieldName().equals("requestId")) {
                    // correlate this file upload session's request and response
                    reqId = fi.getString();
                } else if (fi.getFieldName().equals("_charset_") && !fi.getString().equals("")) {
                    // get the form value charset, if specified
                    charset = fi.getString();
                } else if (fi.getFieldName().startsWith("filename")) {
                    // allow a client to explicitly provide filenames for the uploads
                    names.clear();
                    String value = fi.getString(charset);
                    if (!Strings.isNullOrEmpty(value)) {
                        for (String name : value.split("\n")) {
                            names.add(name.trim());
                        }
                    }
                }
                // strip form fields out of the list of uploads
                it.remove();
            } else {
                if (fi.getName() == null || fi.getName().trim().equals("")) {
                    it.remove();
                } else {
                    filenames.put(fi, names.isEmpty() ? null : names.remove());
                }
            }
        }
    }

    // restrict requestId value for safety due to later use in javascript
    if (reqId != null && reqId.length() != 0) {
        if (!ALLOWED_REQUESTID_CHARS.matcher(reqId).matches()) {
            mLog.info("Rejecting upload with invalid chars in reqId: %s", reqId);
            sendResponse(resp, HttpServletResponse.SC_BAD_REQUEST, fmt, null, null, items);
            return Collections.emptyList();
        }
    }

    // empty upload is not a "success"
    if (items == null || items.isEmpty()) {
        mLog.info("No data in upload for reqId: %s", reqId);
        sendResponse(resp, HttpServletResponse.SC_NO_CONTENT, fmt, reqId, null, items);
        return Collections.emptyList();
    }

    // cache the uploaded files in the hash and construct the list of upload IDs
    List<Upload> uploads = new ArrayList<Upload>(items.size());
    for (FileItem fi : items) {
        String name = filenames.get(fi);
        if (name == null || name.trim().equals(""))
            name = fi.getName();
        Upload up = new Upload(acct.getId(), fi, name);

        mLog.info("Received multipart: %s", up);
        synchronized (mPending) {
            mPending.put(up.uuid, up);
        }
        uploads.add(up);
    }

    sendResponse(resp, HttpServletResponse.SC_OK, fmt, reqId, uploads, items);
    return uploads;
}

From source file:com.zimbra.cs.service.FileUploadServlet.java

/**
 * This is used when handling a POST request generated by {@link ZMailbox#uploadContentAsStream}
 *
 * @param req/*  w  w w  .j a v  a  2s.  co m*/
 * @param resp
 * @param fmt
 * @param acct
 * @param limitByFileUploadMaxSize
 * @return
 * @throws IOException
 * @throws ServiceException
 */
List<Upload> handlePlainUpload(HttpServletRequest req, HttpServletResponse resp, String fmt, Account acct,
        boolean limitByFileUploadMaxSize) throws IOException, ServiceException {
    // metadata is encoded in the response's HTTP headers
    ContentType ctype = new ContentType(req.getContentType());
    String contentType = ctype.getContentType(), filename = ctype.getParameter("name");
    if (filename == null) {
        filename = new ContentDisposition(req.getHeader("Content-Disposition")).getParameter("filename");
    }

    if (filename == null || filename.trim().equals("")) {
        mLog.info("Rejecting upload with no name.");
        drainRequestStream(req);
        sendResponse(resp, HttpServletResponse.SC_NO_CONTENT, fmt, null, null, null);
        return Collections.emptyList();
    }

    // Unescape the filename so it actually displays correctly
    filename = StringEscapeUtils.unescapeHtml(filename);

    // store the fetched file as a normal upload
    ServletFileUpload upload = getUploader2(limitByFileUploadMaxSize);
    FileItem fi = upload.getFileItemFactory().createItem("upload", contentType, false, filename);
    try {
        // write the upload to disk, but make sure not to exceed the permitted max upload size
        long size = ByteUtil.copy(req.getInputStream(), false, fi.getOutputStream(), true,
                upload.getSizeMax() * 3);
        if ((upload.getSizeMax() >= 0 /* -1 would mean "no limit" */) && (size > upload.getSizeMax())) {
            mLog.debug("handlePlainUpload(): deleting %s", fi);
            fi.delete();
            mLog.info("Exceeded maximum upload size of " + upload.getSizeMax() + " bytes: " + acct.getId());
            drainRequestStream(req);
            sendResponse(resp, HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE, fmt, null, null, null);
            return Collections.emptyList();
        }
    } catch (IOException ioe) {
        mLog.warn("Unable to store upload.  Deleting %s", fi, ioe);
        fi.delete();
        drainRequestStream(req);
        sendResponse(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, fmt, null, null, null);
        return Collections.emptyList();
    }
    List<FileItem> items = new ArrayList<FileItem>(1);
    items.add(fi);

    Upload up = new Upload(acct.getId(), fi, filename);
    mLog.info("Received plain: %s", up);
    synchronized (mPending) {
        mPending.put(up.uuid, up);
    }

    List<Upload> uploads = Arrays.asList(up);
    sendResponse(resp, HttpServletResponse.SC_OK, fmt, null, uploads, items);
    return uploads;
}

From source file:org.gss_project.gss.server.rest.FilesHandler.java

/**
 * Restores a previous version for a file.
 *
 * @param req the HTTP request//from w  w  w  .j  a va2  s .c o  m
 * @param resp the HTTP response
 * @param path the resource path
 * @param version the version number to restore
 * @throws IOException if an I/O error occurs
 */
private void restoreVersion(HttpServletRequest req, HttpServletResponse resp, String path, String version)
        throws IOException {
    final User user = getUser(req);
    User owner = getOwner(req);
    Object resource = null;
    try {
        resource = getService().getResourceAtPath(owner.getId(), path, true);
    } catch (ObjectNotFoundException e) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND, path);
        return;
    } catch (RpcException e) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
        return;
    }
    if (resource instanceof Folder) {
        resp.sendError(HttpServletResponse.SC_CONFLICT);
        return;
    }

    try {
        final FileHeader file = (FileHeader) resource;
        final int oldVersion = Integer.parseInt(version);

        new TransactionHelper<Void>().tryExecute(new Callable<Void>() {
            @Override
            public Void call() throws Exception {
                getService().restoreVersion(user.getId(), file.getId(), oldVersion);
                return null;
            }
        });
    } catch (InsufficientPermissionsException e) {
        resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
    } catch (ObjectNotFoundException e) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage());
    } catch (RpcException e) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
    } catch (GSSIOException e) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    } catch (QuotaExceededException e) {
        resp.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE, e.getMessage());
    } catch (NumberFormatException e) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
    } catch (Exception e) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    }
}

From source file:org.atomserver.AtomServer.java

private ResponseContext tooMuchDataError(Abdera abdera, RequestContext request) {
    String msg = "TOO MUCH DATA :: (Content length exceeds the maximum length allowed.) :: " + request.getUri();
    logger.error(msg);//  w w w  . jav a 2  s.c o  m
    return returnBase(createErrorDocument(abdera, HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE, msg, null),
            HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE, null);
}