Example usage for javax.servlet.http HttpServletResponse SC_PARTIAL_CONTENT

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

Introduction

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

Prototype

int SC_PARTIAL_CONTENT

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

Click Source Link

Document

Status code (206) indicating that the server has fulfilled the partial GET request for the resource.

Usage

From source file:com.newatlanta.appengine.datastore.CachingDatastoreService.java

@SuppressWarnings("unchecked")
private static void doWriteBehindTask(HttpServletRequest req, HttpServletResponse res) throws IOException {
    Object payload = null;/*from  w w  w  . ja v  a 2  s. c o  m*/
    try {
        payload = deserialize(req);
        if (payload == null) {
            return;
        }
    } catch (Exception e) {
        log.warning(e.toString());
        return;
    }
    MemcacheService memcache = getMemcacheService();
    List<Key> keys;
    if (payload instanceof Key) {
        keys = new ArrayList<Key>();
        keys.add((Key) payload);
        // delete flag that prevents multiple tasks from being queued
        memcache.delete(keyToString((Key) payload));
    } else if (payload instanceof List) {
        keys = (List) payload;
    } else {
        log.warning(payload.getClass().getName());
        return;
    }
    Map<String, Entity> entityMap = (Map) memcache.getAll((List) keys);
    if ((entityMap != null) && !entityMap.isEmpty()) {
        try {
            if (getDatastoreService().put(entityMap.values()).size() != entityMap.size()) {
                log.info("failed to write all entities - retrying");
                res.sendError(HttpServletResponse.SC_PARTIAL_CONTENT);
            }
        } catch (DatastoreTimeoutException e) { // retry task
            log.info(e.getMessage());
            res.sendError(HttpServletResponse.SC_REQUEST_TIMEOUT);
        } catch (ConcurrentModificationException e) { // retry task
            log.info(e.getMessage());
            res.sendError(HttpServletResponse.SC_CONFLICT);
        } catch (Exception e) { // don't retry
            log.warning(e.toString());
        }
    }
}

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

@Test
public void testFullRestRange() throws XWikiException, IOException {
    // This test expects the whole file
    final Date d = new Date();
    createAttachment(d, DEFAULT_FILE_NAME);
    setRequestExpectations(DEFAULT_URI, null, null, "bytes=0-", -1l);
    setResponseExpectations(d.getTime(), this.fileContent.length);
    setOutputExpectations(0, this.fileContent.length);
    getMockery().checking(new Expectations() {
        {/*from w  w w.  ja  v a  2s .  c om*/
            one(DownloadActionTest.this.response).setStatus(with(HttpServletResponse.SC_PARTIAL_CONTENT));
            one(DownloadActionTest.this.response).setHeader(with("Content-Range"),
                    with("bytes 0-13/" + DownloadActionTest.this.fileContent.length));
        }
    });
    Assert.assertNull(this.action.render(getContext()));
}

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

@Test
public void testTailRange() throws XWikiException, IOException {
    // This test expects the last four bytes (10, 11, 12 and 13) from the file
    final Date d = new Date();
    createAttachment(d, DEFAULT_FILE_NAME);
    setRequestExpectations(DEFAULT_URI, null, null, "bytes=-4", -1l);
    setResponseExpectations(d.getTime(), this.fileContent.length - 10);
    setOutputExpectations(10, this.fileContent.length);
    getMockery().checking(new Expectations() {
        {/* w w  w . ja v a2 s.  c  om*/
            one(DownloadActionTest.this.response).setStatus(with(HttpServletResponse.SC_PARTIAL_CONTENT));
            one(DownloadActionTest.this.response).setHeader(with("Content-Range"),
                    with("bytes 10-13/" + DownloadActionTest.this.fileContent.length));
        }
    });
    Assert.assertNull(this.action.render(getContext()));
}

From source file:org.springframework.web.servlet.resource.ResourceHttpRequestHandler.java

/**
 * Processes a resource request.//from   w w w . j  av  a2  s . co m
 * <p>Checks for the existence of the requested resource in the configured list of locations.
 * If the resource does not exist, a {@code 404} response will be returned to the client.
 * If the resource exists, the request will be checked for the presence of the
 * {@code Last-Modified} header, and its value will be compared against the last-modified
 * timestamp of the given resource, returning a {@code 304} status code if the
 * {@code Last-Modified} value  is greater. If the resource is newer than the
 * {@code Last-Modified} value, or the header is not present, the content resource
 * of the resource will be written to the response with caching headers
 * set to expire one year in the future.
 */
@Override
public void handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    // For very general mappings (e.g. "/") we need to check 404 first
    Resource resource = getResource(request);
    if (resource == null) {
        logger.trace("No matching resource found - returning 404");
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    if (HttpMethod.OPTIONS.matches(request.getMethod())) {
        response.setHeader("Allow", getAllowHeader());
        return;
    }

    // Supported methods and required session
    checkRequest(request);

    // Header phase
    if (new ServletWebRequest(request, response).checkNotModified(resource.lastModified())) {
        logger.trace("Resource not modified - returning 304");
        return;
    }

    // Apply cache settings, if any
    prepareResponse(response);

    // Check the media type for the resource
    MediaType mediaType = getMediaType(request, resource);
    if (mediaType != null) {
        if (logger.isTraceEnabled()) {
            logger.trace("Determined media type '" + mediaType + "' for " + resource);
        }
    } else {
        if (logger.isTraceEnabled()) {
            logger.trace("No media type found for " + resource + " - not sending a content-type header");
        }
    }

    // Content phase
    if (METHOD_HEAD.equals(request.getMethod())) {
        setHeaders(response, resource, mediaType);
        logger.trace("HEAD request - skipping content");
        return;
    }

    ServletServerHttpResponse outputMessage = new ServletServerHttpResponse(response);
    if (request.getHeader(HttpHeaders.RANGE) == null) {
        Assert.state(this.resourceHttpMessageConverter != null, "Not initialized");
        setHeaders(response, resource, mediaType);
        this.resourceHttpMessageConverter.write(resource, mediaType, outputMessage);
    } else {
        Assert.state(this.resourceRegionHttpMessageConverter != null, "Not initialized");
        response.setHeader(HttpHeaders.ACCEPT_RANGES, "bytes");
        ServletServerHttpRequest inputMessage = new ServletServerHttpRequest(request);
        try {
            List<HttpRange> httpRanges = inputMessage.getHeaders().getRange();
            response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
            this.resourceRegionHttpMessageConverter.write(HttpRange.toResourceRegions(httpRanges, resource),
                    mediaType, outputMessage);
        } catch (IllegalArgumentException ex) {
            response.setHeader("Content-Range", "bytes */" + resource.contentLength());
            response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
        }
    }
}

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

@Test
public void testFullTailRange() throws XWikiException, IOException {
    // This test expects the whole file
    final Date d = new Date();
    createAttachment(d, DEFAULT_FILE_NAME);
    setRequestExpectations(DEFAULT_URI, null, null, "bytes=-14", -1l);
    setResponseExpectations(d.getTime(), this.fileContent.length);
    setOutputExpectations(0, this.fileContent.length);
    getMockery().checking(new Expectations() {
        {//w w  w.ja  v  a 2  s  .  co  m
            one(DownloadActionTest.this.response).setStatus(with(HttpServletResponse.SC_PARTIAL_CONTENT));
            one(DownloadActionTest.this.response).setHeader(with("Content-Range"),
                    with("bytes 0-13/" + DownloadActionTest.this.fileContent.length));
        }
    });
    Assert.assertNull(this.action.render(getContext()));
}

From source file:de.digitalcollections.streaming.euphoria.controller.StreamingController.java

/**
 * Create response for the request.//from ww  w. j ava2s.  c o  m
 *
 * @param id The id of requested content.
 * @param extension The (target) file extension/format of requested content.
 * @param request The request to be responded to.
 * @param response The response to the request.
 * @param head "true" if response body should be written (GET) or "false" if not (HEAD).
 * @throws IOException If something fails at I/O level.
 */
private void respond(String id, String extension, HttpServletRequest request, HttpServletResponse response,
        boolean head) throws IOException {
    logRequestHeaders(request);

    response.reset();

    // try to get access to resource
    Resource resource;
    try {
        resource = getResource(id, extension);
    } catch (ResourceIOException ex) {
        LOGGER.warn("*** Response {}: Error referencing streaming resource with id {} and extension {}",
                HttpServletResponse.SC_NOT_FOUND, id, extension);
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // get resource metadata
    ResourceInfo resourceInfo = new ResourceInfo(id, resource);
    if (resourceInfo.length <= 0) {
        LOGGER.warn("*** Response {}: Error streaming resource with id {} and extension {}: not found/no size",
                HttpServletResponse.SC_NOT_FOUND, id, extension);
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    if (preconditionFailed(request, resourceInfo)) {
        LOGGER.warn(
                "*** Response {}: Precondition If-Match/If-Unmodified-Since failed for resource with id {} and extension {}.",
                HttpServletResponse.SC_PRECONDITION_FAILED, id, extension);
        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        return;
    }

    setCacheHeaders(response, resourceInfo);

    if (notModified(request, resourceInfo)) {
        LOGGER.debug("*** Response {}: 'Not modified'-response for resource with id {} and extension {}.",
                HttpServletResponse.SC_NOT_MODIFIED, id, extension);
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }

    List<Range> ranges = getRanges(request, resourceInfo);

    if (ranges == null) {
        response.setHeader("Content-Range", "bytes */" + resourceInfo.length);
        LOGGER.warn("Response {}: Header Range for resource with id {} and extension {} not satisfiable",
                HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE, id, extension);
        response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
        return;
    }

    if (!ranges.isEmpty()) {
        response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
    } else {
        ranges.add(new Range(0, resourceInfo.length - 1)); // Full content.
    }

    String contentType = setContentHeaders(request, response, resourceInfo, ranges);
    boolean acceptsGzip = false;
    // 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";
    }

    if (head) {
        return;
    }

    writeContent(response, resource, resourceInfo, ranges, contentType, acceptsGzip);
    LOGGER.debug("*** RESPONSE FINISHED ***");
}

From source file:hu.api.SivaPlayerVideoServlet.java

private void doAction(HttpServletRequest request, HttpServletResponse response, String requestType)
        throws ServletException, IOException {

    // Check if it's an AJAX request
    this.isAJAXRequest = (request.getParameter("ajax") != null && request.getParameter("ajax").equals("true"));

    // Allow Cross-Origin-Requests
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE, OPTIONS");
    response.setHeader("Access-Control-Max-Age", "1000");
    response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With");

    // URL pattern: /videoId
    // Get request parameter from URL and check if it has been set.
    // Show 400 if less or more parameters than allowed.
    String requestedVideo = request.getPathInfo();
    if (requestedVideo == null || requestedVideo.split("/").length < 2
            || requestedVideo.split("/")[1].equals("")) {
        this.sendError(response, HttpServletResponse.SC_BAD_REQUEST,
                "The video folder has to be specified for using this web service.");
        return;//  w  w w  . j a  va2s .  com
    }

    this.persistenceProvider = (IPersistenceProvider) getServletContext().getAttribute("PersistenceProvider");
    this.mailService = (MailService) getServletContext().getAttribute("mailService");
    this.brandingConfiguration = (BrandingConfiguration) getServletContext()
            .getAttribute("brandingConfiguration");

    // Check if it's a watching request
    if (request.getPathInfo().endsWith("/watch.html")) {
        this.providePlayer(request, response);
        return;
    }

    // Check if it's a log request and perform logging if so
    if (request.getPathInfo().endsWith("/log") && requestType.equals("POST")) {
        this.doLogging(request, response);
        return;
    }

    // Check if it's a checkSession request and provide session status if so
    if (requestedVideo.endsWith("/getStats.js")) {
        this.getStats(request, response);
        return;
    }

    // Check if user requests user secret and perform login
    if (request.getPathInfo().endsWith("/getSecret.js") && requestType.equals("POST")) {
        this.provideUserSecret(request, response, requestType);
        return;
    }

    // Check if current session exists and if it is allowed to access this
    // video, stop further execution, if so.
    boolean result = handleAccess(request, response, requestType);
    if (!result) {
        return;
    }

    // Check if it's collaboration request and provide data
    if (request.getPathInfo().endsWith("/getCollaboration.js")) {
        this.provideCollaboration(request, response);
        return;
    }

    // Check if it's a thread creation request
    if (request.getPathInfo().endsWith("/createCollaborationThread.js")) {
        this.createCollaborationThread(request, response);
        return;
    }

    // Check if it's a post creation request
    if (request.getPathInfo().endsWith("/createCollaborationPost.js")) {
        this.createCollaborationPost(request, response);
        return;
    }

    // Check if it's a post activation request
    if (request.getPathInfo().endsWith("/activateCollaborationPost.js")) {
        this.activateCollaborationPost(request, response);
        return;
    }

    // Check if it's a post creation request
    if (request.getPathInfo().endsWith("/deleteCollaborationThread.js")) {
        this.deleteCollaborationThread(request, response);
        return;
    }

    // Check if it's a post creation request
    if (request.getPathInfo().endsWith("/deleteCollaborationPost.js")) {
        this.deleteCollaborationPost(request, response);
        return;
    }

    // Check if it's a checkSession request and provide session status if so
    if (requestedVideo.endsWith("/checkSession.js")) {
        this.provideSessionStatus(request, response);
        return;
    }

    // Decode the file name from the URL and check if file actually exists
    // in
    // file system, send 404 if not
    File file = new File(videoPath, URLDecoder.decode(requestedVideo, "UTF-8"));
    if (!file.exists()) {
        this.sendError(response, HttpServletResponse.SC_NOT_FOUND, "File not found");
        return;
    }

    // Create log entry for file request
    this.logFileRequest(requestedVideo);

    // Check if configuration is requested and do needed preparing and
    // stop standard file preparation
    if (file.getName().equals("export.js")) {
        this.provideConfigFile(request, response, file);
        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 (requestType.equals("GET")) {
                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 (requestType.equals("GET")) {
                // 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 (requestType.equals("GET")) {
                // 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);
    }
}

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

@Test
public void testOverflowingTailRange() throws XWikiException, IOException {
    // This test expects the whole file, although the client requested more
    final Date d = new Date();
    createAttachment(d, DEFAULT_FILE_NAME);
    setRequestExpectations(DEFAULT_URI, null, null, "bytes=-40", -1l);
    setResponseExpectations(d.getTime(), this.fileContent.length);
    setOutputExpectations(0, this.fileContent.length);
    getMockery().checking(new Expectations() {
        {/*  w  w w.ja va 2 s.  co  m*/
            one(DownloadActionTest.this.response).setStatus(with(HttpServletResponse.SC_PARTIAL_CONTENT));
            one(DownloadActionTest.this.response).setHeader(with("Content-Range"),
                    with("bytes 0-13/" + DownloadActionTest.this.fileContent.length));
        }
    });
    Assert.assertNull(this.action.render(getContext()));
}

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

@Test
public void testValidOverflowingRange() throws XWikiException, IOException {
    // This test expects bytes 9, 10, 11, 12 and 13 from the file, although 14 and 15 are requested as well.
    final Date d = new Date();
    createAttachment(d, DEFAULT_FILE_NAME);
    setRequestExpectations(DEFAULT_URI, null, null, "bytes=9-15", -1l);
    setResponseExpectations(d.getTime(), this.fileContent.length - 9);
    setOutputExpectations(9, this.fileContent.length);
    getMockery().checking(new Expectations() {
        {/*from  w ww.j  a v a 2s  .c o  m*/
            one(DownloadActionTest.this.response).setStatus(with(HttpServletResponse.SC_PARTIAL_CONTENT));
            one(DownloadActionTest.this.response).setHeader(with("Content-Range"),
                    with("bytes 9-13/" + DownloadActionTest.this.fileContent.length));
        }
    });
    Assert.assertNull(this.action.render(getContext()));
}

From source file:org.orderofthebee.addons.support.tools.share.ContentStreamer.java

protected boolean processSingleRange(final Response res, final File file, final String range,
        final String mimetype) throws IOException {
    // return the specific set of bytes as requested in the content-range header

    /*//from  ww w  . jav a2  s  .  c  o  m
     * Examples of byte-content-range-spec values, assuming that the entity contains total of 1234 bytes:
     * The first 500 bytes:
     * bytes 0-499/1234
     * The second 500 bytes:
     * bytes 500-999/1234
     * All except for the first 500 bytes:
     * bytes 500-1233/1234
     */
    /*
     * 'Range' header example:
     * bytes=10485760-20971519
     */

    boolean processedRange = false;
    Range r = null;
    try {
        r = Range.constructRange(range, mimetype, file.length());
    } catch (final IllegalArgumentException err) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Failed to parse range header - returning 416 status code: " + err.getMessage());
        }

        res.setStatus(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
        res.setHeader(HEADER_CONTENT_RANGE, "\"*\"");
        res.getOutputStream().close();
        return true;
    }

    // set Partial Content status and range headers
    final String contentRange = "bytes " + Long.toString(r.start) + "-" + Long.toString(r.end) + "/"
            + Long.toString(file.length());

    res.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
    res.setContentType(mimetype);
    res.setHeader(HEADER_CONTENT_RANGE, contentRange);
    res.setHeader(HEADER_CONTENT_LENGTH, Long.toString((r.end - r.start) + 1L));

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Processing: Content-Range: " + contentRange);
    }

    InputStream is = null;
    try {
        // output the binary data for the range
        OutputStream os = null;
        os = res.getOutputStream();
        is = new FileInputStream(file);

        this.streamRangeBytes(r, is, os, 0L);

        os.close();
        processedRange = true;
    } catch (final IOException err) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Unable to process single range due to IO Exception: " + err.getMessage());
        }
        throw err;
    } finally {
        if (is != null) {
            is.close();
        }
    }

    return processedRange;
}