Example usage for javax.servlet.http HttpServletResponse SC_METHOD_NOT_ALLOWED

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

Introduction

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

Prototype

int SC_METHOD_NOT_ALLOWED

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

Click Source Link

Document

Status code (405) indicating that the method specified in the Request-Line is not allowed for the resource identified by the Request-URI.

Usage

From source file:edu.stanford.epad.epadws.handlers.dicom.ResourcesFileHandler.java

@Override
public void handle(String s, Request request, HttpServletRequest httpRequest,
        HttpServletResponse httpResponse) {
    ServletOutputStream responseStream = null;
    String origin = httpRequest.getHeader("Origin"); // CORS request should have Origin header
    int statusCode = HttpServletResponse.SC_OK;

    // Origin header indicates a possible CORS requests
    if (origin != null) {
        httpResponse.setHeader("Access-Control-Allow-Origin", origin);
        httpResponse.setHeader("Access-Control-Allow-Credentials", "true"); // Needed to allow cookies
    } else {//from w  w w  . jav  a2s .com
        httpResponse.setHeader("Access-Control-Allow-Origin", "*");
    }

    if (request != null) // In case handler is not called thru jetty
        request.setHandled(true);

    String method = httpRequest.getMethod();
    if ("GET".equalsIgnoreCase(method)) {
        try {
            String sessionID = SessionService.getJSessionIDFromRequest(httpRequest);
            if (sessionID == null || sessionID.length() == 0) {
                log.warning("JSESSIONID is Missing in client request");
                statusCode = HandlerUtil.invalidTokenJSONResponse(INVALID_SESSION_TOKEN_MESSAGE,
                        httpResponse.getWriter(), log);
            } else {
                String username = httpRequest.getParameter("username");
                responseStream = httpResponse.getOutputStream();

                if (SessionService.hasValidSessionID(httpRequest)) {
                    String relativePath = httpRequest.getParameter("relativePath");
                    relativePath = URLDecoder.decode(relativePath, "UTF-8");
                    if (relativePath != null) {
                        File file = new File(EPADConfig.getEPADWebServerResourcesDir() + relativePath);
                        if (!file.exists()) {
                            throw new Exception("File " + file.getAbsolutePath() + " does not exist");
                        }
                        String name = request.getParameter("name");
                        if (name == null)
                            name = file.getName();
                        EPADFileUtils.sendFile(request, httpResponse, file, name, false);
                    } else {
                        statusCode = HandlerUtil.badRequestResponse(MISSING_QUERY_MESSAGE, log);
                        log.warning("Missing Resource Path");
                    }
                } else {
                    statusCode = HandlerUtil.invalidTokenResponse(INVALID_SESSION_TOKEN_MESSAGE, log);
                }
            }
        } catch (Throwable t) {
            statusCode = HandlerUtil.internalErrorResponse(INTERNAL_EXCEPTION_MESSAGE, log);
            log.warning("Error is Resources query", t);
        }
    } else {
        httpResponse.setHeader("Access-Control-Allow-Methods", "GET");
        statusCode = HandlerUtil.warningResponse(HttpServletResponse.SC_METHOD_NOT_ALLOWED, INVALID_METHOD,
                log);
    }
    httpResponse.setStatus(statusCode);
}

From source file:com.zimbra.cs.dav.service.DavServlet.java

@Override
public void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    ZimbraLog.clearContext();//from w w w .  j  a  va 2  s.  c  om
    addRemoteIpToLoggingContext(req);
    ZimbraLog.addUserAgentToContext(req.getHeader(DavProtocol.HEADER_USER_AGENT));

    //bug fix - send 400 for Range requests
    String rangeHeader = req.getHeader(DavProtocol.HEADER_RANGE);
    if (null != rangeHeader) {
        sendError(resp, HttpServletResponse.SC_BAD_REQUEST, "Range header not supported", null, Level.debug);
        return;
    }

    RequestType rtype = getAllowedRequestType(req);
    ZimbraLog.dav.debug("Allowable request types %s", rtype);

    if (rtype == RequestType.none) {
        sendError(resp, HttpServletResponse.SC_NOT_ACCEPTABLE, "Not an allowed request type", null,
                Level.debug);
        return;
    }

    logRequestInfo(req);
    Account authUser = null;
    DavContext ctxt;
    try {
        AuthToken at = AuthProvider.getAuthToken(req, false);
        if (at != null && (at.isExpired() || !at.isRegistered())) {
            at = null;
        }
        if (at != null && (rtype == RequestType.both || rtype == RequestType.authtoken)) {
            authUser = Provisioning.getInstance().get(AccountBy.id, at.getAccountId());
        } else if (at == null && (rtype == RequestType.both || rtype == RequestType.password)) {
            AuthUtil.AuthResult result = AuthUtil.basicAuthRequest(req, resp, true, this);
            if (result.sendErrorCalled) {
                logResponseInfo(resp);
                return;
            }
            authUser = result.authorizedAccount;
        }
        if (authUser == null) {
            try {
                sendError(resp, HttpServletResponse.SC_UNAUTHORIZED, "Authentication failed", null,
                        Level.debug);
            } catch (Exception e) {
            }
            return;
        }
        ZimbraLog.addToContext(ZimbraLog.C_ANAME, authUser.getName());
        ctxt = new DavContext(req, resp, authUser);
    } catch (AuthTokenException e) {
        sendError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "error getting authenticated user", e);
        return;
    } catch (ServiceException e) {
        sendError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "error getting authenticated user", e);
        return;
    }

    DavMethod method = sMethods.get(req.getMethod());
    if (method == null) {
        setAllowHeader(resp);
        sendError(resp, HttpServletResponse.SC_METHOD_NOT_ALLOWED, "Not an allowed method", null, Level.debug);
        return;
    }

    long t0 = System.currentTimeMillis();

    CacheStates cache = null;
    try {
        if (ZimbraLog.dav.isDebugEnabled()) {
            try {
                Upload upload = ctxt.getUpload();
                if (upload.getSize() > 0 && upload.getContentType().startsWith("text")) {
                    if (ZimbraLog.dav.isDebugEnabled()) {
                        StringBuilder logMsg = new StringBuilder("REQUEST\n").append(
                                new String(ByteUtil.readInput(upload.getInputStream(), -1, 20480), "UTF-8"));
                        ZimbraLog.dav.debug(logMsg.toString());
                    }
                }
            } catch (DavException de) {
                throw de;
            } catch (Exception e) {
                ZimbraLog.dav.debug("ouch", e);
            }
        }
        cache = checkCachedResponse(ctxt, authUser);
        if (!ctxt.isResponseSent() && !isProxyRequest(ctxt, method)) {

            method.checkPrecondition(ctxt);
            method.handle(ctxt);
            method.checkPostcondition(ctxt);
            if (!ctxt.isResponseSent()) {
                resp.setStatus(ctxt.getStatus());
            }
        }
        if (!ctxt.isResponseSent()) {
            logResponseInfo(resp);
        }
    } catch (DavException e) {
        if (e.getCause() instanceof MailServiceException.NoSuchItemException
                || e.getStatus() == HttpServletResponse.SC_NOT_FOUND)
            ZimbraLog.dav.info(ctxt.getUri() + " not found");
        else if (e.getStatus() == HttpServletResponse.SC_MOVED_TEMPORARILY
                || e.getStatus() == HttpServletResponse.SC_MOVED_PERMANENTLY)
            ZimbraLog.dav.info("sending redirect");

        try {
            if (e.isStatusSet()) {
                resp.setStatus(e.getStatus());
                if (e.hasErrorMessage())
                    e.writeErrorMsg(resp.getOutputStream());
                if (ZimbraLog.dav.isDebugEnabled()) {
                    ZimbraLog.dav.info("sending http error %d because: %s", e.getStatus(), e.getMessage(), e);
                } else {
                    ZimbraLog.dav.info("sending http error %d because: %s", e.getStatus(), e.getMessage());
                }
                if (e.getCause() != null)
                    ZimbraLog.dav.debug("exception: ", e.getCause());
            } else {
                sendError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        "error handling method " + method.getName(), e);
            }
        } catch (IllegalStateException ise) {
            ZimbraLog.dav.debug("can't write error msg", ise);
        }
    } catch (ServiceException e) {
        if (e instanceof MailServiceException.NoSuchItemException) {
            sendError(resp, HttpServletResponse.SC_NOT_FOUND, ctxt.getUri() + " not found", null, Level.info);
            return;
        }
        sendError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "error handling method " + method.getName(), e);
    } catch (Exception e) {
        try {
            sendError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "error handling method " + method.getName(), e);
        } catch (Exception ex) {
        }
    } finally {
        long t1 = System.currentTimeMillis();
        ZimbraLog.dav.info("DavServlet operation " + method.getName() + " to " + req.getPathInfo() + " (depth: "
                + ctxt.getDepth().name() + ") finished in " + (t1 - t0) + "ms");
        if (cache != null)
            cacheCleanUp(ctxt, cache);
        ctxt.cleanup();
    }
}

From source file:org.apache.chemistry.opencmis.server.impl.atompub.CmisAtomPubServlet.java

/**
 * Dispatches to feed, entry or whatever.
 *///from  ww  w  .j a  v  a  2 s .  c  om
private void dispatch(CallContext context, HttpServletRequest request, HttpServletResponse response,
        String[] pathFragments) throws Exception {

    CmisService service = null;
    try {
        // get the service
        service = getServiceFactory().getService(context);

        // analyze the path
        if (pathFragments.length < 2) {
            // CSRF check
            checkCsrfToken(request, response, true, false);

            // root -> service document
            dispatcher.dispatch("", METHOD_GET, context, service, null, request, response);
            return;
        }

        String method = request.getMethod();
        String repositoryId = pathFragments[0];
        String resource = pathFragments[1];

        // CSRF check
        checkCsrfToken(request, response, false,
                RESOURCE_CONTENT.equals(resource) && METHOD_GET.equals(method));

        // dispatch
        boolean callServiceFound = dispatcher.dispatch(resource, method, context, service, repositoryId,
                request, response);

        // if the dispatcher couldn't find a matching service
        // -> return an error message
        if (!callServiceFound) {
            response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, "Unknown operation");
        }
    } finally {
        if (service != null) {
            service.close();
        }
    }
}

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

/**
 * Handle a Delete request./*  ww w  .  j ava  2s . c  o m*/
 *
 * @param req The servlet request we are processing
 * @param resp The servlet response we are processing
* @throws IOException if the response cannot be sent
 */
@Override
protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    // Strip the username part
    String path;
    try {
        path = getUserPath(req);
    } catch (ObjectNotFoundException e) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage());
        return;
    }

    if (path.startsWith(PATH_OTHERS)) {
        resp.addHeader("Allow", methodsAllowed.get(PATH_OTHERS));
        resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
    } else if (path.startsWith(PATH_SEARCH)) {
        resp.addHeader("Allow", methodsAllowed.get(PATH_SEARCH));
        resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
    } else if (path.startsWith(PATH_TOKEN)) {
        resp.addHeader("Allow", methodsAllowed.get(PATH_TOKEN));
        resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
    } else if (path.startsWith(PATH_USERS)) {
        resp.addHeader("Allow", methodsAllowed.get(PATH_USERS));
        resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
    } else if (path.startsWith(PATH_SHARED)) {
        resp.addHeader("Allow", methodsAllowed.get(PATH_SHARED));
        resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
    } else if (path.startsWith(PATH_TAGS)) {
        resp.addHeader("Allow", methodsAllowed.get(PATH_TAGS));
        resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
    } else if (path.startsWith(PATH_GROUPS))
        new GroupsHandler().deleteGroup(req, resp);
    else if (path.startsWith(PATH_TRASH))
        new TrashHandler().emptyTrash(req, resp);
    else if (path.startsWith(PATH_FILES))
        new FilesHandler(getServletContext()).deleteResource(req, resp);
    else
        resp.sendError(HttpServletResponse.SC_NOT_FOUND, req.getRequestURI());
}

From source file:org.sakaiproject.nakamura.http.usercontent.ServerProtectionServiceImpl.java

/**
 * {@inheritDoc}/*from   w ww  . ja v  a  2  s .  c o  m*/
 * 
 * This method requires a resource to operate successfully and is best used by a Sling
 * Filter rather than a Servlet Filter, so that Sling will have made the appropriate
 * resource resolution.
 *
 * @see org.sakaiproject.nakamura.api.http.usercontent.ServerProtectionService#isRequestSafe(org.apache.sling.api.SlingHttpServletRequest,
 *      org.apache.sling.api.SlingHttpServletResponse)
 */
public boolean isRequestSafe(SlingHttpServletRequest srequest, SlingHttpServletResponse sresponse)
        throws UnsupportedEncodingException, IOException {
    if (disableProtectionForDevMode) {
        LOGGER.warn("XSS Protection is disabled [isRequestSafe]");
        return true;
    }
    // if the method is not safe, the request can't be safe.
    if (!isMethodSafe(srequest, sresponse)) {
        return false;
    }
    String method = srequest.getMethod();
    if ("GET|OPTIONS|HEAD".indexOf(method) < 0) {
        String userId = srequest.getRemoteUser();
        if (User.ANON_USER.equals(userId)) {
            String path = srequest.getRequestURI();
            boolean safeForAnonToPost = false;
            for (String safePath : safeForAnonToPostPaths) {
                if (path.startsWith(safePath)) {
                    safeForAnonToPost = true;
                    break;
                }
            }
            if (!safeForAnonToPost) {
                sresponse.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED,
                        "Anon users may not perform POST operations");
                return false;
            }
        }
    }
    boolean safeHost = isSafeHost(srequest);
    if (safeHost && "GET".equals(method)) {
        boolean safeToStream = false;
        RequestPathInfo requestPathInfo = srequest.getRequestPathInfo();
        String ext = requestPathInfo.getExtension();
        if (ext == null || "res".equals(ext)) {
            // this is going to stream
            String path = srequest.getRequestURI();
            LOGGER.debug("Checking [{}] RequestPathInfo {}", path, requestPathInfo);
            safeToStream = isMatchToSafePath(path);
            if (!safeToStream) {
                Resource resource = srequest.getResource();
                if (resource != null) {
                    if ("sling:nonexisting".equals(resource.getResourceType())) {
                        // Trust a "GET" of non-existing content so that the 404 comes from
                        // the right port (KERN-2001)
                        LOGGER.debug("Non existing resource {}", resource.getPath());
                        return true;
                    }
                    // The original unrecognized URI might be a mapping to a trusted resource.
                    // Check again now that any aliases have been resolved.
                    String resourcePath = resource.getPath();
                    LOGGER.debug("Checking Resource Path [{}]", resourcePath);
                    safeToStream = isMatchToSafePath(resourcePath);
                    if (!safeToStream) {
                        for (ServerProtectionValidator serverProtectionValidator : serverProtectionValidators) {
                            if (serverProtectionValidator.safeToStream(srequest, resource)) {
                                LOGGER.debug(" {} said this {} is safe to stream ", serverProtectionValidator,
                                        resourcePath);
                                safeToStream = true;
                                break;
                            }
                        }
                    }
                }
            } else {
                LOGGER.debug("Content was safe to stream ");
            }
        } else {
            safeToStream = true;
            LOGGER.debug("doesnt look like a body, checking with vetos");
        }
        LOGGER.debug("Checking server vetos, safe to stream ? {} ", safeToStream);
        for (ServerProtectionVeto serverProtectionVeto : serverProtectionVetos) {
            LOGGER.debug("Checking for Veto on {} ", serverProtectionVeto);
            if (serverProtectionVeto.willVeto(srequest)) {
                safeToStream = serverProtectionVeto.safeToStream(srequest);
                LOGGER.debug("{} vetoed {}  ", serverProtectionVeto, safeToStream);
                break;
            }
        }
        if (!safeToStream) {
            redirectToContent(srequest, sresponse);
            return false;
        }
        LOGGER.debug("Request will be sent from this host, no redirect {}",
                srequest.getRequestURL().toString());
    }
    return true;
}

From source file:net.yacy.http.servlets.YaCyDefaultServlet.java

@Override
protected void doTrace(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
}

From source file:com.imaginary.home.cloud.api.RestApi.java

@Override
public void doPut(@Nonnull HttpServletRequest req, @Nonnull HttpServletResponse resp)
        throws IOException, ServletException {
    String requestId = request(req);

    try {//  w  w w  .j  a va2  s.  c o  m
        Map<String, Object> headers = parseHeaders(req);
        String[] path = getPath(req);

        if (path.length < 1) {
            throw new RestException(HttpServletResponse.SC_METHOD_NOT_ALLOWED, RestException.INVALID_OPERATION,
                    "No PUT is allowed against /");
        } else if (apiCalls.containsKey(path[0])) {
            Map<String, Object> parameters = parseParameters(req);
            APICall call = apiCalls.get(path[0]);

            String userId = authenticate("PUT", req, headers);

            call.put(requestId, userId, path, req, resp, headers, parameters);
        } else {
            throw new RestException(HttpServletResponse.SC_NOT_FOUND, RestException.NO_SUCH_RESOURCE,
                    "No " + path[0] + " resource exists in this API");
        }
    } catch (RestException e) {
        HashMap<String, Object> error = new HashMap<String, Object>();

        error.put("code", e.getStatus());
        error.put("message", e.getMessage());
        error.put("description", e.getDescription());
        resp.setStatus(e.getStatus());
        resp.getWriter().println((new JSONObject(error)).toString());
        resp.getWriter().flush();
    } catch (Throwable t) {
        t.printStackTrace();
        HashMap<String, Object> error = new HashMap<String, Object>();

        error.put("code", HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        error.put("message", RestException.INTERNAL_ERROR);
        error.put("description", t.getMessage());
        resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        resp.getWriter().println((new JSONObject(error)).toString());
        resp.getWriter().flush();
    }
}

From source file:ch.entwine.weblounge.common.impl.request.Http11ProtocolHandler.java

/**
 * Method generateHeaders./*from ww w .j  a  va2s  . c o m*/
 * 
 * @param resp
 * @param type
 */
public static void generateHeaders(HttpServletResponse resp, Http11ResponseType type) {

    /* generate headers only once! */
    if (type.headers)
        return;
    type.headers = true;

    /* adjust the statistics */
    ++stats[STATS_HEADER_GENERATED];
    incResponseStats(type.type, headerStats);

    /* set the date header */
    resp.setDateHeader(HEADER_DATE, type.time);

    /* check expires */
    if (type.expires > type.time + MS_PER_YEAR) {
        type.expires = type.time + MS_PER_YEAR;
        log.warn("Expiration date too far in the future. Adjusting.");
    }

    /* set the standard headers and status code */
    switch (type.type) {
    case RESPONSE_PARTIAL_CONTENT:
        if (type.expires > type.time)
            resp.setDateHeader(HEADER_EXPIRES, type.expires);
        if (type.modified > 0) {
            resp.setHeader(HEADER_ETAG, Http11Utils.calcETag(type.modified));
            resp.setDateHeader(HEADER_LAST_MODIFIED, type.modified);
        }
        if (type.size < 0 || type.from < 0 || type.to < 0 || type.from > type.to || type.to > type.size) {
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            break;
        }
        resp.setContentLength((int) type.size);
        resp.setHeader(HEADER_CONTENT_RANGE, "bytes " + type.from + "-" + type.to + "/" + type.size);
        resp.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
        break;

    case RESPONSE_OK:
        if (type.expires > type.time) {
            resp.setDateHeader(HEADER_EXPIRES, type.expires);
        } else if (type.expires == 0) {
            resp.setHeader(HEADER_CACHE_CONTROL, "no-cache");
            resp.setHeader(HEADER_PRAGMA, "no-cache");
            resp.setDateHeader(HEADER_EXPIRES, 0);
        }
        if (type.modified > 0) {
            resp.setHeader(HEADER_ETAG, Http11Utils.calcETag(type.modified));
            resp.setDateHeader(HEADER_LAST_MODIFIED, type.modified);
        }
        if (type.size >= 0)
            resp.setContentLength((int) type.size);
        resp.setStatus(HttpServletResponse.SC_OK);
        break;

    case RESPONSE_NOT_MODIFIED:
        if (type.expires > type.time)
            resp.setDateHeader(HEADER_EXPIRES, type.expires);
        if (type.modified > 0)
            resp.setHeader(HEADER_ETAG, Http11Utils.calcETag(type.modified));
        resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        break;

    case RESPONSE_METHOD_NOT_ALLOWED:
        resp.setHeader(HEADER_ALLOW, "GET, POST, HEAD");
        resp.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        break;

    case RESPONSE_PRECONDITION_FAILED:
        if (type.expires > type.time)
            resp.setDateHeader(HEADER_EXPIRES, type.expires);
        if (type.modified > 0) {
            resp.setHeader(HEADER_ETAG, Http11Utils.calcETag(type.modified));
            resp.setDateHeader(HEADER_LAST_MODIFIED, type.modified);
        }
        resp.setStatus(HttpServletResponse.SC_PRECONDITION_FAILED);
        break;

    case RESPONSE_REQUESTED_RANGE_NOT_SATISFIABLE:
        if (type.expires > type.time)
            resp.setDateHeader(HEADER_EXPIRES, type.expires);
        if (type.modified > 0) {
            resp.setHeader(HEADER_ETAG, Http11Utils.calcETag(type.modified));
            resp.setDateHeader(HEADER_LAST_MODIFIED, type.modified);
        }
        if (type.size >= 0)
            resp.setHeader(HEADER_CONTENT_RANGE, "*/" + type.size);
        break;

    case RESPONSE_INTERNAL_SERVER_ERROR:
    default:
        resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

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

/**
  * Serve the specified resource, optionally including the data content.
  */*from   ww w. j av a 2 s  . co  m*/
  * @param req The servlet request we are processing
  * @param resp The servlet response we are creating
  * @param content Should the content be included?
  *
  * @exception IOException if an input/output error occurs
  * @exception ServletException if a servlet-specified error occurs
  * @throws RpcException
  * @throws InsufficientPermissionsException
  * @throws ObjectNotFoundException
  */
@Override
protected void serveResource(HttpServletRequest req, HttpServletResponse resp, boolean content)
        throws IOException, ServletException {
    boolean authDeferred = getAuthDeferred(req);
    String path = getInnerPath(req, PATH_FILES);
    if (path.equals(""))
        path = "/";
    try {
        path = URLDecoder.decode(path, "UTF-8");
    } catch (IllegalArgumentException e) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
        return;
    }
    String progress = req.getParameter(PROGRESS_PARAMETER);

    if (logger.isDebugEnabled())
        if (content)
            logger.debug("Serving resource '" + path + "' headers and data");
        else
            logger.debug("Serving resource '" + path + "' headers only");

    User user = getUser(req);
    User owner = getOwner(req);
    boolean exists = true;
    Object resource = null;
    FileHeader file = null;
    Folder folder = null;
    try {
        resource = getService().getResourceAtPath(owner.getId(), path, false);
    } catch (ObjectNotFoundException e) {
        exists = false;
    } catch (RpcException e) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
        return;
    }

    if (!exists && authDeferred) {
        // We do not want to leak information if the request
        // was not authenticated.
        resp.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    if (resource instanceof Folder)
        folder = (Folder) resource;
    else
        file = (FileHeader) resource; // Note that file will be null, if (!exists).

    // Now it's time to perform the deferred authentication check.
    // Since regular signature checking was already performed,
    // we need to check the read-all flag or the signature-in-parameters.
    if (authDeferred) {
        if (file != null && !file.isReadForAll() && content) {
            // Check for GET with the signature in the request parameters.
            String auth = req.getParameter(AUTHORIZATION_PARAMETER);
            String dateParam = req.getParameter(DATE_PARAMETER);
            if (auth == null || dateParam == null) {
                // Check for a valid authentication cookie.
                if (req.getCookies() != null) {
                    boolean found = false;
                    for (Cookie cookie : req.getCookies())
                        if (Login.AUTH_COOKIE.equals(cookie.getName())) {
                            String cookieauth = cookie.getValue();
                            int sepIndex = cookieauth.indexOf(Login.COOKIE_SEPARATOR);
                            if (sepIndex == -1) {
                                handleAuthFailure(req, resp);
                                return;
                            }
                            String username = URLDecoder.decode(cookieauth.substring(0, sepIndex), "US-ASCII");
                            user = null;
                            try {
                                user = getService().findUser(username);
                            } catch (RpcException e) {
                                resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
                                return;
                            }
                            if (user == null) {
                                resp.sendError(HttpServletResponse.SC_FORBIDDEN);
                                return;
                            }
                            req.setAttribute(USER_ATTRIBUTE, user);
                            String token = cookieauth.substring(sepIndex + 1);
                            if (user.getAuthToken() == null) {
                                resp.sendError(HttpServletResponse.SC_FORBIDDEN);
                                return;
                            }
                            if (!Arrays.equals(user.getAuthToken(), Base64.decodeBase64(token))) {
                                resp.sendError(HttpServletResponse.SC_FORBIDDEN);
                                return;
                            }
                            found = true;
                            break;
                        }
                    if (!found) {
                        handleAuthFailure(req, resp);
                        return;
                    }
                } else {
                    handleAuthFailure(req, resp);
                    return;
                }
            } else {
                long timestamp;
                try {
                    timestamp = DateUtil.parseDate(dateParam).getTime();
                } catch (DateParseException e) {
                    resp.sendError(HttpServletResponse.SC_FORBIDDEN, e.getMessage());
                    return;
                }

                // Fetch the Authorization parameter and find the user specified in it.
                String[] authParts = auth.split(" ");
                if (authParts.length != 2) {
                    resp.sendError(HttpServletResponse.SC_FORBIDDEN);
                    return;
                }
                String username = authParts[0];
                String signature = authParts[1];
                user = null;
                try {
                    user = getService().findUser(username);
                } catch (RpcException e) {
                    resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
                    return;
                }
                if (user == null) {
                    resp.sendError(HttpServletResponse.SC_FORBIDDEN);
                    return;
                }
                req.setAttribute(USER_ATTRIBUTE, user);

                // Remove the servlet path from the request URI.
                String p = req.getRequestURI();
                String servletPath = req.getContextPath() + req.getServletPath();
                p = p.substring(servletPath.length());
                // Validate the signature in the Authorization parameter.
                String data = req.getMethod() + dateParam + p;
                if (!isSignatureValid(signature, user, data)) {
                    resp.sendError(HttpServletResponse.SC_FORBIDDEN);
                    return;
                }
            }
        } else if (folder != null && folder.isReadForAll() || file != null && file.isReadForAll()) {
            //This case refers to a folder or file with public privileges
            //For a read-for-all folder request, pretend the owner is making it.
            user = owner;
            req.setAttribute(USER_ATTRIBUTE, user);
        } else if (folder != null && !folder.isReadForAll()) {
            resp.sendError(HttpServletResponse.SC_FORBIDDEN);
            return;
        } else {
            resp.sendError(HttpServletResponse.SC_FORBIDDEN);
            return;
        }
    }
    // If the resource is not a collection, and the resource path
    // ends with "/" or "\", return NOT FOUND.
    if (folder == null)
        if (path.endsWith("/") || path.endsWith("\\")) {
            resp.sendError(HttpServletResponse.SC_NOT_FOUND, req.getRequestURI());
            return;
        }

    // Workaround for IE's broken caching behavior.
    if (folder != null)
        resp.setHeader("Expires", "-1");

    // A request for upload progress.
    if (progress != null && content) {
        serveProgress(req, resp, progress, user, file);
        return;
    }

    // Fetch the version to retrieve, if specified.
    String verStr = req.getParameter(VERSION_PARAM);
    int version = 0;
    FileBody oldBody = null;
    if (verStr != null && file != null)
        try {
            version = Integer.valueOf(verStr);
        } catch (NumberFormatException e) {
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, req.getRequestURI());
            return;
        }
    if (version > 0)
        try {
            oldBody = getService().getFileVersion(user.getId(), file.getId(), version);
        } catch (RpcException e) {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
            return;
        } catch (ObjectNotFoundException e) {
            resp.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        } catch (InsufficientPermissionsException e) {
            resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            return;
        }

    // Check if the conditions specified in the optional If headers are
    // satisfied. Doing this for folders would require recursive checking
    // for all of their children, which in turn would defy the purpose of
    // the optimization.
    if (folder == null) {
        // Checking If headers.
        if (!checkIfHeaders(req, resp, file, oldBody))
            return;
    } else if (!checkIfModifiedSince(req, resp, folder))
        return;

    // Find content type.
    String contentType = null;
    boolean isContentHtml = false;
    boolean expectJSON = false;

    if (file != null) {
        contentType = version > 0 ? oldBody.getMimeType() : file.getCurrentBody().getMimeType();
        if (contentType == null) {
            contentType = context.getMimeType(file.getName());
            file.getCurrentBody().setMimeType(contentType);
        }
    } else { // folder != null
        String accept = req.getHeader("Accept");
        // The order in this conditional pessimizes the common API case,
        // but is important for backwards compatibility with existing
        // clients who send no accept header and expect a JSON response.
        if (accept != null && accept.contains("text/html")) {
            contentType = "text/html;charset=UTF-8";
            isContentHtml = true;
            //this is the case when clients send the appropriate headers, the contentType is "text/html"
            //and expect a JSON response. The above check applies to FireGSS client
            expectJSON = !authDeferred ? true : false;
        } else if (authDeferred && req.getMethod().equals(METHOD_GET)) {
            contentType = "text/html;charset=UTF-8";
            isContentHtml = true;
            expectJSON = false;
        } else {
            contentType = "application/json;charset=UTF-8";
            expectJSON = true;
        }
    }

    ArrayList ranges = null;
    long contentLength = -1L;

    if (file != null) {
        // Parse range specifier.
        ranges = parseRange(req, resp, file, oldBody);
        // ETag header
        resp.setHeader("ETag", getETag(file, oldBody));
        // Last-Modified header.
        String lastModified = oldBody == null ? getLastModifiedHttp(file.getAuditInfo())
                : getLastModifiedHttp(oldBody.getAuditInfo());
        resp.setHeader("Last-Modified", lastModified);
        // X-GSS-Metadata header.
        try {
            resp.setHeader("X-GSS-Metadata", renderJson(user, file, oldBody));
        } catch (InsufficientPermissionsException e) {
            resp.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            return;
        }
        // Get content length.
        contentLength = version > 0 ? oldBody.getFileSize() : file.getCurrentBody().getFileSize();
        // Special case for zero length files, which would cause a
        // (silent) ISE when setting the output buffer size.
        if (contentLength == 0L)
            content = false;
    } else
        // Set the folder X-GSS-Metadata header.
        try {
            resp.setHeader("X-GSS-Metadata", renderJsonMetadata(user, folder));
        } catch (InsufficientPermissionsException e) {
            resp.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            return;
        }

    ServletOutputStream ostream = null;
    PrintWriter writer = null;

    if (content)
        try {
            ostream = resp.getOutputStream();
        } catch (IllegalStateException e) {
            // If it fails, we try to get a Writer instead if we're
            // trying to serve a text file
            if (contentType == null || contentType.startsWith("text") || contentType.endsWith("xml"))
                writer = resp.getWriter();
            else
                throw e;
        }
    if (folder != null || (ranges == null || ranges.isEmpty()) && req.getHeader("Range") == null
            || ranges == FULL) {
        // Set the appropriate output headers
        if (contentType != null) {
            if (logger.isDebugEnabled())
                logger.debug("contentType='" + contentType + "'");
            resp.setContentType(contentType);
        }
        if (file != null && contentLength >= 0) {
            if (logger.isDebugEnabled())
                logger.debug("contentLength=" + contentLength);
            if (contentLength < Integer.MAX_VALUE)
                resp.setContentLength((int) contentLength);

            else
                // Set the content-length as String to be able to use a long
                resp.setHeader("content-length", "" + contentLength);
        }

        InputStream renderResult = null;
        String relativePath = getRelativePath(req);
        String contextPath = req.getContextPath();
        String servletPath = req.getServletPath();
        String contextServletPath = contextPath + servletPath;
        if (folder != null && content)
            // Serve the directory browser for a public folder
            if (isContentHtml && !expectJSON) {
                try {
                    folder = getService().expandFolder(folder);
                } catch (ObjectNotFoundException e) {
                    resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
                    return;
                } catch (RpcException e) {
                    //We send 500 instead of 404 because this folder has been loaded before in this method and it is
                    //impossible to not be found now
                    resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
                    return;
                }
                renderResult = renderHtml(contextServletPath, relativePath, folder, user);
            }
            // Serve the directory for an ordinary folder or for fireGSS client
            else
                try {
                    renderResult = renderJson(user, folder);
                } catch (InsufficientPermissionsException e) {
                    resp.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
                    return;
                }

        // Copy the input stream to our output stream (if requested)
        if (content) {
            try {
                resp.setBufferSize(output);
            } catch (IllegalStateException e) {
                // Silent catch
            }
            try {
                if (file != null)
                    if (needsContentDisposition(req))
                        resp.setHeader("Content-Disposition",
                                "attachment; filename*=UTF-8''" + getDispositionFilename(file));
                    else
                        resp.setHeader("Content-Disposition",
                                "inline; filename*=UTF-8''" + getDispositionFilename(file));
                if (ostream != null)
                    copy(file, renderResult, ostream, req, oldBody);
                else
                    copy(file, renderResult, writer, req, oldBody);
                if (file != null)
                    updateAccounting(owner, new Date(), contentLength);
            } catch (ObjectNotFoundException e) {
                resp.sendError(HttpServletResponse.SC_NOT_FOUND);
                return;
            } catch (InsufficientPermissionsException e) {
                resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
                return;
            } catch (RpcException e) {
                resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                return;
            }
        }
    } else {
        if (ranges == null || ranges.isEmpty())
            return;
        // Partial content response.
        resp.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);

        if (ranges.size() == 1) {
            Range range = (Range) ranges.get(0);
            resp.addHeader("Content-Range", "bytes " + range.start + "-" + range.end + "/" + range.length);
            long length = range.end - range.start + 1;
            if (length < Integer.MAX_VALUE)
                resp.setContentLength((int) length);
            else
                // Set the content-length as String to be able to use a long
                resp.setHeader("content-length", "" + length);

            if (contentType != null) {
                if (logger.isDebugEnabled())
                    logger.debug("contentType='" + contentType + "'");
                resp.setContentType(contentType);
            }

            if (content) {
                try {
                    resp.setBufferSize(output);
                } catch (IllegalStateException e) {
                    // Silent catch
                }
                try {
                    if (ostream != null)
                        copy(file, ostream, range, req, oldBody);
                    else
                        copy(file, writer, range, req, oldBody);
                    updateAccounting(owner, new Date(), contentLength);
                } catch (ObjectNotFoundException e) {
                    resp.sendError(HttpServletResponse.SC_NOT_FOUND);
                    return;
                } catch (InsufficientPermissionsException e) {
                    resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
                    return;
                } catch (RpcException e) {
                    resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                    return;
                }
            }
        } else {
            resp.setContentType("multipart/byteranges; boundary=" + mimeSeparation);
            if (content) {
                try {
                    resp.setBufferSize(output);
                } catch (IllegalStateException e) {
                    // Silent catch
                }
                try {
                    if (ostream != null)
                        copy(file, ostream, ranges.iterator(), contentType, req, oldBody);
                    else
                        copy(file, writer, ranges.iterator(), contentType, req, oldBody);
                    updateAccounting(owner, new Date(), contentLength);
                } catch (ObjectNotFoundException e) {
                    resp.sendError(HttpServletResponse.SC_NOT_FOUND);
                    return;
                } catch (InsufficientPermissionsException e) {
                    resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
                    return;
                } catch (RpcException e) {
                    resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                    return;
                }
            }
        }
    }
}