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:ee.pri.rl.blog.web.servlet.FileDownloadServlet.java

private void sendNotModified(String calculatedTag, HttpServletResponse resp) {
    resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
    resp.setHeader("ETag", calculatedTag);
}

From source file:org.massyframework.assembly.base.web.HttpResourceProcessorManagement.java

/**
 * ???Http?/*  www.  j  a v  a2s.  co m*/
 * @param req http
 * @param resp http?
 * @param resourcePath ?
 * @param resourceURL ?URL
 * @throws IOException ?IO
 */
private void writeResource(final HttpServletRequest req, final HttpServletResponse resp, final String pathInfo,
        final URL resourceURL) throws IOException {
    URLConnection connection = resourceURL.openConnection();
    long lastModified = connection.getLastModified();
    int contentLength = connection.getContentLength();

    String etag = null;
    if (lastModified != -1 && contentLength != -1)
        etag = "W/\"" + contentLength + "-" + lastModified + "\""; //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$

    // Check for cache revalidation.
    // We should prefer ETag validation as the guarantees are stronger and all HTTP 1.1 clients should be using it
    String ifNoneMatch = req.getHeader(IF_NONE_MATCH);
    if (ifNoneMatch != null && etag != null && ifNoneMatch.indexOf(etag) != -1) {
        resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
    }

    long ifModifiedSince = req.getDateHeader(IF_MODIFIED_SINCE);
    // for purposes of comparison we add 999 to ifModifiedSince since the fidelity
    // of the IMS header generally doesn't include milli-seconds
    if (ifModifiedSince > -1 && lastModified > 0 && lastModified <= (ifModifiedSince + 999)) {
        resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
    }

    // return the full contents regularly
    if (contentLength != -1)
        resp.setContentLength(contentLength);

    String contentType = getServletContext().getMimeType(pathInfo);
    if (contentType != null)
        resp.setContentType(contentType);

    if (lastModified > 0)
        resp.setDateHeader(LAST_MODIFIED, lastModified);

    if (etag != null)
        resp.setHeader(ETAG, etag);

    if (contentLength != 0) {
        // open the input stream
        InputStream is = null;
        try {
            is = connection.getInputStream();
            // write the resource
            try {
                OutputStream os = resp.getOutputStream();
                int writtenContentLength = writeResourceToOutputStream(is, os);
                if (contentLength == -1 || contentLength != writtenContentLength)
                    resp.setContentLength(writtenContentLength);
            } catch (IllegalStateException e) { // can occur if the response output is already open as a Writer
                Writer writer = resp.getWriter();
                writeResourceToWriter(is, writer);
                // Since ContentLength is a measure of the number of bytes contained in the body
                // of a message when we use a Writer we lose control of the exact byte count and
                // defer the problem to the Servlet Engine's Writer implementation.
            }
        } catch (FileNotFoundException e) {
            // FileNotFoundException may indicate the following scenarios
            // - url is a directory
            // - url is not accessible
            sendError(resp, HttpServletResponse.SC_FORBIDDEN);
        } catch (SecurityException e) {
            // SecurityException may indicate the following scenarios
            // - url is not accessible
            sendError(resp, HttpServletResponse.SC_FORBIDDEN);
        } finally {
            if (is != null)
                try {
                    is.close();
                } catch (IOException e) {
                    // ignore
                }
        }
    }

}

From source file:org.nuxeo.ecm.core.io.download.TestDownloadService.java

protected void doTestETagHeader(Boolean match) throws Exception {
    // Given a blob
    String blobValue = "Hello World";
    Blob blob = Blobs.createBlob(blobValue);
    blob.setFilename("myFile.txt");
    blob.setDigest("12345");

    String digestToTest;//from www .j  ava  2 s .c  om
    if (match == null) {
        digestToTest = null;
    } else if (TRUE.equals(match)) {
        digestToTest = "12345";
    } else {
        digestToTest = "78787";
    }

    // When I send a request a given digest
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    HttpServletRequest req = mock(HttpServletRequest.class);
    when(req.getHeader("If-None-Match")).thenReturn('"' + digestToTest + '"');
    when(req.getMethod()).thenReturn("GET");

    HttpServletResponse resp = mock(HttpServletResponse.class);
    ServletOutputStream sos = new ServletOutputStream() {
        @Override
        public void write(int b) throws IOException {
            out.write(b);
        }
    };
    @SuppressWarnings("resource")
    PrintWriter printWriter = new PrintWriter(sos);
    when(resp.getOutputStream()).thenReturn(sos);
    when(resp.getWriter()).thenReturn(printWriter);

    downloadService.downloadBlob(req, resp, null, null, blob, null, null);

    verify(req, atLeast(1)).getHeader("If-None-Match");

    // Then the response differs if the digest match
    if (TRUE.equals(match)) {
        assertEquals(0, out.toByteArray().length);
        verify(resp).sendError(HttpServletResponse.SC_NOT_MODIFIED);
    } else {
        assertEquals(blobValue, out.toString());
        verify(resp).setHeader("ETag", '"' + blob.getDigest() + '"');
    }
}

From source file:com.sun.socialsite.web.rest.servlets.ImageServlet.java

/**
 * Handles the HTTP <code>GET</code> method.
 * @param req servlet request/*from w w  w .  j  a v  a  2s  .  c om*/
 * @param resp servlet response
 */
@Override
protected final void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    String itemName = ((req.getPathInfo() != null) ? req.getPathInfo().substring(1) : null);
    if (itemName != null)
        itemName = URLDecoder.decode(itemName, "UTF-8");

    Result result = getResult(itemName);

    if ((result == null) || (result.imageType == null) || (result.imageType.equals(""))) {
        RequestDispatcher rd = req.getRequestDispatcher(defaultImage);
        rd.forward(req, resp);
        return;
    }

    long ifModifiedTime = 0L;
    if (req.getHeader("If-Modified-Since") != null) {
        try {
            ifModifiedTime = getDateFormat().parse(req.getHeader("If-Modified-Since")).getTime();
        } catch (Throwable intentionallyIgnored) {
        }
    }

    // We've got an EHCache GenericResponseWrapper, it ignores date headers
    //resp.setDateHeader("Last-Modified", lastModifiedString);
    resp.setHeader("Last-Modified", getDateFormat().format(result.lastUpdate));
    resp.setHeader("ETag", result.eTag);

    // Force clients to revalidate each time
    // See RFC 2616 (HTTP 1.1 spec) secs 14.21, 13.2.1
    // We've got an EHCache GenericResponseWrapper, it ignores date headers
    //resp.setDateHeader("Expires", 0);
    resp.setHeader("Expires", epoch);

    // We may also want this (See 13.2.1 and 14.9.4)
    // response.setHeader("Cache-Control","must-revalidate");

    if (result.lastUpdate.getTime() > ifModifiedTime || !handleConditionalGets) {
        resp.setContentType(result.imageType);
        resp.setContentLength(result.imageBytes.length);
        OutputStream out = resp.getOutputStream();
        out.write(result.imageBytes, 0, result.imageBytes.length);
        out.close();
    } else {
        resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
    }

    return;
}

From source file:ch.ralscha.extdirectspring.util.ExtDirectSpringUtil.java

/**
 * Checks etag and sends back HTTP status 304 if not modified. If modified sets
 * content type and content length, adds cache headers (
 * {@link #addCacheHeaders(HttpServletResponse, String, Integer)}), writes the data
 * into the {@link HttpServletResponse#getOutputStream()} and flushes it.
 *
 * @param request the HTTP servlet request
 * @param response the HTTP servlet response
 * @param data the response data/*from w w w  .j av  a  2s.  com*/
 * @param contentType the content type of the data (i.e.
 * "application/javascript;charset=UTF-8")
 * @throws IOException
 */
public static void handleCacheableResponse(HttpServletRequest request, HttpServletResponse response,
        byte[] data, String contentType) throws IOException {
    String ifNoneMatch = request.getHeader("If-None-Match");
    String etag = "\"0" + DigestUtils.md5DigestAsHex(data) + "\"";

    if (etag.equals(ifNoneMatch)) {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }

    response.setContentType(contentType);
    response.setContentLength(data.length);

    addCacheHeaders(response, etag, 6);

    @SuppressWarnings("resource")
    ServletOutputStream out = response.getOutputStream();
    out.write(data);
    out.flush();
}

From source file:org.restcomm.connect.http.filters.FileCacheServlet.java

/**
 * Process the actual request.// ww w . j av a2  s  . co 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.
    String requestedFile = request.getPathInfo();
    if (logger.isDebugEnabled()) {
        logger.debug("Requested path:" + requestedFile);
    }

    // Check if file is actually supplied to the request URL.
    if (requestedFile == null) {
        logger.debug("No file requested, return 404.");
        // Do your thing if the file is not supplied to the request URL.
        // Throw an exception, or send 404, or show default/warning page, or just ignore it.
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    Configuration rootConfiguration = (Configuration) request.getServletContext()
            .getAttribute(Configuration.class.getName());
    Configuration runtimeConfiguration = rootConfiguration.subset("runtime-settings");

    String basePath = runtimeConfiguration.getString("cache-path");
    int bufferSize = runtimeConfiguration.getInteger("cache-buffer-size", DEFAULT_BUFFER_SIZE);
    long expireTime = runtimeConfiguration.getLong("cache-expire-time", DEFAULT_EXPIRE_TIME);

    // URL-decode the file name (might contain spaces and on) and prepare file object.
    String fDecodedPath = URLDecoder.decode(requestedFile, "UTF-8");
    File file = new File(basePath, fDecodedPath);

    // Check if file actually exists in filesystem.
    if (!file.exists()) {
        logger.debug("Requested file not found, return 404.");
        // Do your thing if the file appears to be non-existing.
        // Throw an exception, or send 404, or show default/warning page, or just ignore it.
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // Prepare some variables. The ETag is an unique identifier of the file.
    String fileName = file.getName();
    long length = file.length();
    long lastModified = file.lastModified();
    String eTag = fileName + "_" + length + "_" + lastModified;
    long expires = System.currentTimeMillis() + expireTime;

    // 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 (ifNoneMatch != null && matches(ifNoneMatch, eTag)) {
        logger.debug("IfNoneMatch/Etag not matching, return 304.");
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        response.setHeader("ETag", eTag); // Required in 304.
        response.setDateHeader("Expires", expires); // Postpone cache with 1 week.
        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) {
        logger.debug("IfModifiedSince not matching, return 304.");
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        response.setHeader("ETag", eTag); // Required in 304.
        response.setDateHeader("Expires", expires); // Postpone cache with 1 week.
        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)) {
        logger.debug("ifMatch not matching, return 412.");
        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) {
        logger.debug("ifUnmodifiedSince not matching, return 412.");
        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        return;
    }

    // Prepare and initialize response --------------------------------------------------------
    // Get content type by file name and content disposition.
    String contentType = getServletContext().getMimeType(fileName);
    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 content type is text, expand content type with the one and right character encoding.
    if (contentType.startsWith("text")) {
        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";
    }

    // Initialize response.
    response.reset();
    response.setBufferSize(bufferSize);
    response.setHeader("Content-Disposition", disposition + ";filename=\"" + fileName + "\"");
    response.setHeader("Accept-Ranges", "bytes");
    response.setHeader("ETag", eTag);
    response.setDateHeader("Last-Modified", lastModified);
    response.setDateHeader("Expires", expires);

    // Send requested file (part(s)) to client ------------------------------------------------
    // Prepare streams.
    FileInputStream input = null;
    OutputStream output = null;

    if (content) {
        logger.debug("Content requested,streaming.");
        // Open streams.
        input = new FileInputStream(file);
        output = response.getOutputStream();
        long streamed = stream(input, output, bufferSize);
        if (logger.isDebugEnabled()) {
            logger.debug("Bytes streamed:" + streamed);
        }
    }

}

From source file:net.sourceforge.vulcan.web.ProjectFileServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    final String pathInfo = request.getPathInfo();

    if (isBlank(pathInfo)) {
        response.sendRedirect(request.getContextPath());
        return;//ww w .  j  a v a2s.  co m
    }

    final PathInfo projPathInfo = getProjectNameAndBuildNumber(pathInfo);

    if (isBlank(projPathInfo.projectName)) {
        response.sendRedirect(request.getContextPath());
        return;
    }

    final ProjectConfigDto projectConfig;

    try {
        projectConfig = projectManager.getProjectConfig(projPathInfo.projectName);
    } catch (NoSuchProjectException e) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    final String requestURI = request.getRequestURI();

    if (projPathInfo.buildNumber < 0) {
        redirectWithBuildNumber(response, projPathInfo, requestURI);
        return;
    }

    final ProjectStatusDto buildOutcome = buildManager.getStatusByBuildNumber(projPathInfo.projectName,
            projPathInfo.buildNumber);

    if (buildOutcome == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND,
                "No such build " + projPathInfo.buildNumber + " for project Project.");
        return;
    }

    final String workDir;

    if (StringUtils.isNotBlank(buildOutcome.getWorkDir())) {
        workDir = buildOutcome.getWorkDir();
    } else {
        workDir = projectConfig.getWorkDir();
    }

    final File file = getFile(workDir, pathInfo, true);

    if (!file.exists()) {
        if (shouldFallback(request, workDir, file)) {
            response.sendRedirect(getFallbackParentPath(request, workDir));
            return;
        }
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    } else if (!file.canRead()) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    } else if (file.isDirectory()) {
        if (!pathInfo.endsWith("/")) {
            response.sendRedirect(requestURI + "/");
            return;
        }

        final File[] files = getDirectoryListing(file);

        request.setAttribute(Keys.DIR_PATH, pathInfo);
        request.setAttribute(Keys.FILE_LIST, files);

        request.getRequestDispatcher(Keys.FILE_LIST_VIEW).forward(request, response);
        return;
    }

    setContentType(request, response, pathInfo);

    final Date lastModifiedDate = new Date(file.lastModified());

    if (!checkModifiedSinceHeader(request, lastModifiedDate)) {
        response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }

    response.setStatus(HttpServletResponse.SC_OK);

    setLastModifiedDate(response, lastModifiedDate);

    response.setContentLength((int) file.length());

    final FileInputStream fis = new FileInputStream(file);
    final ServletOutputStream os = response.getOutputStream();

    sendFile(fis, os);
}

From source file:com.xpn.xwiki.web.DownloadActionTest.java

@Test
public void testIfModifiedSinceSame() throws XWikiException, IOException {
    final Date d = new Date();
    createAttachment(d, DEFAULT_FILE_NAME);
    setRequestExpectations(DEFAULT_URI, null, null, null, d.getTime());
    getMockery().checking(new Expectations() {
        {//from   w w w  .jav a 2 s .  c  om
            allowing(DownloadActionTest.this.response).setStatus(with(HttpServletResponse.SC_NOT_MODIFIED));
        }
    });
    Assert.assertNull(this.action.render(getContext()));
}

From source file:org.openmrs.module.patientnarratives.web.servlet.FileServlet.java

/**
 * Process the actual request./*from  w w  w. jav  a  2s . 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 ------------------------------------------------------------

    Integer videoObsId = Integer.parseInt(request.getParameter("obsId"));
    Obs complexObs = Context.getObsService().getComplexObs(videoObsId, OpenmrsConstants.RAW_VIEW);
    ComplexData complexData = complexObs.getComplexData();
    byte[] videoObjectData = ((byte[]) complexData.getData());

    String fileExt_file = complexData.getTitle();
    String arrFileExt[] = fileExt_file.split(" ");

    tempMergedVideoFile = createFile(arrFileExt[0]);
    String requestedFile = tempMergedVideoFile.getCanonicalPath();

    FileUtils.writeByteArrayToFile(new File(requestedFile), videoObjectData);

    // Check if file is actually supplied to the request URL.
    if (requestedFile == null) {
        // Do your thing if the file is not supplied to the request URL.
        // Throw an exception, or send 404, or show default/warning page, or just ignore it.
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // URL-decode the file name (might contain spaces and on) and prepare file object.
    File file = new File(requestedFile);

    // Check if file actually exists in filesystem.
    if (!file.exists()) {
        // Do your thing if the file appears to be non-existing.
        // Throw an exception, or send 404, or show default/warning page, or just ignore it.
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // Prepare some variables. The ETag is an unique identifier of the file.
    String fileName = file.getName();
    long length = file.length();
    long lastModified = file.lastModified();
    String eTag = fileName + "_" + length + "_" + lastModified;
    long expires = System.currentTimeMillis() + DEFAULT_EXPIRE_TIME;

    // 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 (ifNoneMatch != null && matches(ifNoneMatch, eTag)) {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        response.setHeader("ETag", eTag); // Required in 304.
        response.setDateHeader("Expires", expires); // Postpone cache with 1 week.
        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.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        response.setHeader("ETag", eTag); // Required in 304.
        response.setDateHeader("Expires", expires); // Postpone cache with 1 week.
        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;
    }

    // Validate and process range -------------------------------------------------------------

    // Prepare some variables. The full Range represents the complete file.
    Range full = new Range(0, length - 1, length);
    List<Range> ranges = new ArrayList<Range>();

    // Validate and process Range and If-Range headers.
    String range = request.getHeader("Range");
    if (range != null) {

        // Range header should match format "bytes=n-n,n-n,n-n...". If not, then return 416.
        if (!range.matches("^bytes=\\d*-\\d*(,\\d*-\\d*)*$")) {
            response.setHeader("Content-Range", "bytes */" + length); // Required in 416.
            response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
            return;
        }

        // If-Range header should either match ETag or be greater then LastModified. If not,
        // then return full file.
        String ifRange = request.getHeader("If-Range");
        if (ifRange != null && !ifRange.equals(eTag)) {
            try {
                long ifRangeTime = request.getDateHeader("If-Range"); // Throws IAE if invalid.
                if (ifRangeTime != -1 && ifRangeTime + 1000 < lastModified) {
                    ranges.add(full);
                }
            } catch (IllegalArgumentException ignore) {
                ranges.add(full);
            }
        }

        // If any valid If-Range header, then process each part of byte range.
        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 = length - end;
                    end = length - 1;
                } else if (end == -1 || end > length - 1) {
                    end = length - 1;
                }

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

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

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

    // Get content type by file name and set default GZIP support and content disposition.
    String contentType = getServletContext().getMimeType(fileName);
    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 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.
    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";
    }

    // Initialize response.
    response.reset();
    response.setBufferSize(DEFAULT_BUFFER_SIZE);
    response.setHeader("Content-Disposition", disposition + ";filename=\"" + fileName + "\"");
    response.setHeader("Accept-Ranges", "bytes");
    response.setHeader("ETag", eTag);
    response.setDateHeader("Last-Modified", lastModified);
    response.setDateHeader("Expires", expires);

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

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

    try {
        // Open streams.
        input = new RandomAccessFile(file, "r");
        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);

            if (content) {
                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", String.valueOf(r.length));
                }

                // Copy full range.
                copy(input, output, 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.

            if (content) {
                // Copy single part range.
                copy(input, output, r.start, r.length);
            }

        } else {

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

            if (content) {
                // 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("--" + 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, r.start, r.length);
                }

                // End with multipart boundary.
                sos.println();
                sos.println("--" + MULTIPART_BOUNDARY + "--");
            }
        }
    } finally {
        // Gently close streams.
        close(output);
        close(input);
        tempMergedVideoFile.delete();
    }
}

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

public void testCachedResourceETag() throws IOException, ServletException {
    testEmptyCacheValidResource();//from www  .j a  v a  2s . c  o  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.getHeader(LessCssServlet.IF_NONE_MATCH)).andReturn(Hex.md5(_cssBytes));
    EasyMock.expect(_request.getParameter(LessCssServlet.CLEAR_CACHE)).andReturn(null);

    _response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);

    doReplay();

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

    doVerify();
}