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:org.silverpeas.mobile.server.servlets.MediaServlet.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String componentId = "";
    String albumId = "";
    String tempDir = MediaHelper.getTemporaryUploadMediaPath();

    // configures upload settings
    DiskFileItemFactory factory = new DiskFileItemFactory();
    // sets memory threshold - beyond which files are stored in disk
    factory.setSizeThreshold(MEMORY_THRESHOLD);
    // sets temporary location to store files
    factory.setRepository(new File(tempDir));

    ServletFileUpload upload = new ServletFileUpload(factory);

    // sets maximum size of upload file
    upload.setFileSizeMax(MAX_FILE_SIZE);

    // sets maximum size of request (include file + form data)
    upload.setSizeMax(MAX_REQUEST_SIZE);

    // Parse the request
    @SuppressWarnings("unchecked")
    List<FileItem> items = null;
    try {/* w  ww.jav a 2s . c o  m*/
        items = upload.parseRequest(request);
    } catch (FileUploadBase.FileSizeLimitExceededException eu) {
        response.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE);
        return;
    } catch (FileUploadException e) {
        e.printStackTrace();
    }

    // Process the uploaded items
    Iterator iter = items.iterator();
    while (iter.hasNext()) {
        FileItem item = (FileItem) iter.next();
        if (item.isFormField()) {
            if (item.getFieldName().equals("componentId"))
                componentId = item.getString();
            if (item.getFieldName().equals("albumId"))
                albumId = item.getString();

        } else {
            String fileName = item.getName();
            File file = new File(tempDir + File.separator + fileName);
            try {
                item.write(file);
                createMedia(request, response, fileName, getUserInSession(request).getId(), componentId,
                        albumId, file, false, "", "", true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:org.silverpeas.mobile.server.servlets.FormServlet.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {/*from   ww  w.ja  v a2s.  com*/
        String instanceId = null;
        String currentAction = null;
        String currentRole = null;
        String currentState = null;
        String processId = null;
        HashMap<String, Object> fields = new HashMap<String, Object>();
        String charset = "UTF-8";
        String tempDir = MediaHelper.getTemporaryUploadMediaPath();

        // configures upload settings
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // sets memory threshold - beyond which files are stored in disk
        factory.setSizeThreshold(MEMORY_THRESHOLD);
        // sets temporary location to store files
        factory.setRepository(new File(tempDir));

        ServletFileUpload upload = new ServletFileUpload(factory);

        // sets maximum size of upload file
        upload.setFileSizeMax(MAX_FILE_SIZE);

        // sets maximum size of request (include file + form data)
        upload.setSizeMax(MAX_REQUEST_SIZE);

        // Parse the request
        @SuppressWarnings("unchecked")
        List<FileItem> items = null;
        items = upload.parseRequest(request);

        // Process the uploaded items
        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            if (item.isFormField()) {
                if (item.getFieldName().equals("instanceId")) {
                    instanceId = item.getString(charset);
                } else if (item.getFieldName().equals("currentAction")) {
                    currentAction = item.getString(charset);
                } else if (item.getFieldName().equals("currentRole")) {
                    currentRole = item.getString(charset);
                } else if (item.getFieldName().equals("currentState")) {
                    currentState = item.getString(charset);
                } else if (item.getFieldName().equals("processId")) {
                    processId = item.getString(charset);
                } else {
                    fields.put(item.getFieldName(), item.getString(charset));
                }
            } else {
                String fileName = item.getName();
                File file = new File(tempDir + File.separator + fileName);
                item.write(file);
                fields.put(item.getFieldName(), file);
            }
        }
        processAction(request, response, fields, instanceId, currentAction, currentRole, currentState,
                processId);
    } catch (FileUploadBase.FileSizeLimitExceededException eu) {
        response.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE);
        return;
    } catch (Exception e) {
        e.printStackTrace();
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

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

@Override
public AuthenticateResponse validateToken(String tenant, String userToken, String tracingHeader)
        throws AuthServiceException {
    AuthenticateResponse authenticateResponse = null;
    ServiceClientResponse serviceResponse = validateUser(userToken, tenant, false, tracingHeader);

    switch (serviceResponse.getStatus()) {
    case HttpServletResponse.SC_OK:
        authenticateResponse = openStackCoreResponseUnmarshaller.unmarshall(serviceResponse.getData(),
                AuthenticateResponse.class);
        break;//from w ww  . ja  v  a 2s.co  m

    case HttpServletResponse.SC_NOT_FOUND:
        // User's token is bad
        delegationMessage.set("Unable to validate token: " + userToken + ". Invalid token.");
        LOG.error("Unable to validate token.  Invalid token. " + serviceResponse.getStatus());
        break;

    case HttpServletResponse.SC_UNAUTHORIZED:
        LOG.error(
                "Unable to validate token: " + userToken + " due to status code: " + serviceResponse.getStatus()
                        + " :admin token expired. Retrieving new admin token and retrying token validation...");

        serviceResponse = validateUser(userToken, tenant, true, tracingHeader);

        if (serviceResponse.getStatus() == HttpServletResponse.SC_OK) {
            authenticateResponse = openStackCoreResponseUnmarshaller.unmarshall(serviceResponse.getData(),
                    AuthenticateResponse.class);
        } else if (serviceResponse.getStatus() == HttpServletResponse.SC_NOT_FOUND) {
            delegationMessage.set("Unable to validate token: " + userToken + ". Invalid token. Status Code: "
                    + serviceResponse.getStatus());
            LOG.error("Unable to validate token.  Invalid token. " + serviceResponse.getStatus());
        } else {
            delegationMessage
                    .set("Unable to validate token: " + userToken + " with configured admin credentials.");
            LOG.error("Still unable to validate token: " + serviceResponse.getStatus());
            throw new AuthServiceException("Unable to authenticate 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 validate token: " + userToken + ". Invalid token. Status Code: "
                + serviceResponse.getStatus());
        throw buildAuthServiceOverLimitException(serviceResponse);
    default:
        delegationMessage.set("Authentication Service returned an unexpected response status code: "
                + serviceResponse.getStatus() + " for token: " + userToken);
        LOG.error("Authentication Service returned an unexpected response status code: "
                + serviceResponse.getStatus());
        throw new AuthServiceException("Unable to validate token. Response from " + targetHostUri + ": "
                + serviceResponse.getStatus());
    }

    return authenticateResponse;
}

From source file:org.purl.sword.server.DepositServlet.java

/**
 * Process a post request./*w w  w.j  a  v a2  s . co  m*/
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // Create the Deposit request
    Deposit d = new Deposit();
    Date date = new Date();
    log.debug("Starting deposit processing at " + date.toString() + " by " + request.getRemoteAddr());

    // Are there any authentication details?
    String usernamePassword = getUsernamePassword(request);
    if ((usernamePassword != null) && (!usernamePassword.equals(""))) {
        int p = usernamePassword.indexOf(':');
        if (p != -1) {
            d.setUsername(usernamePassword.substring(0, p));
            d.setPassword(usernamePassword.substring(p + 1));
        }
    } else if (authenticateWithBasic()) {
        String s = "Basic realm=\"SWORD\"";
        response.setHeader("WWW-Authenticate", s);
        response.setStatus(401);
        return;
    }

    // Set up some variables
    String filename = null;

    // Do the processing
    try {
        // Write the file to the temp directory
        filename = tempDirectory + "SWORD-" + request.getRemoteAddr() + "-" + counter.addAndGet(1);
        log.debug("Package temporarily stored as: " + filename);
        InputStream inputstream = request.getInputStream();
        OutputStream outputstream = new FileOutputStream(new File(filename));
        try {
            byte[] buf = new byte[1024];
            int len;
            while ((len = inputstream.read(buf)) > 0) {
                outputstream.write(buf, 0, len);
            }
        } finally {
            inputstream.close();
            outputstream.close();
        }

        // Check the size is OK
        File file = new File(filename);
        long fLength = file.length() / 1024;
        if ((maxUploadSize != -1) && (fLength > maxUploadSize)) {
            this.makeErrorDocument(ErrorCodes.MAX_UPLOAD_SIZE_EXCEEDED,
                    HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE,
                    "The uploaded file exceeded the maximum file size this server will accept (the file is "
                            + fLength + "kB but the server will only accept files as large as " + maxUploadSize
                            + "kB)",
                    request, response);
            return;
        }

        // Check the MD5 hash
        String receivedMD5 = ChecksumUtils.generateMD5(filename);
        log.debug("Received filechecksum: " + receivedMD5);
        d.setMd5(receivedMD5);
        String md5 = request.getHeader("Content-MD5");
        log.debug("Received file checksum header: " + md5);
        if ((md5 != null) && (!md5.equals(receivedMD5))) {
            // Return an error document
            this.makeErrorDocument(ErrorCodes.ERROR_CHECKSUM_MISMATCH,
                    HttpServletResponse.SC_PRECONDITION_FAILED,
                    "The received MD5 checksum for the deposited file did not match the checksum sent by the deposit client",
                    request, response);
            log.debug("Bad MD5 for file. Aborting with appropriate error message");
            return;
        } else {
            // Set the file to be deposited
            d.setFile(file);

            // Set the X-On-Behalf-Of header
            String onBehalfOf = request.getHeader(HttpHeaders.X_ON_BEHALF_OF.toString());
            if ((onBehalfOf != null) && (onBehalfOf.equals("reject"))) {
                // user name is "reject", so throw a not know error to allow the client to be tested
                throw new SWORDErrorException(ErrorCodes.TARGET_OWNER_UKNOWN, "unknown user \"reject\"");
            } else {
                d.setOnBehalfOf(onBehalfOf);
            }

            // Set the X-Packaging header
            d.setPackaging(request.getHeader(HttpHeaders.X_PACKAGING));

            // Set the X-No-Op header
            String noop = request.getHeader(HttpHeaders.X_NO_OP);
            log.error("X_NO_OP value is " + noop);
            if ((noop != null) && (noop.equals("true"))) {
                d.setNoOp(true);
            } else if ((noop != null) && (noop.equals("false"))) {
                d.setNoOp(false);
            } else if (noop == null) {
                d.setNoOp(false);
            } else {
                throw new SWORDErrorException(ErrorCodes.ERROR_BAD_REQUEST, "Bad no-op");
            }

            // Set the X-Verbose header
            String verbose = request.getHeader(HttpHeaders.X_VERBOSE);
            if ((verbose != null) && (verbose.equals("true"))) {
                d.setVerbose(true);
            } else if ((verbose != null) && (verbose.equals("false"))) {
                d.setVerbose(false);
            } else if (verbose == null) {
                d.setVerbose(false);
            } else {
                throw new SWORDErrorException(ErrorCodes.ERROR_BAD_REQUEST, "Bad verbose");
            }

            // Set the slug
            String slug = request.getHeader(HttpHeaders.SLUG);
            if (slug != null) {
                d.setSlug(slug);
            }

            // Set the content disposition
            d.setContentDisposition(request.getHeader(HttpHeaders.CONTENT_DISPOSITION));

            // Set the IP address
            d.setIPAddress(request.getRemoteAddr());

            // Set the deposit location
            d.setLocation(getUrl(request));

            // Set the content type
            d.setContentType(request.getContentType());

            // Set the content length
            String cl = request.getHeader(HttpHeaders.CONTENT_LENGTH);
            if ((cl != null) && (!cl.equals(""))) {
                d.setContentLength(Integer.parseInt(cl));
            }

            // Get the DepositResponse
            DepositResponse dr = myRepository.doDeposit(d);

            // Echo back the user agent
            if (request.getHeader(HttpHeaders.USER_AGENT.toString()) != null) {
                dr.getEntry().setUserAgent(request.getHeader(HttpHeaders.USER_AGENT.toString()));
            }

            // Echo back the packaging format
            if (request.getHeader(HttpHeaders.X_PACKAGING.toString()) != null) {
                dr.getEntry().setPackaging(request.getHeader(HttpHeaders.X_PACKAGING.toString()));
            }

            // Print out the Deposit Response
            response.setStatus(dr.getHttpResponse());
            if ((dr.getLocation() != null) && (!dr.getLocation().equals(""))) {
                response.setHeader("Location", dr.getLocation());
            }
            response.setContentType("application/atom+xml; charset=UTF-8");
            PrintWriter out = response.getWriter();
            out.write(dr.marshall());
            out.flush();
        }
    } catch (SWORDAuthenticationException sae) {
        // Ask for credentials again
        if (authN.equals("Basic")) {
            String s = "Basic realm=\"SWORD\"";
            response.setHeader("WWW-Authenticate", s);
            response.setStatus(401);
        }
    } catch (SWORDErrorException see) {
        // Get the details and send the right SWORD error document
        log.error(see.toString());
        this.makeErrorDocument(see.getErrorURI(), see.getStatus(), see.getDescription(), request, response);
        return;
    } catch (SWORDException se) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        log.error(se.toString());
    } catch (NoSuchAlgorithmException nsae) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        log.error(nsae.toString());
    }

    finally {
        // Try deleting the temp file
        if (filename != null) {
            File f = new File(filename);
            if (f != null && !f.delete()) {
                log.error("Unable to delete file: " + filename);
            }
        }
    }
}

From source file:axiom.servlet.AbstractServletClient.java

/**
 * Handle a request./*from www  .ja  va2s  . c  o m*/
 *
 * @param request ...
 * @param response ...
 *
 * @throws ServletException ...
 * @throws IOException ...
 */
protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    final String httpMethod = request.getMethod();
    if (!"POST".equalsIgnoreCase(httpMethod) && !"GET".equalsIgnoreCase(httpMethod)) {
        sendError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "HTTP Method " + httpMethod + " not supported.");
        return;
    }

    RequestTrans reqtrans = new RequestTrans(request, response, getPathInfo(request));

    try {
        // get the character encoding
        String encoding = request.getCharacterEncoding();

        if (encoding == null) {
            // no encoding from request, use the application's charset
            encoding = getApplication().getCharset();
        }

        // read and set http parameters
        parseParameters(request, reqtrans, encoding);

        List uploads = null;
        ServletRequestContext reqcx = new ServletRequestContext(request);

        if (ServletFileUpload.isMultipartContent(reqcx)) {
            // get session for upload progress monitoring
            UploadStatus uploadStatus = getApplication().getUploadStatus(reqtrans);
            try {
                uploads = parseUploads(reqcx, reqtrans, uploadStatus, encoding);
            } catch (Exception upx) {
                System.err.println("Error in file upload: " + upx);
                if (uploadSoftfail) {
                    String msg = upx.getMessage();
                    if (msg == null || msg.length() == 0) {
                        msg = upx.toString();
                    }
                    reqtrans.set("axiom_upload_error", msg);
                } else if (upx instanceof FileUploadBase.SizeLimitExceededException) {
                    sendError(response, HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE,
                            "File upload size exceeds limit of " + uploadLimit + "kB");
                    return;
                } else {
                    sendError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                            "Error in file upload: " + upx);
                    return;
                }
            }
        }

        parseCookies(request, reqtrans, encoding);

        // do standard HTTP variables
        String host = request.getHeader("Host");

        if (host != null) {
            host = host.toLowerCase();
            reqtrans.set("http_host", host);
        }

        String referer = request.getHeader("Referer");

        if (referer != null) {
            reqtrans.set("http_referer", referer);
        }

        try {
            long ifModifiedSince = request.getDateHeader("If-Modified-Since");

            if (ifModifiedSince > -1) {
                reqtrans.setIfModifiedSince(ifModifiedSince);
            }
        } catch (IllegalArgumentException ignore) {
        }

        String ifNoneMatch = request.getHeader("If-None-Match");

        if (ifNoneMatch != null) {
            reqtrans.setETags(ifNoneMatch);
        }

        String remotehost = request.getRemoteAddr();

        if (remotehost != null) {
            reqtrans.set("http_remotehost", remotehost);
        }

        // get the cookie domain to use for this response, if any.
        String resCookieDomain = cookieDomain;

        if (resCookieDomain != null) {
            // check if cookieDomain is valid for this response.
            // (note: cookieDomain is guaranteed to be lower case)
            // check for x-forwarded-for header, fix for bug 443
            String proxiedHost = request.getHeader("x-forwarded-host");
            if (proxiedHost != null) {
                if (proxiedHost.toLowerCase().indexOf(cookieDomain) == -1) {
                    resCookieDomain = null;
                }
            } else if ((host != null) && host.toLowerCase().indexOf(cookieDomain) == -1) {
                resCookieDomain = null;
            }
        }

        // check if session cookie is present and valid, creating it if not.
        checkSessionCookie(request, response, reqtrans, resCookieDomain);

        String browser = request.getHeader("User-Agent");

        if (browser != null) {
            reqtrans.set("http_browser", browser);
        }

        String language = request.getHeader("Accept-Language");

        if (language != null) {
            reqtrans.set("http_language", language);
        }

        String authorization = request.getHeader("authorization");

        if (authorization != null) {
            reqtrans.set("authorization", authorization);
        }

        ResponseTrans restrans = getApplication().execute(reqtrans);

        // if the response was already written and committed by the application
        // we can skip this part and return
        if (response.isCommitted()) {
            return;
        }

        // set cookies
        if (restrans.countCookies() > 0) {
            CookieTrans[] resCookies = restrans.getCookies();

            for (int i = 0; i < resCookies.length; i++)
                try {
                    Cookie c = resCookies[i].getCookie("/", resCookieDomain);

                    response.addCookie(c);
                } catch (Exception ignore) {
                    ignore.printStackTrace();
                }
        }

        // write response
        writeResponse(request, response, reqtrans, restrans);

    } catch (Exception x) {
        try {
            if (debug) {
                sendError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Server error: " + x);
                x.printStackTrace();
            } else {
                sendError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        "The server encountered an error while processing your request. "
                                + "Please check back later.");
            }

            log("Exception in execute: " + x);
        } catch (IOException io_e) {
            log("Exception in sendError: " + io_e);
        }
    }
}

From source file:org.openrepose.nodeservice.httpcomponent.RequestProxyServiceImpl.java

private int executeProxyRequest(HttpRequestBase httpMethodProxyRequest, HttpServletResponse response)
        throws IOException, HttpException {
    HttpClientResponse httpClientResponse = getClient();

    try {//  ww w.jav  a  2  s.  c  o m
        HttpResponse httpResponse = httpClientResponse.getHttpClient().execute(httpMethodProxyRequest);
        HttpComponentResponseCodeProcessor responseCode = new HttpComponentResponseCodeProcessor(
                httpResponse.getStatusLine().getStatusCode());
        HttpComponentResponseProcessor responseProcessor = new HttpComponentResponseProcessor(httpResponse,
                response, responseCode);

        if (responseCode.isRedirect()) {
            responseProcessor.sendTranslatedRedirect(responseCode.getCode());
        } else {
            responseProcessor.process();
        }

        return responseCode.getCode();
    } catch (ClientProtocolException ex) {
        if (Throwables.getRootCause(ex) instanceof ReadLimitReachedException) {
            LOG.error("Error reading request content", ex);
            response.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE,
                    "Error reading request content");
        } else {
            //Sadly, because of how this is implemented, I can't make sure my problem is actually with
            // the origin service. I can only "fail" here.
            LOG.error("Error processing outgoing request", ex);
            return -1;
        }
    } finally {
        httpClientService.releaseClient(httpClientResponse);
    }
    return 1;

}

From source file:helma.servlet.AbstractServletClient.java

/**
 * Handle a request.//  w w w  . j a  va  2  s.  c o m
 *
 * @param request ...
 * @param response ...
 *
 * @throws ServletException ...
 * @throws IOException ...
 */
protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    RequestTrans reqtrans = new RequestTrans(request, response, getPathInfo(request));

    try {
        // get the character encoding
        String encoding = request.getCharacterEncoding();

        if (encoding == null) {
            // no encoding from request, use the application's charset
            encoding = getApplication().getCharset();
        }

        // read cookies
        Cookie[] reqCookies = request.getCookies();

        if (reqCookies != null) {
            for (int i = 0; i < reqCookies.length; i++) {
                try {
                    // get Cookies
                    String key = reqCookies[i].getName();

                    if (sessionCookieName.equals(key)) {
                        reqtrans.setSession(reqCookies[i].getValue());
                    }
                    reqtrans.setCookie(key, reqCookies[i]);
                } catch (Exception badCookie) {
                    log("Error setting cookie", badCookie);
                }
            }
        }

        // get the cookie domain to use for this response, if any.
        String resCookieDomain = cookieDomain;

        if (resCookieDomain != null) {
            // check if cookieDomain is valid for this response.
            // (note: cookieDomain is guaranteed to be lower case)
            // check for x-forwarded-for header, fix for bug 443
            String proxiedHost = request.getHeader("x-forwarded-host");
            if (proxiedHost != null) {
                if (proxiedHost.toLowerCase().indexOf(resCookieDomain) == -1) {
                    resCookieDomain = null;
                }
            } else {
                String host = (String) reqtrans.get("http_host");
                // http_host is guaranteed to be lower case 
                if (host != null && host.indexOf(resCookieDomain) == -1) {
                    resCookieDomain = null;
                }
            }
        }

        // check if session cookie is present and valid, creating it if not.
        checkSessionCookie(request, response, reqtrans, resCookieDomain);

        // read and set http parameters
        parseParameters(request, reqtrans, encoding);

        // read file uploads
        List uploads = null;
        ServletRequestContext reqcx = new ServletRequestContext(request);

        if (ServletFileUpload.isMultipartContent(reqcx)) {
            // get session for upload progress monitoring
            UploadStatus uploadStatus = getApplication().getUploadStatus(reqtrans);
            try {
                uploads = parseUploads(reqcx, reqtrans, uploadStatus, encoding);
            } catch (Exception upx) {
                log("Error in file upload", upx);
                String message;
                boolean tooLarge = (upx instanceof FileUploadBase.SizeLimitExceededException);
                if (tooLarge) {
                    message = "File upload size exceeds limit of " + uploadLimit + " kB";
                } else {
                    message = upx.getMessage();
                    if (message == null || message.length() == 0) {
                        message = upx.toString();
                    }
                }
                if (uploadStatus != null) {
                    uploadStatus.setError(message);
                }

                if (uploadSoftfail || uploadStatus != null) {
                    reqtrans.set("helma_upload_error", message);
                } else {
                    int errorCode = tooLarge ? HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE
                            : HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
                    sendError(response, errorCode, "Error in file upload: " + message);
                    return;
                }
            }
        }

        ResponseTrans restrans = getApplication().execute(reqtrans);

        // delete uploads if any
        if (uploads != null) {
            for (int i = 0; i < uploads.size(); i++) {
                ((FileItem) uploads.get(i)).delete();
            }
        }

        // if the response was already written and committed by the application
        // we can skip this part and return
        if (response.isCommitted()) {
            return;
        }

        // set cookies
        if (restrans.countCookies() > 0) {
            CookieTrans[] resCookies = restrans.getCookies();

            for (int i = 0; i < resCookies.length; i++)
                try {
                    Cookie c = resCookies[i].getCookie("/", resCookieDomain);

                    response.addCookie(c);
                } catch (Exception x) {
                    getApplication().logEvent("Error adding cookie: " + x);
                }
        }

        // write response
        writeResponse(request, response, reqtrans, restrans);
    } catch (Exception x) {
        log("Exception in execute", x);
        try {
            if (debug) {
                sendError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Server error: " + x);
            } else {
                sendError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        "The server encountered an error while processing your request. "
                                + "Please check back later.");
            }
        } catch (IOException iox) {
            log("Exception in sendError", iox);
        }
    }
}

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

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

    List<Endpoint> endpointList;

    try {//from ww  w.  ja  va2  s  . c  o m
        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 endpointListResponse = akkaServiceClient.get(ENDPOINTS_PREFIX + userToken,
                targetHostUri + TOKENS + userToken + ENDPOINTS, headers);

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

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

            if (endpointListResponse.getStatus() == HttpServletResponse.SC_OK) {
                endpointList = getEndpointList(endpointListResponse);
            } else {
                delegationMessage.set("Unable to get endpoints for user: " + userToken
                        + " with configured admin credentials");
                LOG.error("Still unable to get endpoints: " + endpointListResponse.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: "
                    + endpointListResponse.getStatus());
            throw buildAuthServiceOverLimitException(endpointListResponse);
        default:
            delegationMessage.set("Unable to get endpoints for token: " + userToken + ". Status code: "
                    + endpointListResponse.getStatus());
            LOG.error("Unable to get endpoints for token. Status code: " + endpointListResponse.getStatus());
            throw new AuthServiceException("Unable to retrieve service catalog for user. Response from "
                    + targetHostUri + ": " + endpointListResponse.getStatus());
        }
    } catch (AkkaServiceClientException e) {
        throw new AuthServiceException("Unable to get endpoints.", e);
    }

    return endpointList;
}

From source file:org.signserver.web.GenericProcessServlet.java

/**
 * Handles http post.// ww  w .  j  a va2  s  .c om
 *
 * @param req servlet request
 * @param res servlet response
 *
 * @throws IOException input/output error
 * @throws ServletException error
 */
@Override
public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
    LOG.debug(">doPost()");

    int workerId = 1;
    byte[] data = null;
    String fileName = null;
    String pdfPassword = null;
    boolean workerRequest = false;

    if (LOG.isDebugEnabled()) {
        LOG.debug("Received a request with length: " + req.getContentLength());
    }

    final String workerNameOverride = (String) req.getAttribute(WORKERNAME_PROPERTY_OVERRIDE);

    if (workerNameOverride != null) {
        workerId = getWorkerSession().getWorkerId(workerNameOverride);
        workerRequest = true;
    }

    final long maxUploadSize = getMaxUploadSize();

    ProcessType processType = ProcessType.signDocument;
    final MetaDataHolder metadataHolder = new MetaDataHolder();

    if (ServletFileUpload.isMultipartContent(req)) {
        final DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(Integer.MAX_VALUE); // Don't write to disk

        final ServletFileUpload upload = new ServletFileUpload(factory);

        // Limit the maximum size of input
        upload.setSizeMax(maxUploadSize);

        try {
            final List items = upload.parseRequest(req);
            final Iterator iter = items.iterator();
            FileItem fileItem = null;
            String encoding = null;
            while (iter.hasNext()) {
                final Object o = iter.next();
                if (o instanceof FileItem) {
                    final FileItem item = (FileItem) o;

                    if (item.isFormField()) {
                        if (!workerRequest) {
                            if (WORKERNAME_PROPERTY_NAME.equals(item.getFieldName())) {
                                if (LOG.isDebugEnabled()) {
                                    LOG.debug("Found a signerName in the request: " + item.getString());
                                }
                                workerId = getWorkerSession().getWorkerId(item.getString());
                            } else if (WORKERID_PROPERTY_NAME.equals(item.getFieldName())) {
                                if (LOG.isDebugEnabled()) {
                                    LOG.debug("Found a signerId in the request: " + item.getString());
                                }
                                try {
                                    workerId = Integer.parseInt(item.getString());
                                } catch (NumberFormatException ignored) {
                                }
                            }
                        }

                        final String itemFieldName = item.getFieldName();

                        if (PDFPASSWORD_PROPERTY_NAME.equals(itemFieldName)) {
                            if (LOG.isDebugEnabled()) {
                                LOG.debug("Found a pdfPassword in the request.");
                            }
                            pdfPassword = item.getString("ISO-8859-1");
                        } else if (PROCESS_TYPE_PROPERTY_NAME.equals(itemFieldName)) {
                            final String processTypeAttribute = item.getString("ISO-8859-1");

                            if (LOG.isDebugEnabled()) {
                                LOG.debug("Found process type in the request: " + processTypeAttribute);
                            }

                            if (processTypeAttribute != null) {
                                try {
                                    processType = ProcessType.valueOf(processTypeAttribute);
                                } catch (IllegalArgumentException e) {
                                    sendBadRequest(res, "Illegal process type: " + processTypeAttribute);
                                    return;
                                }
                            } else {
                                processType = ProcessType.signDocument;
                            }
                        } else if (ENCODING_PROPERTY_NAME.equals(itemFieldName)) {
                            encoding = item.getString("ISO-8859-1");
                        } else if (isFieldMatchingMetaData(itemFieldName)) {
                            try {
                                metadataHolder.handleMetaDataProperty(itemFieldName,
                                        item.getString("ISO-8859-1"));
                            } catch (IOException e) {
                                sendBadRequest(res, "Malformed properties given using REQUEST_METADATA.");
                                return;
                            }
                        }
                    } else {
                        // We only care for one upload at a time right now
                        if (fileItem == null) {
                            fileItem = item;
                        }
                    }
                }
            }

            if (fileItem == null) {
                sendBadRequest(res, "Missing file content in upload");
                return;
            } else {
                fileName = fileItem.getName();
                data = fileItem.get(); // Note: Reads entiry file to memory

                if (encoding != null && !encoding.isEmpty()) {
                    if (ENCODING_BASE64.equalsIgnoreCase(encoding)) {
                        if (LOG.isDebugEnabled()) {
                            LOG.debug("Decoding base64 data");
                        }
                        data = Base64.decode(data);
                    } else {
                        sendBadRequest(res, "Unknown encoding for the 'data' field: " + encoding);
                        return;
                    }
                }
            }
        } catch (FileUploadBase.SizeLimitExceededException ex) {
            LOG.error(HTTP_MAX_UPLOAD_SIZE + " exceeded: " + ex.getLocalizedMessage());
            res.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE,
                    "Maximum content length is " + maxUploadSize + " bytes");
            return;
        } catch (FileUploadException ex) {
            throw new ServletException("Upload failed", ex);
        }
    } else {
        if (!workerRequest) {
            String name = req.getParameter(WORKERNAME_PROPERTY_NAME);
            if (name != null) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Found a signerName in the request: " + name);
                }
                workerId = getWorkerSession().getWorkerId(name);
            }
            String id = req.getParameter(WORKERID_PROPERTY_NAME);
            if (id != null) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Found a signerId in the request: " + id);
                }
                workerId = Integer.parseInt(id);
            }
        }

        final Enumeration<String> params = req.getParameterNames();

        while (params.hasMoreElements()) {
            final String property = params.nextElement();
            if (PDFPASSWORD_PROPERTY_NAME.equals(property)) {
                pdfPassword = (String) req.getParameter(PDFPASSWORD_PROPERTY_NAME);
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Found a pdfPassword in the request.");
                }
            } else if (isFieldMatchingMetaData(property)) {
                try {
                    metadataHolder.handleMetaDataProperty(property, req.getParameter(property));
                } catch (IOException e) {
                    sendBadRequest(res, "Malformed properties given using REQUEST_METADATA.");
                    return;
                }
            }
        }

        final String processTypeAttribute = (String) req.getParameter(PROCESS_TYPE_PROPERTY_NAME);

        if (processTypeAttribute != null) {
            try {
                processType = ProcessType.valueOf(processTypeAttribute);
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Found process type in the request: " + processType.name());
                }
            } catch (IllegalArgumentException e) {
                sendBadRequest(res, "Illegal process type: " + processTypeAttribute);
                return;
            }
        } else {
            processType = ProcessType.signDocument;
        }

        if (METHOD_GET.equalsIgnoreCase(req.getMethod())
                || (req.getContentType() != null && req.getContentType().contains(FORM_URL_ENCODED))) {
            LOG.debug("Request is FORM_URL_ENCODED");

            if (req.getParameter(DATA_PROPERTY_NAME) == null) {
                sendBadRequest(res, "Missing field 'data' in request");
                return;
            }
            data = req.getParameter(DATA_PROPERTY_NAME).getBytes();

            String encoding = req.getParameter(ENCODING_PROPERTY_NAME);
            if (encoding != null && !encoding.isEmpty()) {
                if (ENCODING_BASE64.equalsIgnoreCase(encoding)) {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Decoding base64 data");
                    }
                    data = Base64.decode(data);
                } else {
                    sendBadRequest(res, "Unknown encoding for the 'data' field: " + encoding);
                    return;
                }
            }
        } else {
            // Pass-through the content to be handled by worker if
            // unknown content-type
            if (LOG.isDebugEnabled()) {
                LOG.debug("Request Content-type: " + req.getContentType());
            }

            // Get an input stream and read the bytes from the stream
            InputStream in = req.getInputStream();
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            int len;
            byte[] buf = new byte[1024];
            while ((len = in.read(buf)) > 0) {
                os.write(buf, 0, len);
            }
            in.close();
            os.close();
            data = os.toByteArray();
        }
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("Request of type: " + processType.name());
    }

    // Limit the maximum size of input
    if (data.length > maxUploadSize) {
        LOG.error("Content length exceeds " + maxUploadSize + ", not processed: " + req.getContentLength());
        res.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE,
                "Maximum content length is " + maxUploadSize + " bytes");
    } else {
        processRequest(req, res, workerId, data, fileName, pdfPassword, processType, metadataHolder);
    }

    LOG.debug("<doPost()");
}

From source file:org.ajax4jsf.webapp.BaseFilter.java

/**
 * Method catches upload files request. Request parameter
 * <b>org.ajax4jsf.Filter.UPLOAD_FILES_ID</b> indicates if request
 * generated by rich-upload component. If it was detected custom parsing
 * request should be done. Processing information about percent of
 * completion and file size will be put into session scope. 
 * //from   w  w  w. ja v  a 2 s.  com
 * @param request
 * @param response
 * @return 
 * @throws IOException 
 * @throws ServletException 
 */
protected void processUploadsAndHandleRequest(HttpServletRequest request, HttpServletResponse response,
        FilterChain chain) throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;

    Map<String, String> queryParamMap = parseQueryString(httpRequest.getQueryString());
    String uid = queryParamMap.get(FileUploadConstants.UPLOAD_FILES_ID);

    if (uid != null) {

        if (isMultipartRequest(httpRequest)) {
            MultipartRequest multipartRequest = new MultipartRequest(httpRequest, createTempFiles,
                    maxRequestSize, uid);

            Object oldAttributeValue = httpRequest
                    .getAttribute(FileUploadConstants.FILE_UPLOAD_REQUEST_ATTRIBUTE_NAME);
            httpRequest.setAttribute(FileUploadConstants.FILE_UPLOAD_REQUEST_ATTRIBUTE_NAME, multipartRequest);

            try {
                if (isFileSizeRestricted(request, maxRequestSize)) {

                    boolean sendError = Boolean.parseBoolean(queryParamMap.get(SEND_HTTP_ERROR));
                    if (sendError) {
                        response.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE);
                        System.err.println("ERROR " + HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE
                                + "request entity is larger than the server is willing or able to process.");
                        return;
                    } else {
                        printResponse(response, "<html id=\"_richfaces_file_upload_size_restricted\"></html>");
                    }

                } else if (!checkFileCount(httpRequest, queryParamMap.get("id"))) {
                    printResponse(response, "<html id=\"_richfaces_file_upload_forbidden\"></html>");
                } else {

                    handleRequest(multipartRequest, multipartRequest.isFormUpload() ? response
                            : new HttpServletResponseWrapper((HttpServletResponse) response) {
                                @Override
                                public void setContentType(String type) {
                                    super.setContentType(BaseXMLFilter.TEXT_HTML + ";charset=UTF-8");
                                }
                            }, chain);

                    if (!multipartRequest.isDone()) {
                        printResponse(response, "<html id=\"_richfaces_file_upload_stopped\"></html>");
                    }
                }

            } finally {
                httpRequest.setAttribute(FileUploadConstants.FILE_UPLOAD_REQUEST_ATTRIBUTE_NAME,
                        oldAttributeValue);
                multipartRequest.clearRequestData();
            }
        } else {
            handleRequest(request, response, chain);
        }
    } else {
        handleRequest(request, response, chain);
    }
}