Example usage for javax.servlet.http HttpServletResponse SC_NOT_MODIFIED

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

Introduction

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

Prototype

int SC_NOT_MODIFIED

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

Click Source Link

Document

Status code (304) indicating that a conditional GET operation found that the resource was available and not modified.

Usage

From source file:org.localmatters.lesscss4j.servlet.LessCssServletTest.java

public void testCachedResourceNotModified() throws IOException, ServletException {
    testEmptyCacheValidResource();//from  w  w w  .ja v a  2s.  co  m

    EasyMock.reset(_request);
    EasyMock.reset(_response);
    EasyMock.reset(_servletContext);

    EasyMock.expect(_request.getPathInfo()).andReturn(_path);
    EasyMock.expect(_request.getMethod()).andReturn("GET");
    EasyMock.expect(_request.getDateHeader(LessCssServlet.IF_MOD_SINCE)).andReturn(_systemMillis + 1000);
    EasyMock.expect(_request.getHeader(LessCssServlet.IF_NONE_MATCH)).andReturn(null);
    EasyMock.expect(_request.getParameter(LessCssServlet.CLEAR_CACHE)).andReturn(null);

    _response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);

    doReplay();

    _servlet.init(_servletConfig);
    _servlet.service(_request, _response);

    doVerify();
}

From source file:org.opengeoportal.proxy.controllers.DynamicOgcController.java

private boolean doResponseRedirectOrNotModifiedLogic(HttpServletRequest servletRequest,
        HttpServletResponse servletResponse, HttpResponse proxyResponse, int statusCode)
        throws ServletException, IOException {
    // Check if the proxy response is a redirect
    // The following code is adapted from org.tigris.noodle.filters.CheckForRedirect
    if (statusCode >= HttpServletResponse.SC_MULTIPLE_CHOICES /* 300 */
            && statusCode < HttpServletResponse.SC_NOT_MODIFIED /* 304 */) {
        Header locationHeader = proxyResponse.getLastHeader(HttpHeaders.LOCATION);
        if (locationHeader == null) {
            throw new ServletException("Received status code: " + statusCode + " but no " + HttpHeaders.LOCATION
                    + " header was found in the response");
        }//w w  w .  j a v a 2s . com
        // Modify the redirect to go to this proxy servlet rather that the proxied host
        String locStr = rewriteUrlFromResponse(servletRequest, locationHeader.getValue());

        servletResponse.sendRedirect(locStr);
        return true;
    }
    // 304 needs special handling. See:
    // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304
    // We get a 304 whenever passed an 'If-Modified-Since'
    // header and the data on disk has not changed; server
    // responds w/ a 304 saying I'm not going to send the
    // body because the file has not changed.
    if (statusCode == HttpServletResponse.SC_NOT_MODIFIED) {
        servletResponse.setIntHeader(HttpHeaders.CONTENT_LENGTH, 0);
        servletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return true;
    }
    return false;
}

From source file:edu.ucsd.library.dams.api.FileStoreServlet.java

/**
 * Process the actual request./* w  w  w  . jav  a2s  . c o m*/
 * @param request The request to be processed.
 * @param response The response to be created.
 * @param content Whether the request body should be written (GET) or not
 *  (HEAD).
 * @throws IOException If something fails at I/O level.
 */
private void processRequest(HttpServletRequest request, HttpServletResponse response, boolean content)
        throws IOException {
    // Validate the requested file -------------------------------------

    // Get requested file by path info.
    /* start ucsd changes */

    // get object and file ids from path
    String objid = null;
    String cmpid = null;
    String fileid = null;
    try {
        // /bb1234567x/1.tif
        // /bb1234567x/1/2.tif
        String[] path = request.getPathInfo().split("/");
        if (path.length == 3) {
            objid = path[1];
            fileid = path[2];
        } else if (path.length == 4) {
            objid = path[1];
            cmpid = path[2];
            fileid = path[3];
        }
    } catch (Exception e) {
        String errorMessage = "Error parsing request pathInfo: " + request.getPathInfo();
        log.error(errorMessage, e);
        response.setContentType("text/plain");
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, errorMessage);
        return;
    }

    // make sure required parameters are populated
    if (objid == null || objid.trim().length() == 0 || fileid == null || fileid.trim().length() == 0) {
        response.setContentType("text/plain");
        response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                "Subject and file must be specified in the request URI");
        return;
    }
    String fullFilename = objid + (StringUtils.isNotBlank(cmpid) ? "-" + cmpid : "") + "-" + fileid;

    // first load the FileStore (no point if this doesn't work)
    FileStore fs = null;
    long fsTime = 0;
    try {
        long start = System.currentTimeMillis();
        fs = FileStoreUtil.getFileStore(props, fsDefault);
        fsTime = System.currentTimeMillis() - start;
    } catch (Exception ex) {
        response.setContentType("text/plain");
        response.sendError(response.SC_INTERNAL_SERVER_ERROR, "Error initializing FileStore");
        ex.printStackTrace();
        return;
    }

    // check authorization attribute
    String restricted = null;
    String authorized = (String) request.getAttribute("edu.ucsd.library.dams.api.DAMSAPIServlet.authorized");
    if (authorized == null || !authorized.equals("true")) {
        log.warn("Illegal Access from IP " + request.getRemoteAddr() + " for file " + fullFilename);
        response.setContentType("text/plain");
        response.sendError(HttpServletResponse.SC_FORBIDDEN, "Access without authorization.");
        return;
    } else {
        log.info("DAMS Access authorized for IP " + request.getRemoteAddr() + " for file " + fullFilename);
        restricted = (String) request.getAttribute("pas.restricted");
        //Disable browser caching for restricted objects.
        if (restricted != null && restricted.equals("1")) {
            String browser = request.getHeader("User-Agent");
            if (browser != null && browser.indexOf("MSIE") != -1) {
                response.addHeader("Cache-Control", "post-check=0, pre-check=0");
            } else {
                response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
            }
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Expires", "0");
        }
    }
    /* end ucsd changes */

    // load file metadata
    Map<String, String> meta = null;
    long metaTime = 0;
    try {
        long start = System.currentTimeMillis();
        meta = fs.meta(objid, cmpid, fileid);
        metaTime = System.currentTimeMillis() - start;
    } catch (Exception ex) {
        log.error("File " + fullFilename + " doesn't exist.", ex);
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // Prepare some variables. The ETag is an unique identifier of the file
    String length = meta.get("Content-Length");
    String lastModStr = meta.get("Last-Modified");
    long lastModified = 0L;
    try {
        lastModified = df.parse(lastModStr).getTime();
    } catch (Exception ex) {
        // error parsing lastmod date... set to now
        lastModified = System.currentTimeMillis();
    }
    String eTag = meta.get("ETag");
    if (eTag == null) {
        eTag = fullFilename + "_" + length + "_" + lastModified;
    }

    // Validate request headers for caching -----------------------------

    // If-None-Match header should contain "*" or ETag. If so, return 304.
    String ifNoneMatch = request.getHeader("If-None-Match");
    if (ifNoneMatch != null && matches(ifNoneMatch, eTag)) {
        response.setHeader("ETag", eTag); // Required in 304.
        response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }

    // If-Modified-Since header should be greater than LastModified. If so,
    // then return 304.
    // This header is ignored if any If-None-Match header is specified.
    long ifModifiedSince = request.getDateHeader("If-Modified-Since");
    if (ifNoneMatch == null && ifModifiedSince != -1 && ifModifiedSince + 1000 > lastModified) {
        response.setHeader("ETag", eTag); // Required in 304.
        response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }

    // Validate request headers for resume ------------------------------

    // If-Match header should contain "*" or ETag. If not, then return 412.
    String ifMatch = request.getHeader("If-Match");
    if (ifMatch != null && !matches(ifMatch, eTag)) {
        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        return;
    }

    // If-Unmodified-Since header should be greater than LastModified.
    // If not, then return 412.
    long ifUnmodifiedSince = request.getDateHeader("If-Unmodified-Since");
    if (ifUnmodifiedSince != -1 && ifUnmodifiedSince + 1000 <= lastModified) {
        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        return;
    }

    // Prepare and initialize response ----------------------------------

    // Get content type by file name and set default GZIP support and
    // content disposition.
    String contentType = getServletContext().getMimeType(fullFilename);
    boolean acceptsGzip = false;
    String disposition = "inline";

    // If content type is unknown, then set the default value.  For all
    // content types, see: http://www.w3schools.com/media/media_mimeref.asp
    // To add new content types, add new mime-mapping entry in web.xml.
    if (contentType == null) {
        contentType = "application/octet-stream";
    }

    //If UCSD download
    boolean download = request.getParameter("download") != null;
    if (download) {
        disposition = "attachment";
        contentType = "application/x-download";
    }
    // Else if content type is text, then determine whether GZIP content
    // encoding is supported by the browser and expand content type with
    // the one and right character encoding.
    else if (contentType.startsWith("text")) {
        //String acceptEncoding = request.getHeader("Accept-Encoding");
        //acceptsGzip = acceptEncoding != null && accepts(acceptEncoding, "gzip");
        contentType += ";charset=UTF-8";
    }

    // Else, expect for images, determine content disposition. If content
    // type is supported by the browser, then set to inline, else
    // attachment which will pop a 'save as' dialogue.
    else if (!contentType.startsWith("image")) {
        String accept = request.getHeader("Accept");
        disposition = accept != null && accepts(accept, contentType) ? "inline" : "attachment";
    }

    String sFileName = request.getParameter("name");
    if (sFileName == null || (sFileName = sFileName.trim()).length() == 0)
        sFileName = fullFilename;

    // Initialize response.
    response.reset();
    response.setBufferSize(DEFAULT_BUFFER_SIZE);
    response.setHeader("Content-Disposition", disposition + ";filename=\"" + sFileName + "\"");
    response.setHeader("ETag", eTag);
    response.setDateHeader("Last-Modified", lastModified);
    /* begin ucsd changes */
    if (restricted == null || !restricted.equals("1")) {
        response.setDateHeader("Expires", System.currentTimeMillis() + DEFAULT_EXPIRE_TIME);
    }
    /* end ucsd changes */

    // Send requested file to client ------------------------------------

    // Prepare streams.
    InputStream input = null;
    OutputStream output = null;
    long fileTime = 0;
    if (content) {
        try {
            long start = System.currentTimeMillis();
            // Open streams.
            input = fs.getInputStream(objid, cmpid, fileid);
            output = response.getOutputStream();
            response.setContentType(contentType);
            if (acceptsGzip) {
                // The browser accepts GZIP, so GZIP the content.
                response.setHeader("Content-Encoding", "gzip");
                output = new GZIPOutputStream(output, DEFAULT_BUFFER_SIZE);
            } else {
                // Content length is not directly predictable in case of
                // GZIP. So only add it if there is no means of GZIP, else
                // browser will hang.
                response.setHeader("Content-Length", length);
            }

            // Copy full range.
            /* begin ucsd changes */
            FileStoreUtil.copy(input, output);
            fileTime = System.currentTimeMillis() - start;
            /* begin ucsd changes */
        } catch (Exception ex) {
            log.error("Error reading " + fullFilename, ex);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } finally {
            /* begin ucsd changes */
            log.info("Time in miliseconds to retrival file " + fullFilename + "(" + length + " bytes)"
                    + ": Total " + (fsTime + metaTime + fileTime) + "[FileStore initiation: " + fsTime
                    + "; Metadata query: " + metaTime + "; File download: " + fileTime + "]");
            /* begin ucsd changes */
            // Gently close streams.
            close(output);
            close(input);
        }
    }
}

From source file:fr.xebia.servlet.filter.ExpiresFilterTest.java

@Test
public void testExcludedResponseStatusCode() throws Exception {
    HttpServlet servlet = new HttpServlet() {
        private static final long serialVersionUID = 1L;

        @Override/* w w  w.  ja  v a 2  s.  com*/
        protected void service(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
            response.addHeader("ETag", "W/\"1934-1269208821000\"");
            response.addDateHeader("Date", System.currentTimeMillis());
        }
    };

    validate(servlet, null, HttpServletResponse.SC_NOT_MODIFIED);
}

From source file:nl.opengeogroep.filesetsync.server.stripes.FilesetListActionBean.java

public Resolution list() throws Exception {

    final ServerFileset theFileset = getFileset();

    MutableInt noRegexpMatches = new MutableInt();

    long ifModifiedSince = getContext().getRequest().getDateHeader("If-Modified-Since");

    if (ifModifiedSince == -1) {
        log.info("listing " + getLocalSubPath());
        // Stream file records directly to output without buffering all
        // records in memory
        // return new FilesetListingResolution(ServerFileset.getFileRecordsInDir(getLocalSubPath());
        return new FilesetListingResolution(theFileset,
                FileRecord.getFileRecordsInDir(getLocalSubPath(), regexp, noRegexpMatches));
    } else {/* w  ww.  j  a  v  a 2  s .  c  om*/
        // A conditional HTTP request with If-Modified-Since is checked
        // against the latest last modified date of all the files and
        // directories in the fileset.

        // Cache file records in case client cache is outdated and all
        // records must be returned including the hash (not calculated yet)

        // Note: if a file or directory is deleted, the modification time
        // of the directory containing the file or directory is updated so
        // deletions do trigger a cache invalidation. The root directory is
        // included in the file list for this reason.

        long lastModified = -1;
        Collection<FileRecord> fileRecords = new ArrayList();

        String cacheDir = new File(FileHashCache.getCacheDir(theFileset.getName())).getCanonicalPath();

        log.info("traverse " + getLocalSubPath());

        long startTime = System.currentTimeMillis();
        for (FileRecord fr : FileRecord.getFileRecordsInDir(getLocalSubPath(), regexp, noRegexpMatches)) {
            if (fr.getFile().getCanonicalPath().startsWith(cacheDir)) {
                continue;
            }
            fileRecords.add(fr);
            lastModified = Math.max(lastModified, fr.getLastModified());
        }
        log.info(String.format("traversed %d files and dirs%s", fileRecords.size(),
                regexp == null ? "" : ", filtered " + noRegexpMatches + " by regexp"));
        String time = DurationFormatUtils.formatDurationWords(System.currentTimeMillis() - startTime, true,
                false);
        if (ifModifiedSince >= lastModified) {
            log.info("not modified since " + dateToString(new Date(lastModified)) + ", took " + time);
            return new ErrorResolution(HttpServletResponse.SC_NOT_MODIFIED);
        } else {
            log.info(
                    "last modified date " + dateToString(new Date(lastModified)) + " later than client date of "
                            + dateToString(new Date(ifModifiedSince)) + ", returning list (time " + time + ")");
            // Avoid walking dirs twice, only calculate hashes
            return new FilesetListingResolution(theFileset, fileRecords);
        }
    }
}

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

/**
 * Checks the If header conditions/* ww  w  .j  av a2s .c o m*/
 * 
 * @param nodeInfo the node to check
 * @throws WebDAVServerException if a pre-condition is not met
 */
private void checkPreConditions(FileInfo nodeInfo) throws WebDAVServerException {
    // Make an etag for the node

    String strETag = getDAVHelper().makeQuotedETag(nodeInfo);
    TypeConverter typeConv = DefaultTypeConverter.INSTANCE;

    // Check the If-Match header, don't send any content back if none of the tags in
    // the list match the etag, and the wildcard is not present

    if (ifMatchTags != null) {
        if (ifMatchTags.contains(WebDAV.ASTERISK) == false && ifMatchTags.contains(strETag) == false) {
            throw new WebDAVServerException(HttpServletResponse.SC_PRECONDITION_FAILED);
        }
    }

    // Check the If-None-Match header, don't send any content back if any of the tags
    // in the list match the etag, or the wildcard is present

    if (ifNoneMatchTags != null) {
        if (ifNoneMatchTags.contains(WebDAV.ASTERISK) || ifNoneMatchTags.contains(strETag)) {
            throw new WebDAVServerException(HttpServletResponse.SC_NOT_MODIFIED);
        }
    }

    // Check the modified since list, if the If-None-Match header was not specified

    if (m_ifModifiedSince != null && ifNoneMatchTags == null) {
        Date lastModifiedDate = nodeInfo.getModifiedDate();

        long fileLastModified = lastModifiedDate != null ? typeConv.longValue(lastModifiedDate) : 0L;
        long modifiedSince = m_ifModifiedSince.getTime();

        if (fileLastModified != 0L && fileLastModified <= modifiedSince) {
            throw new WebDAVServerException(HttpServletResponse.SC_NOT_MODIFIED);
        }
    }

    // Check the un-modified since list

    if (m_ifUnModifiedSince != null) {
        Date lastModifiedDate = nodeInfo.getModifiedDate();

        long fileLastModified = lastModifiedDate != null ? typeConv.longValue(lastModifiedDate) : 0L;
        long unModifiedSince = m_ifUnModifiedSince.getTime();

        if (fileLastModified >= unModifiedSince) {
            throw new WebDAVServerException(HttpServletResponse.SC_PRECONDITION_FAILED);
        }
    }
}

From source file:com.ecyrd.jspwiki.attachment.SilverpeasAttachmentServlet.java

/**
 * Serves a GET with two parameters: 'wikiname' specifying the wikiname of the attachment,
 * 'version' specifying the version indicator. {@inheritDoc}
 *///from  w  w w. j  av  a  2  s  .  co m
// FIXME: Messages would need to be localized somehow.
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
    WikiContext context = m_engine.createContext(req, WikiContext.ATTACH);

    String version = req.getParameter(HDR_VERSION);
    String nextPage = req.getParameter("nextpage");

    String msg = "An error occurred. Ouch.";
    int ver = WikiProvider.LATEST_VERSION;

    AttachmentManager mgr = m_engine.getAttachmentManager();
    AuthorizationManager authmgr = m_engine.getAuthorizationManager();

    String page = context.getPage().getName();

    if (page == null) {
        log.info("Invalid attachment name.");
        res.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    OutputStream out = null;
    InputStream in = null;

    try {
        log.debug("Attempting to download att " + page + ", version " + version);
        if (version != null) {
            ver = Integer.parseInt(version);
        }

        Attachment att = mgr.getAttachmentInfo(page, ver);

        if (att != null) {
            //
            // Check if the user has permission for this attachment
            //

            Permission permission = PermissionFactory.getPagePermission(att, "view");
            if (!authmgr.checkPermission(context.getWikiSession(), permission)) {
                log.debug("User does not have permission for this");
                res.sendError(HttpServletResponse.SC_FORBIDDEN);
                return;
            }

            //
            // Check if the client already has a version of this attachment.
            //
            if (HttpUtil.checkFor304(req, att)) {
                log.debug("Client has latest version already, sending 304...");
                res.sendError(HttpServletResponse.SC_NOT_MODIFIED);
                return;
            }

            String mimetype = getMimeType(context, att.getFileName());

            res.setContentType(mimetype);

            //
            // We use 'inline' instead of 'attachment' so that user agents
            // can try to automatically open the file.
            //

            res.addHeader("Content-Disposition", "inline; filename=\"" + att.getFileName() + "\";");

            res.addDateHeader("Last-Modified", att.getLastModified().getTime());

            if (!att.isCacheable()) {
                res.addHeader("Pragma", "no-cache");
                res.addHeader("Cache-control", "no-cache");
            }

            // If a size is provided by the provider, report it.
            if (att.getSize() >= 0) {
                res.setContentLength((int) att.getSize());
            }

            out = res.getOutputStream();
            in = mgr.getAttachmentStream(context, att);
            int read = 0;
            byte[] buffer = new byte[BUFFER_SIZE];

            while ((read = in.read(buffer)) > -1) {
                out.write(buffer, 0, read);
            }
            System.out.println("Attachment file is c:/tmp/result/" + att.getFileName());
            System.out.println("Attachment " + att.getFileName() + " sent to " + req.getRemoteUser() + " on "
                    + req.getRemoteAddr());
            if (log.isDebugEnabled()) {
                msg = "Attachment " + att.getFileName() + " sent to " + req.getRemoteUser() + " on "
                        + req.getRemoteAddr();
                log.debug(msg);
            }
            if (nextPage != null) {
                res.sendRedirect(nextPage);
            }

            return;
        }

        msg = "Attachment '" + page + "', version " + ver + " does not exist.";

        log.info(msg);
        res.sendError(HttpServletResponse.SC_NOT_FOUND, msg);
        return;
    } catch (ProviderException pe) {
        msg = "Provider error: " + pe.getMessage();

        log.debug("Provider failed while reading", pe);
        //
        // This might fail, if the response is already committed. So in that
        // case we just log it.
        //
        try {
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
        } catch (IllegalStateException e) {
        }
        return;
    } catch (NumberFormatException nfe) {
        msg = "Invalid version number (" + version + ")";
        res.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
        return;
    } catch (SocketException se) {
        //
        // These are very common in download situations due to aggressive
        // clients. No need to try and send an error.
        //
        log.debug("I/O exception during download", se);
        return;
    } catch (IOException ioe) {
        //
        // Client dropped the connection or something else happened.
        // We don't know where the error came from, so we'll at least
        // try to send an error and catch it quietly if it doesn't quite work.
        //
        msg = "Error: " + ioe.getMessage();
        log.debug("I/O exception during download", ioe);

        try {
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
        } catch (IllegalStateException e) {
        }
        return;
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
            }
        }

        //
        // Quite often, aggressive clients close the connection when they have
        // received the last bits. Therefore, we close the output, but ignore
        // any exception that might come out of it.
        //

        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:org.dataconservancy.ui.api.FileController.java

boolean failIfModifiedSinceHeader(HttpServletRequest req, HttpServletResponse res, Date ifModifiedSince,
        DateTime lastModified) throws IOException {

    if (ifModifiedSince == null) {
        return false;
    }/*from   w  ww  . jav  a  2  s. c o m*/

    if (lastModified == null) {
        res.sendError(HttpServletResponse.SC_NOT_FOUND,
                "Could not find associated DataItem for the file to " + "determine its last modified date.");
        return true;
    }

    final DateTime ifModifiedDateTime = new DateTime(ifModifiedSince);

    if (lastModified.isAfter(ifModifiedDateTime)) {
        return false;
    }

    res.sendError(HttpServletResponse.SC_NOT_MODIFIED);

    return true;
}

From source file:org.dspace.app.rest.utils.MultipartFileSender.java

public boolean isValid() throws IOException {
    if (response == null || request == null) {
        return false;
    }// www  .  j av a2s . co  m

    if (inputStream == null) {
        log.error("Input stream has no content");
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return false;
    }

    if (StringUtils.isEmpty(fileName)) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return false;
    }

    // Validate request headers for caching ---------------------------------------------------
    // If-None-Match header should contain "*" or ETag. If so, then return 304.
    String ifNoneMatch = request.getHeader(IF_NONE_MATCH);
    if (nonNull(ifNoneMatch) && matches(ifNoneMatch, checksum)) {
        log.debug("If-None-Match header should contain \"*\" or ETag. If so, then return 304.");
        response.setHeader(ETAG, checksum); // Required in 304.
        response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
        return false;
    }

    // If-Modified-Since header should be greater than LastModified. If so, then return 304.
    // This header is ignored if any If-None-Match header is specified.
    long ifModifiedSince = request.getDateHeader(IF_MODIFIED_SINCE);
    if (isNull(ifNoneMatch) && ifModifiedSince != -1 && ifModifiedSince + 1000 > lastModified) {
        log.debug("If-Modified-Since header should be greater than LastModified. If so, then return 304.");
        response.setHeader(ETAG, checksum); // Required in 304.
        response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
        return false;
    }

    // Validate request headers for resume ----------------------------------------------------

    // If-Match header should contain "*" or ETag. If not, then return 412.
    String ifMatch = request.getHeader(IF_MATCH);
    if (nonNull(ifMatch) && !matches(ifMatch, checksum)) {
        log.error("If-Match header should contain \"*\" or ETag. If not, then return 412.");
        response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
        return false;
    }

    // If-Unmodified-Since header should be greater than LastModified. If not, then return 412.
    long ifUnmodifiedSince = request.getDateHeader(IF_UNMODIFIED_SINCE);
    if (ifUnmodifiedSince != -1 && ifUnmodifiedSince + 1000 <= lastModified) {
        log.error("If-Unmodified-Since header should be greater than LastModified. If not, then return 412.");
        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        return false;
    }

    return true;
}

From source file:com.metamesh.opencms.rfs.RfsFileLoader.java

/**
 * Checks if the requested resource must be send to the client by checking the "If-Modified-Since" http header.<p>
 * //from   w  w w  .  j  a va  2 s.  co  m
 * If the resource has not been modified, the "304 - not modified" 
 * header is send to the client and <code>true</code>
 * is returned, otherwise nothing is send and <code>false</code> is returned.<p>
 * 
 * @param resource the resource to check
 * @param req the current request
 * @param res the current response
 * 
 * @return <code>true</code> if the "304 - not modified" header has been send to the client
 */
protected boolean canSendLastModifiedHeader(CmsResource resource, HttpServletRequest req,
        HttpServletResponse res) {

    // resource state must be unchanged
    if (resource.getState().isUnchanged()
            // the request must not have been send by a workplace user (we can't use "304 - not modified" in workplace
            && !CmsWorkplaceManager.isWorkplaceUser(req)
            // last modified header must match the time form the resource
            && CmsFlexController.isNotModifiedSince(req, resource.getDateLastModified())) {
        long now = System.currentTimeMillis();
        if ((resource.getDateReleased() < now) && (resource.getDateExpired() > now)) {
            // resource is available and not expired 
            CmsFlexController.setDateExpiresHeader(res, resource.getDateExpired(), m_clientCacheMaxAge);
            // set status 304 - not modified
            res.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
            return true;
        }
    }
    return false;
}