Example usage for javax.servlet.http HttpServletResponse SC_PRECONDITION_FAILED

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

Introduction

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

Prototype

int SC_PRECONDITION_FAILED

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

Click Source Link

Document

Status code (412) indicating that the precondition given in one or more of the request-header fields evaluated to false when it was tested on the server.

Usage

From source file:org.apache.slide.webdav.method.AbstractWebdavMethod.java

/**
 * Check if the conditions specified in the optional If headers are
 * satisfied.//from   w w w . j a va  2  s.  com
 *
 * @param request The servlet request we are processing
 * @param response The servlet response we are creating
 * @param resourceInfo File object
 * @return boolean true if the resource meets all the specified conditions,
 * and false if any of the conditions is not satisfied, in which case
 * request processing is stopped
 */
protected boolean checkIfHeaders(HttpServletRequest request, HttpServletResponse response,
        ResourceInfo resourceInfo) throws IOException {
    // the ETag without apostrophes ("), we use apostrophes as delimiters
    // to because some clients provide If header with out apostrophes
    String eTag = getETagValue(resourceInfo, true);
    long lastModified = resourceInfo.date;

    StringTokenizer commaTokenizer;

    String headerValue;

    // Checking If-Match
    headerValue = request.getHeader("If-Match");
    if (headerValue != null) {
        if (headerValue.indexOf("*") == -1) {

            commaTokenizer = new StringTokenizer(headerValue, ", \"");
            boolean matchingTagFound = false;

            while (!matchingTagFound && commaTokenizer.hasMoreTokens()) {
                matchingTagFound = commaTokenizer.nextToken().equals(eTag);
            }

            // If none of the given ETags match, 412 Precodition failed is
            // sent back
            if (!matchingTagFound) {
                response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
                return false;
            }
        } else {
            if (!resourceInfo.exists()) {
                response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
                return false;
            }
        }
    }

    // Checking If-Modified-Since
    headerValue = request.getHeader("If-Modified-Since");
    if (headerValue != null) {

        // If an If-None-Match header has been specified, if modified since
        // is ignored.
        if (request.getHeader("If-None-Match") == null) {
            Date date = parseHttpDate(headerValue);

            if ((date != null) && (lastModified <= (date.getTime() + 1000))) {
                // The entity has not been modified since the date
                // specified by the client. This is not an error case.
                response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
                return false;
            }
        }
    }

    // Checking If-None-Match
    headerValue = request.getHeader("If-None-Match");
    if (headerValue != null) {
        if (headerValue.indexOf("*") == -1) {

            commaTokenizer = new StringTokenizer(headerValue, ", \"");
            while (commaTokenizer.hasMoreTokens()) {
                if (commaTokenizer.nextToken().equals(eTag)) {
                    // For GET and HEAD, we respond with  304 Not Modified.
                    // For every other method, 412 Precondition Failed
                    if (("GET".equals(request.getMethod())) || ("HEAD".equals(request.getMethod()))) {
                        response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
                        return false;
                    } else {
                        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
                        return false;
                    }
                }
            }
        } else {
            if (resourceInfo.exists()) {
                response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
                return false;
            }
        }
    }

    // Checking If-Unmodified-Since
    headerValue = request.getHeader("If-Unmodified-Since");
    if (headerValue != null) {
        Date date = parseHttpDate(headerValue);

        if ((date != null) && (lastModified > date.getTime())) {
            // The entity has not been modified since the date
            // specified by the client. This is not an error case.
            response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
            return false;
        }
    }
    return true;
}

From source file:de.innovationgate.wgpublisher.WGPDispatcher.java

public void doGet(javax.servlet.http.HttpServletRequest request,
        javax.servlet.http.HttpServletResponse response)
        throws javax.servlet.ServletException, java.io.IOException {

    if (!isServePages()) {
        response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE,
                "Website is currently updating configuration. Please try again later.");
        return;/*w  w  w.j  ava2s .  c  o  m*/
    }

    Date startDate = new Date();

    if (this._contextPath == null) {
        this._contextPath = request.getContextPath();
        this._listenPort = request.getServerPort();
    }

    WGARequestInformation reqInfo = (WGARequestInformation) request
            .getAttribute(WGARequestInformation.REQUEST_ATTRIBUTENAME);

    try {

        // Parse request
        WGPRequestPath path = WGPRequestPath.parseRequest(this, request, response);
        request.setAttribute(WGACore.ATTRIB_REQUESTPATH, path);

        // If database login failed or access was denied exit immediately
        if (!path.isProceedRequest()) {
            return;
        }

        // Set access logging for this request
        if (path.getDatabase() != null) {
            String accessLoggingEnabled = (String) path.getDatabase()
                    .getAttribute(WGACore.DBATTRIB_ENABLE_ACCESSLOGGING);
            if (accessLoggingEnabled != null) {
                if (reqInfo != null) {
                    reqInfo.setLoggingEnabled(Boolean.parseBoolean(accessLoggingEnabled));
                }
            }
        }

        int iPathType = path.getPathType();

        // Treatment of special URL types
        String dbKey = path.getDatabaseKey();
        if (iPathType == WGPRequestPath.TYPE_INVALID) {
            throw new HttpErrorException(404, "Invalid path: " + path.getBasePath(), dbKey);
        }
        if (iPathType == WGPRequestPath.TYPE_INVALID_DB) {
            throw new HttpErrorException(404, "Specified application '" + dbKey + "' is unknown", null);
        }

        if (iPathType == WGPRequestPath.TYPE_UNKNOWN_CONTENT) {
            sendNoContentNotification(path, request, response, path.getDatabase());
            return;
        }

        if (iPathType == WGPRequestPath.TYPE_GOTO_HOMEPAGE) {
            iPathType = determineHomepage(request, path, iPathType);
        }

        if (iPathType == WGPRequestPath.TYPE_UNAVAILABLE_DB) {
            throw new HttpErrorException(HttpServletResponse.SC_SERVICE_UNAVAILABLE,
                    "The website is currently unavailable", path.getDatabaseKey());
        }

        if (iPathType == WGPRequestPath.TYPE_UNDEFINED_HOMEPAGE) {
            throw new HttpErrorException(
                    HttpServletResponse.SC_NOT_FOUND, "No home page was defined for app '"
                            + path.getDatabaseKey() + "'. Please specify an explicit content path.",
                    path.getDatabaseKey());
        }

        if (iPathType == WGPRequestPath.TYPE_TMLDEBUG) {
            _tmlDebugger.performDebugMode(request, response, request.getSession());
            return;
        }

        if (iPathType == WGPRequestPath.TYPE_JOBLOG) {
            sendJobLog(request, response, request.getSession());
            return;
        }

        if (iPathType == WGPRequestPath.TYPE_LOGOUT) {
            WGDatabase db = (WGDatabase) _core.getContentdbs().get(dbKey);
            String domain = (String) db.getAttribute(WGACore.DBATTRIB_DOMAIN);
            _core.logout(domain, request.getSession(), request, response, true);
            removeSessionCookie(response, request.getSession(), db);

            iPathType = WGPRequestPath.TYPE_REDIRECT;
        }

        if (iPathType == WGPRequestPath.TYPE_FAVICON) {
            String faviconPath = determineFavicon(request);
            if (faviconPath != null) {
                iPathType = WGPRequestPath.TYPE_REDIRECT;
                path.setResourcePath(faviconPath);
            } else {
                response.sendError(HttpServletResponse.SC_NOT_FOUND, "Favicon not defined");
                return;
            }
        }

        if (iPathType == WGPRequestPath.TYPE_TMLFORM) {
            dispatchTmlFormRequest(path, request, response);
            return;
        }

        // Treatment of base URL Types
        if (iPathType == WGPRequestPath.TYPE_REDIRECT) {
            String url = path.getResourcePath();
            if (path.appendQueryString() == true && request.getQueryString() != null
                    && !request.getQueryString().equals("")) {
                if (url.indexOf("?") != -1) {
                    url += "&" + request.getQueryString();
                } else {
                    url += "?" + request.getQueryString();
                }
            }

            if (path.isPermanentRedirect()) {
                sendPermanentRedirect(response, url);
            } else {
                sendRedirect(request, response, url);
            }
        } else if (iPathType != WGPRequestPath.TYPE_RESOURCE && iPathType != WGPRequestPath.TYPE_STATICTML
                && !_core.getContentdbs().containsKey(path.getDatabaseKey())) {
            throw new HttpErrorException(404, "Database '" + dbKey + "' is unknown", null);
        } else {

            String requestMethod = request.getMethod().toLowerCase();
            switch (iPathType) {
            case (WGPRequestPath.TYPE_TML):
            case (WGPRequestPath.TYPE_TITLE_PATH):

                // Fetch the redirect cookie
                Cookie lastRedirectCookie = null;
                Cookie[] cookies = request.getCookies();
                if (cookies != null) {
                    for (Cookie cookie : cookies) {
                        if (cookie.getName().equals(COOKIE_LASTREDIRECT)) {
                            lastRedirectCookie = cookie;
                            break;
                        }
                    }
                }

                // If path is not complete redirect it to the complete path, if possible. Set redirect cookie to prevent endless redirections
                if (!path.isCompletePath()) {
                    String redirectPath = path.expandToCompletePath(request);
                    if (isRedirectable(request, redirectPath, lastRedirectCookie)) {
                        lastRedirectCookie = new WGCookie(COOKIE_LASTREDIRECT,
                                Hex.encodeHexString(redirectPath.getBytes("UTF-8")));
                        lastRedirectCookie.setMaxAge(-1);
                        lastRedirectCookie.setPath("/");
                        ((WGCookie) lastRedirectCookie).addCookieHeader(response);
                        sendRedirect(request, response, redirectPath);
                        break;
                    }
                }

                // Delete redirect cookie when exists on normal dispatching
                if (lastRedirectCookie != null) {
                    lastRedirectCookie = new WGCookie(COOKIE_LASTREDIRECT, "");
                    lastRedirectCookie.setMaxAge(0);
                    lastRedirectCookie.setPath("/");
                    ((WGCookie) lastRedirectCookie).addCookieHeader(response);
                }

                // Dispatch
                dispatchTmlRequest(path, request, response, startDate);
                break;

            case (WGPRequestPath.TYPE_FILE):
                dispatchFileRequest(path, request, response);
                break;

            case (WGPRequestPath.TYPE_CSS):
            case (WGPRequestPath.TYPE_JS):
                dispatchCssjsRequest(path, request, response);
                break;

            case (WGPRequestPath.TYPE_RESOURCE):
                dispatchResourceRequest(path, request, response);
                break;

            case (WGPRequestPath.TYPE_STATICTML):
                dispatchStaticTmlRequest(path, request, response);
                break;

            default:
                throw new HttpErrorException(500, "Invalid url format", dbKey);
            }
        }

        // moved from finally block to ensure errorpage can be displayed
        commitResponse(response);
    } catch (ClientAccessException exc) {
        response.sendError(403, exc.getMessage());
    } catch (AjaxFailureException exc) {
        handleAjaxFailure(exc, request, response);
    } catch (HttpErrorException exc) {
        request.setAttribute(WGACore.ATTRIB_EXCEPTION, exc);
        ProblemOccasion occ = new PathDispatchingOccasion(request, exc.getDbHint());
        _core.getProblemRegistry().addProblem(
                Problem.create(occ, "dispatching.http404#" + request.getRequestURL(), ProblemSeverity.LOW));
        if (!response.isCommitted()) {
            // throw exception to display errorpage - with senderror() the
            // applicationserver use the buildin errorpage
            if (exc.getCode() == HttpServletResponse.SC_NOT_FOUND
                    || exc.getCode() == HttpServletResponse.SC_FORBIDDEN
                    || exc.getCode() == HttpServletResponse.SC_PRECONDITION_FAILED) {
                response.sendError(exc.getCode(), exc.getMessage());
            } else {
                _log.error("Exception in processing request from " + request.getRemoteAddr() + " to URL "
                        + String.valueOf(request.getRequestURL()));
                throw new ServletException(exc);
            }
        }
    } catch (SocketException exc) {
        _log.warn("Socket Exception: " + exc.getMessage());
    } catch (Exception exc) {
        _log.error("Exception in processing of request URL " + String.valueOf(request.getRequestURL()), exc);
        request.setAttribute(WGACore.ATTRIB_EXCEPTION, exc);
        throw new ServletException(exc);
    } catch (Error err) {
        _log.error("Error in processing of request URL " + String.valueOf(request.getRequestURL()), err);
        request.setAttribute(WGACore.ATTRIB_EXCEPTION, err);
        throw new ServletException(err);
    } finally {
        if (reqInfo != null) {
            reqInfo.setCommited(true);
        }
    }
}

From source file:jp.aegif.alfresco.online_webdav.WebDAVMethod.java

/**
 * Checks If header conditions. Throws WebDAVServerException with 412(Precondition failed)
 * if none of the conditions success./*from w ww .j ava  2s.c om*/
 * 
 * @param nodeLockToken          - node's lock token
 * @param nodeETag               - node's ETag
 * @throws WebDAVServerException if conditions fail
 */
private void checkConditions(String nodeLockToken, String nodeETag) throws WebDAVServerException {
    // Checks If header conditions.
    // Each condition can contain check of ETag and check of Lock token.

    if (m_conditions == null) {
        // No conditions were provided with "If" request header, so check successful
        return;
    }

    // Check the list of "If" header's conditions.
    // If any condition conforms then check is successful
    for (Condition condition : m_conditions) {
        // Flag for ETag conditions
        boolean fMatchETag = true;
        // Flag for Lock token conditions
        boolean fMatchLockToken = true;

        // Check ETags that should match
        if (condition.getETagsMatch() != null) {
            fMatchETag = condition.getETagsMatch().contains(nodeETag) ? true : false;
        }
        // Check ETags that shouldn't match
        if (condition.getETagsNotMatch() != null) {
            fMatchETag = condition.getETagsNotMatch().contains(nodeETag) ? false : true;
        }
        // Check lock tokens that should match
        if (condition.getLockTokensMatch() != null) {
            fMatchLockToken = nodeLockToken == null || condition.getLockTokensMatch().contains(nodeLockToken);
        }
        // Check lock tokens that shouldn't match
        if (condition.getLockTokensNotMatch() != null) {
            fMatchLockToken = nodeLockToken == null
                    || !condition.getLockTokensNotMatch().contains(nodeLockToken);
        }

        if (fMatchETag && fMatchLockToken) {
            // Condition conforms
            return;
        }
    }

    // None of the conditions successful
    throw new WebDAVServerException(HttpServletResponse.SC_PRECONDITION_FAILED);
}

From source file:org.opencastproject.adminui.endpoint.EmailEndpoint.java

@POST
@Path("preview/{templateId}")
@Produces(MediaType.APPLICATION_JSON)/*  www.j  a  v  a2s .co m*/
@RestQuery(name = "previewmail", description = "Render a mail with the current email configuration for reviewing it", returnDescription = "The renderend message as JSON", pathParameters = {
        @RestParameter(name = "templateId", description = "The template id", isRequired = true, type = RestParameter.Type.INTEGER) }, restParameters = {
                @RestParameter(name = "eventIds", description = "A comma separated list of event ids", isRequired = true, type = RestParameter.Type.TEXT),
                @RestParameter(name = "personIds", description = "A comma separated list of person ids", isRequired = true, type = RestParameter.Type.TEXT),
                @RestParameter(name = "signature", description = "Whether to include the signature", isRequired = false, type = RestParameter.Type.BOOLEAN),
                @RestParameter(name = "body", description = "The optional message body", isRequired = false, type = RestParameter.Type.TEXT) }, reponses = {
                        @RestResponse(description = "No recording or person ids have been set!", responseCode = HttpServletResponse.SC_BAD_REQUEST),
                        @RestResponse(description = "No message signature is configured or no PM user to perform this action!", responseCode = HttpServletResponse.SC_PRECONDITION_FAILED),
                        @RestResponse(description = "Email has been sent", responseCode = HttpServletResponse.SC_NO_CONTENT) })
public Response previewMail(@PathParam("templateId") long template,
        @FormParam("eventIds") String eventIdsString, @FormParam("personIds") String personIdsString,
        @FormParam("signature") @DefaultValue("false") boolean signature, @FormParam("subject") String subject,
        @FormParam("body") String body) {
    if (participationDatabase == null)
        return Response.status(Status.SERVICE_UNAVAILABLE).build();

    final Monadics.ListMonadic<String> eventIds = splitCommaSeparatedParam(option(eventIdsString));
    final Monadics.ListMonadic<Long> personIds = splitCommaSeparatedParam(option(personIdsString)).map(toLong);
    if (eventIds.value().isEmpty() || personIds.value().isEmpty())
        return badRequest();

    Person creator;
    try {
        creator = participationDatabase.getPerson(securityService.getUser().getEmail());
    } catch (Exception e) {
        logger.error("No valid participation managment user found for preview this mail! {}",
                ExceptionUtils.getStackTrace(e));
        return Response.status(Status.PRECONDITION_FAILED).build();
    }

    try {
        List<Recording> recordings = ParticipationUtils.getRecordingsByEventId(schedulerService,
                participationDatabase, eventIds.value());
        List<Person> recipients = getPersonById(personIds.value());

        MessageTemplate messageTemplate = mailService.getMessageTemplate(template);
        if (StringUtils.isNotBlank(body))
            messageTemplate.setBody(body);

        MessageSignature messageSignature = null;

        if (signature) {
            try {
                messageSignature = mailService.getCurrentUsersSignature();
            } catch (NotFoundException e) {
                return Response.status(Status.PRECONDITION_FAILED).build();
            }
            if (messageSignature == null)
                return Response.status(Status.PRECONDITION_FAILED).build();
        } else {
            // Create an empty message signature.
            messageSignature = new MessageSignature(0L, creator.getName(), securityService.getUser(),
                    new EmailAddress(creator.getEmail(), creator.getName()), Option.<EmailAddress>none(), "",
                    new Date(), (new ArrayList<Comment>()));
        }
        messageTemplate
                .setBody(messageTemplate.getBody().concat("\r\n").concat(messageSignature.getSignature()));
        Message message = new Message(creator, messageTemplate, messageSignature, signature);

        List<Val> renderArr = new ArrayList<Jsons.Val>();
        for (Person recipient : recipients) {
            renderArr.add(Jsons.v(emailSender.renderInvitationBody(message, recordings, recipient)));
        }
        return Response.ok(Jsons.arr(renderArr).toJson()).build();
    } catch (Exception e) {
        logger.error("Could not create a preview email: {}", ExceptionUtils.getStackTrace(e));
        throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
    }
}

From source file:org.opencastproject.adminui.endpoint.EmailEndpoint.java

@POST
@Path("send/{templateId}")
@Produces(MediaType.APPLICATION_JSON)//  www. j a v  a2  s .  c om
@RestQuery(name = "sendmail", description = "Render an email with the current email configuration for reviewing it", returnDescription = "The renderend message as JSON", pathParameters = {
        @RestParameter(name = "templateId", description = "The template id", isRequired = true, type = RestParameter.Type.INTEGER) }, restParameters = {
                @RestParameter(name = "eventIds", description = "A comma separated list of event ids", isRequired = true, type = RestParameter.Type.TEXT),
                @RestParameter(name = "personIds", description = "A comma separated list of person ids", isRequired = true, type = RestParameter.Type.TEXT),
                @RestParameter(name = "signature", description = "Whether to include the signature", isRequired = false, type = RestParameter.Type.BOOLEAN),
                @RestParameter(name = "subject", description = "The optional message subject", isRequired = false, type = RestParameter.Type.STRING),
                @RestParameter(name = "body", description = "The optional message body", isRequired = false, type = RestParameter.Type.TEXT),
                @RestParameter(name = "store", description = "Whether to store the message to the audit trail", isRequired = false, type = RestParameter.Type.BOOLEAN) }, reponses = {
                        @RestResponse(description = "No recording or person ids have been set!", responseCode = HttpServletResponse.SC_BAD_REQUEST),
                        @RestResponse(description = "No message signature is configured or no PM user to perform this action!", responseCode = HttpServletResponse.SC_PRECONDITION_FAILED),
                        @RestResponse(description = "Email has been sent", responseCode = HttpServletResponse.SC_NO_CONTENT) })
public Response sendMail(@PathParam("templateId") long template, @FormParam("eventIds") String eventIdsString,
        @FormParam("personIds") String personIdsString,
        @FormParam("signature") @DefaultValue("false") boolean signature, @FormParam("subject") String subject,
        @FormParam("body") String body, @FormParam("store") @DefaultValue("false") boolean store) {
    if (participationDatabase == null)
        return Response.status(Status.SERVICE_UNAVAILABLE).build();

    final Monadics.ListMonadic<String> eventIds = splitCommaSeparatedParam(option(eventIdsString));
    final Monadics.ListMonadic<Long> personIds = splitCommaSeparatedParam(option(personIdsString)).map(toLong);
    if (eventIds.value().isEmpty() || personIds.value().isEmpty())
        return badRequest();

    Person creator;
    try {
        creator = participationDatabase.getPerson(securityService.getUser().getEmail());
    } catch (Exception e) {
        logger.error("No valid participation management user found for sending this mail!");
        return Response.status(Status.PRECONDITION_FAILED).build();
    }

    try {
        List<Recording> recordings = ParticipationUtils.getRecordingsByEventId(schedulerService,
                participationDatabase, eventIds.value());
        List<Person> recipients = getPersonById(personIds.value());

        MessageTemplate messageTemplate = mailService.getMessageTemplate(template);
        if (StringUtils.isNotBlank(subject))
            messageTemplate.setSubject(subject);
        if (StringUtils.isNotBlank(body))
            messageTemplate.setBody(body);

        MessageSignature messageSignature = mailService.getCurrentUsersSignature();
        if (messageSignature == null)
            return Response.status(Status.PRECONDITION_FAILED).build();

        Message message = new Message(creator, messageTemplate, messageSignature, signature);
        emailSender.sendMessagesForRecordings(recordings, recipients, message, store);

        for (String eventId : eventIds.value()) {
            try {
                schedulerService.updateReviewStatus(eventId, ReviewStatus.UNCONFIRMED);
            } catch (Exception e) {
                logger.error("Unable to update review status of event {}", eventId);
                continue;
            }
        }
        return Response.noContent().build();
    } catch (Exception e) {
        logger.error("Could not update the email configuration: {}", ExceptionUtils.getStackTrace(e));
        throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
    }
}

From source file:org.apache.catalina.servlets.DefaultServlet.java

/**
 * Check if the if-match condition is satisfied.
 *
 * @param request      The servlet request we are processing
 * @param response     The servlet response we are creating
 * @param resourceInfo File object/*  ww  w.j  a v a2  s .  c  o  m*/
 * @return boolean true if the resource meets the specified condition,
 *         and false if the condition is not satisfied, in which case request
 *         processing is stopped
 * @throws IOException Description of the Exception
 */
private boolean checkIfMatch(HttpServletRequest request, HttpServletResponse response,
        ResourceInfo resourceInfo) throws IOException {

    String eTag = getETag(resourceInfo);
    String headerValue = request.getHeader("If-Match");
    if (headerValue != null) {
        if (headerValue.indexOf('*') == -1) {

            StringTokenizer commaTokenizer = new StringTokenizer(headerValue, ",");
            boolean conditionSatisfied = false;

            while (!conditionSatisfied && commaTokenizer.hasMoreTokens()) {
                String currentToken = commaTokenizer.nextToken();
                if (currentToken.trim().equals(eTag)) {
                    conditionSatisfied = true;
                }
            }

            // If none of the given ETags match, 412 Precodition failed is
            // sent back
            if (!conditionSatisfied) {
                response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
                return false;
            }
        }
    }
    return true;
}

From source file:org.apache.catalina.servlets.DefaultServlet.java

/**
 * Check if the if-none-match condition is satisfied.
 *
 * @param request      The servlet request we are processing
 * @param response     The servlet response we are creating
 * @param resourceInfo File object/* www  .  j  a v a 2  s  .com*/
 * @return boolean true if the resource meets the specified condition,
 *         and false if the condition is not satisfied, in which case request
 *         processing is stopped
 * @throws IOException Description of the Exception
 */
private boolean checkIfNoneMatch(HttpServletRequest request, HttpServletResponse response,
        ResourceInfo resourceInfo) throws IOException {

    String eTag = getETag(resourceInfo);
    String headerValue = request.getHeader("If-None-Match");
    if (headerValue != null) {

        boolean conditionSatisfied = false;

        if (!headerValue.equals("*")) {

            StringTokenizer commaTokenizer = new StringTokenizer(headerValue, ",");

            while (!conditionSatisfied && commaTokenizer.hasMoreTokens()) {
                String currentToken = commaTokenizer.nextToken();
                if (currentToken.trim().equals(eTag)) {
                    conditionSatisfied = true;
                }
            }

        } else {
            conditionSatisfied = true;
        }

        if (conditionSatisfied) {

            // For GET and HEAD, we should respond with
            // 304 Not Modified.
            // For every other method, 412 Precondition Failed is sent
            // back.
            if (("GET".equals(request.getMethod())) || ("HEAD".equals(request.getMethod()))) {
                response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                return false;
            } else {
                response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
                return false;
            }
        }
    }
    return true;
}

From source file:org.apache.catalina.servlets.DefaultServlet.java

/**
 * Check if the if-unmodified-since condition is satisfied.
 *
 * @param request      The servlet request we are processing
 * @param response     The servlet response we are creating
 * @param resourceInfo File object/*from   w w  w  .  ja va  2  s  . c om*/
 * @return boolean true if the resource meets the specified condition,
 *         and false if the condition is not satisfied, in which case request
 *         processing is stopped
 * @throws IOException Description of the Exception
 */
private boolean checkIfUnmodifiedSince(HttpServletRequest request, HttpServletResponse response,
        ResourceInfo resourceInfo) throws IOException {
    try {
        long lastModified = resourceInfo.date;
        long headerValue = request.getDateHeader("If-Unmodified-Since");
        if (headerValue != -1) {
            if (lastModified > (headerValue + 1000)) {
                // The entity has not been modified since the date
                // specified by the client. This is not an error case.
                response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
                return false;
            }
        }
    } catch (IllegalArgumentException illegalArgument) {
        return true;
    }
    return true;
}

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

/**
 * Check if the if-match condition is satisfied.
 *
 * @param request The servlet request we are processing
 * @param response The servlet response we are creating
 * @param file the file object//from   w  ww . j a va  2 s  .  c  o  m
 * @param oldBody the old version of the file, if requested
 * @return boolean true if the resource meets the specified condition, and
 *         false if the condition is not satisfied, in which case request
 *         processing is stopped
 * @throws IOException
 */
private boolean checkIfMatch(HttpServletRequest request, HttpServletResponse response, FileHeader file,
        FileBody oldBody) throws IOException {
    String eTag = getETag(file, oldBody);
    String headerValue = request.getHeader("If-Match");
    if (headerValue != null)
        if (headerValue.indexOf('*') == -1) {
            StringTokenizer commaTokenizer = new StringTokenizer(headerValue, ",");
            boolean conditionSatisfied = false;
            while (!conditionSatisfied && commaTokenizer.hasMoreTokens()) {
                String currentToken = commaTokenizer.nextToken();
                if (currentToken.trim().equals(eTag))
                    conditionSatisfied = true;
            }
            // If none of the given ETags match, 412 Precodition failed is
            // sent back.
            if (!conditionSatisfied) {
                response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
                return false;
            }
        }
    return true;
}