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.shredzone.cilla.view.AbstractView.java

/**
 * Checks that the request sent an "If-Modified-Since" header, and the date matches
 * the given date.//ww w . j  a  va  2 s.c o  m
 *
 * @param req
 *            {@link HttpServletRequest} to use
 * @param date
 *            {@link Date} to check
 * @return {@code true}: Resource has not changed since it was last delivered
 */
protected boolean isNotModifiedSince(HttpServletRequest req, Date date) {
    long modifiedSinceTs = -1;
    try {
        modifiedSinceTs = req.getDateHeader("If-Modified-Since");
    } catch (IllegalArgumentException ex) {
        // As stated in RFC2616 Sec. 14.25, an invalid date will just be ignored.
    }

    return (modifiedSinceTs >= 0 && (modifiedSinceTs / 1000) == (date.getTime() / 1000));
}

From source file:org.sakaiproject.nakamura.files.pool.StreamHelper.java

/**
 * Returns <code>true</code> if the request has a <code>If-Modified-Since</code> header
 * whose date value is later than the last modification time given as
 * <code>modifTime</code>.//from ww w .j ava2 s  .co  m
 *
 * @param request
 *          The <code>ComponentRequest</code> checked for the
 *          <code>If-Modified-Since</code> header.
 * @param modifTime
 *          The last modification time to compare the header to.
 * @return <code>true</code> if the <code>modifTime</code> is less than or equal to the
 *         time of the <code>If-Modified-Since</code> header.
 */
private boolean unmodified(HttpServletRequest request, long modifTime) {
    if (modifTime > 0) {
        long modTime = modifTime / 1000; // seconds
        long ims = request.getDateHeader(HEADER_IF_MODIFIED_SINCE) / 1000;
        return modTime <= ims;
    }

    // we have no modification time value, assume modified
    return false;
}

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

/**
 * Parses and validates the range header.
 * This method ensures that all ranges are in ascending order and non-overlapping, so we can use a single
 * InputStream.// w  ww.  ja va  2s.  c  om
 */
private static ArrayList<Range> parseRange(final HttpServletRequest request, final HttpServletResponse response,
        final MCRContent content) throws IOException {

    // Checking if range is still valid (lastModified)
    final String headerValue = request.getHeader("If-Range");

    if (headerValue != null) {
        long headerValueTime = -1L;
        try {
            headerValueTime = request.getDateHeader("If-Range");
        } catch (final IllegalArgumentException e) {
            // Ignore
        }

        final String eTag = content.getETag();
        final long lastModified = content.lastModified();

        if (headerValueTime == -1L) {
            // If the content changed, the complete content is served.
            if (!eTag.equals(headerValue.trim())) {
                return FULL;
            }
        } else {
            //add one second buffer to check if the content was modified.
            if (lastModified > headerValueTime + 1000) {
                return FULL;
            }
        }

    }

    final long fileLength = content.length();
    if (fileLength <= 0) {
        return null;
    }

    String rangeHeader = request.getHeader("Range");
    if (rangeHeader == null) {
        return null;
    }

    // We operate on byte level only
    String rangeUnit = "bytes";
    if (!rangeHeader.startsWith(rangeUnit)) {
        response.addHeader("Content-Range", "bytes */" + fileLength);
        response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
        return null;
    }

    rangeHeader = rangeHeader.substring(rangeUnit.length() + 1);

    final ArrayList<Range> result = new ArrayList<>();
    final StringTokenizer commaTokenizer = new StringTokenizer(rangeHeader, ",");

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

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

        final 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 {
                //offset is negative
                final long offset = Long.parseLong(rangeDefinition);
                currentRange.start = fileLength + offset;
                currentRange.end = fileLength - 1;
            } catch (final 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 (final NumberFormatException e) {
                response.addHeader("Content-Range", "bytes */" + fileLength);
                response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
                return null;
            }

        }

        if (!currentRange.validate() || lastByte > currentRange.start) {
            response.addHeader("Content-Range", "bytes */" + fileLength);
            response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
            return null;
        }
        lastByte = currentRange.end;
        result.add(currentRange);
    }
    return result;
}

From source file:org.kuali.mobility.icons.controllers.WebIconsController.java

/**
 * Get the icon matching all the criteria of the request and write it the the HttpServletResponse.
 *
 * @param iconName Name of the icon to get.
 * @param theme    The theme to get the icon in.
 * @param size     Size to get the icon in.
 * @param request  The HttpServletRequest being handled.
 * @param response The HttpServletResponse that will reply.
 * @throws IOException Thrown if there is an exception creating the icon or writing it to the response.
 *//*from   ww  w  .  j  a v  a 2s.c o  m*/
private void writeIconToHttpResponse(String iconName, String theme, int size, HttpServletRequest request,
        HttpServletResponse response) throws IOException {
    long dateChanged = request.getDateHeader("If-Modified-Since") / 1000;
    File imageFile = iconService.getImageFile(iconName, theme, size);

    long mediaChanged = imageFile.lastModified() / 1000;
    if (dateChanged == mediaChanged) {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }
    response.setContentType("image/png");
    InputStream imageInput = new FileInputStream(imageFile);
    response.setDateHeader("Last-Modified", imageFile.lastModified());

    int bytesWritten = IOUtils.copy(imageInput, response.getOutputStream());
    response.setContentLength(bytesWritten);
    response.flushBuffer();
}

From source file:org.eclipse.smarthome.ui.icon.internal.IconServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    if (req.getDateHeader("If-Modified-Since") > startupTime) {
        resp.setStatus(304);// w  w w.ja  va 2 s .co m
        return;
    }

    String category = getCategory(req);
    Format format = getFormat(req);
    String state = getState(req);
    String iconSetId = getIconSetId(req);

    IconProvider topProvider = null;
    int maxPrio = Integer.MIN_VALUE;
    for (IconProvider provider : iconProvider) {
        Integer prio = provider.hasIcon(category, iconSetId, format);
        if (prio != null && prio > maxPrio) {
            maxPrio = prio;
            topProvider = provider;
        }
    }
    if (topProvider != null) {
        if (format.equals(Format.SVG)) {
            resp.setContentType("image/svg+xml");
        } else {
            resp.setContentType("image/png");
        }
        resp.setDateHeader("Last-Modified", new Date().getTime());
        ServletOutputStream os = resp.getOutputStream();
        try (InputStream is = topProvider.getIcon(category, iconSetId, state, format)) {
            IOUtils.copy(is, os);
            resp.flushBuffer();
        } catch (IOException e) {
            logger.error("Failed sending the icon byte stream as a response: {}", e.getMessage());
            resp.sendError(500, e.getMessage());
        }
    } else {
        resp.sendError(404);
    }
}

From source file:nl.strohalm.cyclos.servlets.ImageByNameServlet.java

/**
 * Write the image file to the response//from w  w w. j av  a2  s . c o  m
 */
private void write(final HttpServletRequest request, final HttpServletResponse response, final File file,
        final ImageType type) throws IOException {
    final long ifModifiedSince = request.getDateHeader("If-Modified-Since");
    if (ifModifiedSince > 0 && file.lastModified() <= ifModifiedSince) {
        // The contents have not changed
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }
    // The contents are modified, or not in browser's cache. Render it
    if (type != null) {
        response.setContentType(type.getContentType());
    }
    responseHelper.writeFile(response, file);
    response.flushBuffer();
}

From source file:ca.intelliware.ihtsdo.mlds.web.rest.MemberResource.java

private ResponseEntity<?> downloadFile(HttpServletRequest request, File file) throws SQLException, IOException {
    if (file == null) {
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    } else if (file.getLastUpdated() != null) {
        long ifModifiedSince = request.getDateHeader("If-Modified-Since");
        long lastUpdatedSecondsFloor = file.getLastUpdated().getMillis() / 1000 * 1000;
        if (ifModifiedSince != -1 && lastUpdatedSecondsFloor <= ifModifiedSince) {
            return new ResponseEntity<>(HttpStatus.NOT_MODIFIED);
        }/*from  w ww  .j  a  v a2  s.  co  m*/
    }

    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setContentType(MediaType.valueOf(file.getMimetype()));
    httpHeaders.setContentLength(file.getContent().length());
    httpHeaders.setContentDispositionFormData("file", file.getFilename());
    if (file.getLastUpdated() != null) {
        httpHeaders.setLastModified(file.getLastUpdated().getMillis());
    }

    byte[] byteArray = IOUtils.toByteArray(file.getContent().getBinaryStream());
    org.springframework.core.io.Resource contents = new ByteArrayResource(byteArray);
    return new ResponseEntity<org.springframework.core.io.Resource>(contents, httpHeaders, HttpStatus.OK);
}

From source file:httpUtils.HttpUtils.java

/**
 * Parse the request headers, build the response, stream back file
 * @param request/* w w w  .j  ava2s.c om*/
 * @param response
 * @param dataStream
 * @param fileLength
 * @param fileName
 * @param fileLastModified
 * @param contentType
 * @return
 */
private static HttpServletResponse getFileAsStream(HttpServletRequest request, HttpServletResponse response,
        InputStream dataStream, long fileLength, String fileName, long fileLastModified, String contentType) {
    if (dataStream == null) {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        return response;
    }

    if (StringUtils.isEmpty(fileName) || fileLastModified == 0L) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return response;
    }

    String ifNoneMatch = request.getHeader("If-None-Match");
    if (ifNoneMatch != null && matches(ifNoneMatch, fileName)) {
        response.setHeader("ETag", fileName);
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return response;
    }

    long ifModifiedSince = request.getDateHeader("If-Modified-Since");
    if (ifNoneMatch == null && ifModifiedSince != -1 && ifModifiedSince + 1000 > fileLastModified) {
        response.setHeader("ETag", fileName);
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return response;
    }

    String ifMatch = request.getHeader("If-Match");
    if (ifMatch != null && !matches(ifMatch, fileName)) {
        response.setStatus(HttpServletResponse.SC_PRECONDITION_FAILED);
        return response;
    }

    long ifUnmodifiedSince = request.getDateHeader("If-Unmodified-Since");
    if (ifUnmodifiedSince != -1 && ifUnmodifiedSince + 1000 <= fileLastModified) {
        response.setStatus(HttpServletResponse.SC_PRECONDITION_FAILED);
        return response;
    }

    Range full = new Range(0, fileLength - 1, fileLength);
    List<Range> ranges = new ArrayList<Range>();
    String range = request.getHeader("Range");
    if (range != null) {
        if (!range.matches("^bytes=\\d*-\\d*(,\\d*-\\d*)*$")) {
            response.setHeader("Content-Range", "bytes */" + fileLength);
            response.setStatus(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
            return response;
        }

        String ifRange = request.getHeader("If-Range");
        if (ifRange != null && !ifRange.equals(fileName)) {
            try {
                long ifRangeTime = request.getDateHeader("If-Range");
                if (ifRangeTime != -1) {
                    ranges.add(full);
                }
            } catch (IllegalArgumentException ignore) {
                ranges.add(full);
            }
        }

        if (ranges.isEmpty()) {
            for (String part : range.substring(6).split(",")) {
                // Assuming a file with length of 100, the following
                // examples returns bytes at:
                // 50-80 (50 to 80), 40- (40 to length=100), -20
                // (length-20=80 to length=100).
                long start = sublong(part, 0, part.indexOf("-"));
                long end = sublong(part, part.indexOf("-") + 1, part.length());

                if (start == -1) {
                    start = fileLength - end;
                    end = fileLength - 1;
                } else if (end == -1 || end > fileLength - 1) {
                    end = fileLength - 1;
                }

                // Check if Range is syntactically valid. If not, then
                // return 416.
                if (start > end) {
                    response.setHeader("Content-Range", "bytes */" + fileLength); // Required
                    // in
                    // 416.
                    response.setStatus(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
                    return response;
                }

                // Add range.
                ranges.add(new Range(start, end, fileLength));
            }
        }
    }

    // Get content type by file name and set content disposition.
    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";
    } else if (!contentType.startsWith("image")) {
        // 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.
        String accept = request.getHeader("Accept");
        disposition = accept != null && accepts(accept, contentType) ? "inline" : "attachment";
    }

    // Initialize response.
    response.reset();
    response.setBufferSize(HttpUtils.DEFAULT_BUFFER_SIZE);
    response.setHeader("Content-Disposition", disposition + ";filename=\"" + fileName + "\"");
    response.setHeader("Accept-Ranges", "bytes");
    response.setHeader("ETag", fileName);
    response.setDateHeader("Last-Modified", fileLastModified);
    response.setDateHeader("Expires", System.currentTimeMillis() + HttpUtils.DEFAULT_EXPIRE_TIME);

    // Send requested file (part(s)) to client
    // ------------------------------------------------

    // Prepare streams.
    InputStream input = null;
    OutputStream output = null;

    try {
        // Open streams.
        input = new BufferedInputStream(dataStream);
        output = response.getOutputStream();

        if (ranges.isEmpty() || ranges.get(0) == full) {

            // Return full file.
            Range r = full;
            response.setContentType(contentType);
            response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total);
            response.setHeader("Content-Length", String.valueOf(r.length));
            copy(input, output, fileLength, r.start, r.length);

        } else if (ranges.size() == 1) {

            // Return single part of file.
            Range r = ranges.get(0);
            response.setContentType(contentType);
            response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total);
            response.setHeader("Content-Length", String.valueOf(r.length));
            response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206.

            // Copy single part range.
            copy(input, output, fileLength, r.start, r.length);

        } else {

            // Return multiple parts of file.
            response.setContentType("multipart/byteranges; boundary=" + HttpUtils.MULTIPART_BOUNDARY);
            response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206.

            // Cast back to ServletOutputStream to get the easy println
            // methods.
            ServletOutputStream sos = (ServletOutputStream) output;

            // Copy multi part range.
            for (Range r : ranges) {
                // Add multipart boundary and header fields for every range.
                sos.println();
                sos.println("--" + HttpUtils.MULTIPART_BOUNDARY);
                sos.println("Content-Type: " + contentType);
                sos.println("Content-Range: bytes " + r.start + "-" + r.end + "/" + r.total);

                // Copy single part range of multi part range.
                copy(input, output, fileLength, r.start, r.length);
            }

            // End with multipart boundary.
            sos.println();
            sos.println("--" + HttpUtils.MULTIPART_BOUNDARY + "--");
        }
    } catch (Exception e) {
        log.error("get file as stream failed", e);
    } finally {
        // Gently close streams.
        close(output);
        close(input);
        close(dataStream);
    }
    return response;
}

From source file:net.duckling.ddl.web.controller.file.BaseAttachController.java

private boolean isModified(MetaInfo meta, HttpServletRequest request) {
    long browserModifyTime = request.getDateHeader("If-Modified-Since");
    try {/*from   w ww .j a  v  a  2s. c om*/
        return (browserModifyTime != meta.lastUpdate.getTime());
    } catch (Exception e) {
        return true;
    }
}

From source file:com.astamuse.asta4d.web.builtin.StaticResourceHandler.java

private long retrieveClientCachedTime(HttpServletRequest request) {
    try {/*from  w w w . j  av a  2 s . c  o  m*/
        long time = request.getDateHeader("If-Modified-Since");
        return DateTimeZone.getDefault().convertLocalToUTC(time, false);
    } catch (Exception e) {
        logger.debug("retrieve If-Modified-Since failed", e);
        return -1;
    }
}