Example usage for javax.servlet.http HttpServletRequest getDateHeader

List of usage examples for javax.servlet.http HttpServletRequest getDateHeader

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getDateHeader.

Prototype

public long getDateHeader(String name);

Source Link

Document

Returns the value of the specified request header as a long value that represents a Date object.

Usage

From source file:org.mycore.common.content.util.MCRServletContentHelper.java

/**
 * Check if the If-Modified-Since condition is satisfied.
 *
 *//*from  www.  ja v a  2 s  .co  m*/
private static boolean checkIfModifiedSince(final HttpServletRequest request,
        final HttpServletResponse response, final MCRContent content) throws IOException {
    try {
        final long headerValue = request.getDateHeader("If-Modified-Since");
        final long lastModified = content.lastModified();
        if (headerValue != -1) {

            // If an If-None-Match header has been specified, if modified since
            // is ignored.
            if (request.getHeader("If-None-Match") == null && lastModified < headerValue + 1000) {
                response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                response.setHeader("ETag", content.getETag());

                return false;
            }
        }
    } catch (final IllegalArgumentException illegalArgument) {
        return true;
    }
    return true;
}

From source file:org.olat.core.gui.media.ServletUtil.java

protected static List<Range> parseRange(HttpServletRequest request, HttpServletResponse response,
        long lastModified, long fileLength) throws IOException {

    String headerValue = request.getHeader("If-Range");

    if (headerValue != null) {
        long headerValueTime = (-1L);
        try {/*from w  ww  .j a  v a 2s  .  c o m*/
            headerValueTime = request.getDateHeader("If-Range");
        } catch (IllegalArgumentException e) {
            //
        }

        if (headerValueTime != (-1L)) {
            // If the timestamp of the entity the client got is older than
            // the last modification date of the entity, the entire entity
            // is returned.
            if (lastModified > (headerValueTime + 1000))
                return Collections.emptyList();
        }
    }

    if (fileLength == 0)
        return null;

    // Retrieving the range header (if any is specified
    String rangeHeader = request.getHeader("Range");

    if (rangeHeader == null)
        return null;
    // bytes is the only range unit supported (and I don't see the point
    // of adding new ones).
    if (!rangeHeader.startsWith("bytes")) {
        response.addHeader("Content-Range", "bytes */" + fileLength);
        response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
        return null;
    }

    rangeHeader = rangeHeader.substring(6);

    // Vector which will contain all the ranges which are successfully
    // parsed.
    List<Range> result = new ArrayList<Range>();
    StringTokenizer commaTokenizer = new StringTokenizer(rangeHeader, ",");

    // Parsing the range list
    while (commaTokenizer.hasMoreTokens()) {
        String rangeDefinition = commaTokenizer.nextToken().trim();

        Range currentRange = new Range();
        currentRange.length = fileLength;

        int dashPos = rangeDefinition.indexOf('-');

        if (dashPos == -1) {
            response.addHeader("Content-Range", "bytes */" + fileLength);
            response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
            return null;
        }

        if (dashPos == 0) {

            try {
                long offset = Long.parseLong(rangeDefinition);
                currentRange.start = fileLength + offset;
                currentRange.end = fileLength - 1;
            } catch (NumberFormatException e) {
                response.addHeader("Content-Range", "bytes */" + fileLength);
                response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
                return null;
            }

        } else {

            try {
                currentRange.start = Long.parseLong(rangeDefinition.substring(0, dashPos));
                if (dashPos < rangeDefinition.length() - 1)
                    currentRange.end = Long
                            .parseLong(rangeDefinition.substring(dashPos + 1, rangeDefinition.length()));
                else
                    currentRange.end = fileLength - 1;
            } catch (NumberFormatException e) {
                response.addHeader("Content-Range", "bytes */" + fileLength);
                response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
                return null;
            }

        }

        if (!currentRange.validate()) {
            response.addHeader("Content-Range", "bytes */" + fileLength);
            response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
            return null;
        }

        result.add(currentRange);
    }

    return result;
}

From source file:org.mycore.common.content.util.MCRServletContentHelper.java

/**
 * Check if the if-unmodified-since condition is satisfied.
 *//*from w w w  .  j  a v a 2 s.  c o  m*/
private static boolean checkIfUnmodifiedSince(final HttpServletRequest request,
        final HttpServletResponse response, final MCRContent resource) throws IOException {
    try {
        final long lastModified = resource.lastModified();
        final long headerValue = request.getDateHeader("If-Unmodified-Since");
        if (headerValue != -1) {
            if (lastModified >= headerValue + 1000) {
                // The content has been modified.
                response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
                return false;
            }
        }
    } catch (final IllegalArgumentException illegalArgument) {
        return true;
    }
    return true;
}

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

/**
 * Method analyzeRequest.//from   w ww  .j  a va  2s .c o m
 * 
 * @param req
 * @param modified
 * @param expires
 * @param size
 * @return Http11ResponseType
 */
public static Http11ResponseType analyzeRequest(HttpServletRequest req, long modified, long expires,
        long size) {

    /* adjust the statistics */
    ++stats[STATS_ANALYZED];

    /* the response type */
    Http11ResponseType type = new Http11ResponseType(RESPONSE_INTERNAL_SERVER_ERROR, modified, expires);
    type.size = size;

    /* calculate the etag */
    String eTag = Http11Utils.calcETag(modified);

    /* decode the conditional headers */
    long ifModifiedSince = -1;
    try {
        ifModifiedSince = req.getDateHeader(HEADER_IF_MODIFIED_SINCE);
    } catch (IllegalArgumentException e) {
        log.debug("Client provided malformed '{}' header: {}", HEADER_IF_MODIFIED_SINCE,
                req.getDateHeader(HEADER_IF_MODIFIED_SINCE));
    }
    String ifNoneMatch = req.getHeader(HEADER_IF_NONE_MATCH);

    long ifUnmodifiedSince = -1;
    try {
        ifUnmodifiedSince = req.getDateHeader(HEADER_IF_UNMODIFIED_SINCE);
    } catch (IllegalArgumentException e) {
        log.debug("Client provided malformed '{}' header: {}", HEADER_IF_UNMODIFIED_SINCE,
                req.getDateHeader(HEADER_IF_UNMODIFIED_SINCE));
    }

    String ifMatch = req.getHeader(HEADER_IF_MATCH);
    String method = req.getMethod();
    type.headerOnly = method.equals(METHOD_HEAD);
    boolean reqGetHead = method.equals(METHOD_GET) || type.headerOnly;
    boolean ifNoneMatchMatch = matchETag(eTag, ifNoneMatch);

    /* method */
    if (!reqGetHead && !method.equals(METHOD_POST)) {
        type.type = RESPONSE_METHOD_NOT_ALLOWED;
        return type;
    }

    /* check e-tag */
    if (ifNoneMatch != null && ifNoneMatchMatch && reqGetHead) {
        type.type = RESPONSE_NOT_MODIFIED;
        return type;
    }

    /* check not modified */
    if (ifNoneMatch == null && ifModifiedSince != -1 && modified < ifModifiedSince + MS_PER_SECOND) {
        type.type = RESPONSE_NOT_MODIFIED;
        return type;
    }

    /* precondition check failed */
    if (ifNoneMatch != null && ifNoneMatchMatch && !reqGetHead) {
        log.error("412 PCF: Method={}, If-None-Match={}, match={}",
                new Object[] { req.getMethod(), ifNoneMatch, ifNoneMatchMatch });
        log.info("If-None-Match header only supported in GET or HEAD requests.");
        type.type = RESPONSE_PRECONDITION_FAILED;
        type.err = "If-None-Match header only supported in GET or HEAD requests.";
        return type;
    }
    if (ifUnmodifiedSince != -1 && modified > ifUnmodifiedSince) {
        log.error("412 PCF: modified={} > ifUnmodifiedSince={}", modified, ifUnmodifiedSince);
        log.info("If-Unmodified-Since precondition check failed.");
        type.type = RESPONSE_PRECONDITION_FAILED;
        type.err = "If-Unmodified-Since precondition check failed.";
        return type;
    }
    if (ifMatch != null && !matchETag(eTag, ifMatch)) {
        log.error("412 PCF: !matchETag({}, {})", eTag, ifMatch);
        log.info("If-match precondition check failed.");
        type.type = RESPONSE_PRECONDITION_FAILED;
        type.err = "If-match precondition check failed.";
        return type;
    }

    /* decode the range headers */
    if (size >= 0) {
        // PENDING: handle ranges
    }

    /* return the result */
    type.type = RESPONSE_OK;
    return type;
}

From source file:org.kuali.mobility.writer.controllers.WriterMediaController.java

@RequestMapping(value = "/{mediaId}", method = RequestMethod.GET)
public void getMedia(@PathVariable int mediaId,
        @RequestParam(value = "thumb", required = false, defaultValue = "false") boolean thumb,
        HttpServletRequest request, HttpServletResponse response) throws IOException {

    long dateChanged = request.getDateHeader("If-Modified-Since") / 1000;

    File mediaFile = service.getMediaFile(mediaId, thumb);
    long mediaChanged = mediaFile.lastModified() / 1000;
    if (dateChanged == mediaChanged) {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return;/*from   w  w  w  .  j av a 2  s  .  c  om*/
    }
    Media media = service.getMedia(mediaId);
    response.setContentType(media.getMimeType());
    response.setDateHeader("Last-Modified", mediaFile.lastModified());

    int bytesWritten = IOUtils.copy(new FileInputStream(mediaFile), response.getOutputStream());
    response.setContentLength(bytesWritten);

}

From source file:fi.aluesarjat.prototype.SubjectGraphServlet.java

@Override
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;

    long ifModifiedSince = request.getDateHeader("If-Modified-Since");
    if (ifModifiedSince >= LAST_MODIFIED) {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return;//from   w  ww.  java  2 s . c  o m
    }

    String subject = request.getRequestURL().toString();
    RDFConnection connection = repository.openConnection();
    try {
        SPARQLQuery query = connection.createQuery(QueryLanguage.SPARQL,
                "CONSTRUCT { ?s ?p ?o } WHERE { ?s ?p ?o }");
        query.setBinding("s", new UID(subject));
        String contentType = getAcceptedType(request, Format.RDFXML);
        response.setDateHeader("Last-Modified", System.currentTimeMillis());
        response.setContentType(contentType);
        query.streamTriples(response.getWriter(), contentType);
    } finally {
        connection.close();
    }

}

From source file:org.apache.myfaces.custom.skin.webapp.CachingStyleSheetLoader.java

private boolean isFileModified(File file, HttpServletRequest request) {
    long lastModified = file.lastModified();
    long browserDate = request.getDateHeader("If-Modified-Since");

    // normalize to seconds - this should work with any os
    lastModified = (lastModified / 1000) * 1000;
    browserDate = (browserDate / 1000) * 1000;

    if (lastModified == browserDate) {
        return false;
    } else {// ww w.  ja  v  a2  s. com
        return true;
    }
}

From source file:fi.aluesarjat.prototype.AreasServlet.java

@Override
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;

    long ifModifiedSince = request.getDateHeader("If-Modified-Since");
    if (ifModifiedSince >= LAST_MODIFIED) {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return;//from   ww w .  ja va 2  s  .c o m
    }

    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.setDateHeader("Last-Modified", System.currentTimeMillis());
    response.setHeader("Cache-Control", "max-age=86400");

    String level = request.getParameter("level");
    String content;
    if (level == null) {
        content = areas;
    } else if ("1".equals(level)) {
        content = areas1;
    } else if ("2".equals(level)) {
        content = areas2;
    } else if ("3".equals(level)) {
        content = areas3;
    } else if ("4".equals(level)) {
        content = areas4;
    } else {
        throw new IllegalArgumentException("Illegal level " + level);
    }
    response.getWriter().append(content);
    response.getWriter().flush();

}

From source file:fi.aluesarjat.prototype.ContextAccessServlet.java

@Override
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;

    long ifModifiedSince = request.getDateHeader("If-Modified-Since");
    if (ifModifiedSince >= LAST_MODIFIED) {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return;//from  ww  w.  j  av  a 2s .c om
    }

    String context = request.getRequestURL().toString();
    RDFConnection connection = repository.openConnection();
    try {
        SPARQLQuery query = connection.createQuery(QueryLanguage.SPARQL,
                "CONSTRUCT { ?s ?p ?o } WHERE { GRAPH ?context { ?s ?p ?o } }");
        query.setBinding("context", new UID(context));

        String contentType = null;
        String format = request.getParameter("format");
        if ("turtle".equals(format)) {
            contentType = Format.TURTLE.getMimetype();
        } else if ("ntriples".equals(format)) {
            contentType = Format.NTRIPLES.getMimetype();
        } else {
            contentType = getAcceptedType(request, Format.RDFXML);
        }
        response.setDateHeader("Last-Modified", System.currentTimeMillis());
        response.setContentType(contentType);
        query.streamTriples(response.getWriter(), contentType);
    } finally {
        connection.close();
    }
}

From source file:org.apache.wiki.util.HttpUtil.java

/**
 *  If returns true, then should return a 304 (HTTP_NOT_MODIFIED)
 *  @param req the HTTP request// w  w  w. j  a v a2  s.  com
 *  @param pageName the wiki page name to check for
 *  @param lastModified the last modified date of the wiki page to check for
 *  @return the result of the check
 */
public static boolean checkFor304(HttpServletRequest req, String pageName, Date lastModified) {
    //
    //  We'll do some handling for CONDITIONAL GET (and return a 304)
    //  If the client has set the following headers, do not try for a 304.
    //
    //    pragma: no-cache
    //    cache-control: no-cache
    //

    if ("no-cache".equalsIgnoreCase(req.getHeader("Pragma"))
            || "no-cache".equalsIgnoreCase(req.getHeader("cache-control"))) {
        // Wants specifically a fresh copy
    } else {
        //
        //  HTTP 1.1 ETags go first
        //
        String thisTag = createETag(pageName, lastModified);

        String eTag = req.getHeader("If-None-Match");

        if (eTag != null && eTag.equals(thisTag)) {
            return true;
        }

        //
        //  Next, try if-modified-since
        //
        DateFormat rfcDateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z");

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

            //log.info("ifModifiedSince:"+ifModifiedSince);
            if (ifModifiedSince != -1) {
                long lastModifiedTime = lastModified.getTime();

                //log.info("lastModifiedTime:" + lastModifiedTime);
                if (lastModifiedTime <= ifModifiedSince) {
                    return true;
                }
            } else {
                try {
                    String s = req.getHeader("If-Modified-Since");

                    if (s != null) {
                        Date ifModifiedSinceDate = rfcDateFormat.parse(s);
                        //log.info("ifModifiedSinceDate:" + ifModifiedSinceDate);
                        if (lastModified.before(ifModifiedSinceDate)) {
                            return true;
                        }
                    }
                } catch (ParseException e) {
                    log.warn(e.getLocalizedMessage(), e);
                }
            }
        } catch (IllegalArgumentException e) {
            // Illegal date/time header format.
            // We fail quietly, and return false.
            // FIXME: Should really move to ETags.
        }
    }

    return false;
}