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:org.apache.openmeetings.web.util.RecordingResourceReference.java

@Override
public IResource getResource() {
    return new AbstractResource() {
        private static final long serialVersionUID = 1L;
        private final static String ACCEPT_RANGES_HEADER = "Accept-Ranges";
        private final static String RANGE_HEADER = "Range";
        private final static String CONTENT_RANGE_HEADER = "Content-Range";
        private final static String RANGES_BYTES = "bytes";
        private File file;
        private boolean isRange = false;
        private long start = 0;
        private long end = 0;

        private long getChunkLength() {
            return isRange ? end - start + 1 : (file == null ? -1 : file.length());
        }/*  www .j  a  va 2  s.c o  m*/

        private IResourceStream getResourceStream() {
            return file == null ? null : new FileResourceStream(file) {
                private static final long serialVersionUID = 2546785247219805747L;
                private transient BoundedInputStream bi;

                @Override
                public InputStream getInputStream() throws ResourceStreamNotFoundException {
                    if (bi == null) {
                        //bi = new BoundedInputStream(super.getInputStream(), end + 1);
                        bi = new BoundedInputStream(super.getInputStream(),
                                isRange ? end + 1 : (file == null ? -1 : file.length()));
                        try {
                            bi.skip(start);
                        } catch (IOException e) {
                            throw new ResourceStreamNotFoundException(e);
                        }
                    }
                    return bi;
                }

                @Override
                public Bytes length() {
                    return Bytes.bytes(getChunkLength());
                }

                @Override
                public void close() throws IOException {
                    if (bi != null) {
                        bi.close(); //also will close original stream
                        bi = null;
                    }
                }

                @Override
                public String getContentType() {
                    return RecordingResourceReference.this.getContentType();
                }
            };
        }

        @Override
        protected void setResponseHeaders(ResourceResponse data, Attributes attributes) {
            Response response = attributes.getResponse();
            if (response instanceof WebResponse) {
                WebResponse webResponse = (WebResponse) response;
                webResponse.setStatus(
                        isRange ? HttpServletResponse.SC_PARTIAL_CONTENT : HttpServletResponse.SC_OK);
            }
            super.setResponseHeaders(data, attributes);
        }

        @Override
        protected ResourceResponse newResourceResponse(Attributes attributes) {
            ResourceResponse rr = new ResourceResponse();
            FlvRecording r = getRecording(attributes);
            if (r != null) {
                isRange = false;
                file = getFile(r);
                rr.setFileName(getFileName(r));
                rr.setContentType(RecordingResourceReference.this.getContentType());
                rr.setContentDisposition(ContentDisposition.INLINE);
                rr.setLastModified(Time.millis(file.lastModified()));
                rr.getHeaders().addHeader(ACCEPT_RANGES_HEADER, RANGES_BYTES);
                String range = ((HttpServletRequest) attributes.getRequest().getContainerRequest())
                        .getHeader(RANGE_HEADER);
                if (range != null && range.startsWith(RANGES_BYTES)) {
                    String[] bounds = range.substring(RANGES_BYTES.length() + 1).split("-");
                    if (bounds != null && bounds.length > 0) {
                        long length = file.length();
                        isRange = true;
                        start = Long.parseLong(bounds[0]);
                        end = bounds.length > 1 ? Long.parseLong(bounds[1]) : length - 1;
                        //Content-Range: bytes 229376-232468/232469
                        rr.getHeaders().addHeader(CONTENT_RANGE_HEADER,
                                String.format("%s %d-%d/%d", RANGES_BYTES, start, end, length));
                    }
                }
                rr.setContentLength(getChunkLength());
                rr.setWriteCallback(new WriteCallback() {
                    @Override
                    public void writeData(Attributes attributes) throws IOException {
                        IResourceStream rStream = getResourceStream();
                        try {
                            writeStream(attributes, rStream.getInputStream());
                        } catch (ResourceStreamNotFoundException e1) {
                        } catch (ResponseIOException e) {
                            // in case of range operations we expecting such exceptions
                            if (!isRange) {
                                log.error("Error while playing the stream", e);
                            }
                        } finally {
                            rStream.close();
                        }
                    }
                });
            } else {
                rr.setError(HttpServletResponse.SC_NOT_FOUND);
            }
            return rr;
        }
    };
}

From source file:org.nuxeo.ecm.platform.ui.web.download.BlobDownloadServlet.java

void downloadBlob(HttpServletRequest req, HttpServletResponse resp, Blob blob, String fileName)
        throws IOException, ServletException {
    InputStream in = blob.getStream();
    OutputStream out = resp.getOutputStream();
    try {//from  w  w  w. j  a  v  a  2  s  .c  o m

        if (fileName == null || fileName.length() == 0) {
            if (blob.getFilename() != null && blob.getFilename().length() > 0) {
                fileName = blob.getFilename();
            } else {
                fileName = "file";
            }
        }

        resp.setHeader("Content-Disposition", ServletHelper.getRFC2231ContentDisposition(req, fileName));
        resp.setContentType(blob.getMimeType());

        long fileSize = blob.getLength();
        if (fileSize > 0) {
            String range = req.getHeader("Range");
            ByteRange byteRange = null;
            if (range != null) {
                try {
                    byteRange = parseRange(range, fileSize);
                } catch (ClientException e) {
                    log.error(e.getMessage(), e);
                }
            }
            if (byteRange != null) {
                resp.setHeader("Accept-Ranges", "bytes");
                resp.setHeader("Content-Range",
                        "bytes " + byteRange.getStart() + "-" + byteRange.getEnd() + "/" + fileSize);
                long length = byteRange.getLength();
                if (length < Integer.MAX_VALUE) {
                    resp.setContentLength((int) length);
                }
                resp.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
                writeStream(in, out, byteRange);
            } else {
                if (fileSize < Integer.MAX_VALUE) {
                    resp.setContentLength((int) fileSize);
                }
                writeStream(in, out, new ByteRange(0, fileSize - 1));
            }
        }

    } catch (IOException ioe) {
        handleClientDisconnect(ioe);
    } catch (Exception e) {
        throw new ServletException(e);
    } finally {
        if (resp != null) {
            try {
                resp.flushBuffer();
            } catch (IOException ioe) {
                handleClientDisconnect(ioe);
            }
        }
        if (in != null) {
            in.close();
        }
    }
}

From source file:com.zlfun.framework.misc.UploadUtils.java

public static boolean download(HttpServletRequest request, HttpServletResponse response, String uuid) {

    InputStream bis;// w  w  w  .  j a  v  a2  s . c  om
    boolean ret = false;
    try {

        byte[] voiceData = FsUtils.readFromDisk(uuid);
        if (voiceData != null) {
            long p = 0L;
            long toLength = 0L;
            long contentLength = 0L;
            int rangeSwitch = 0; // 0,1,?bytes=27000-2,???bytes=27000-39000
            long fileLength;
            String rangBytes = "";
            fileLength = voiceData.length;

            // get file content
            bis = new ByteArrayInputStream(voiceData);

            // tell the client to allow accept-ranges
            response.reset();
            response.setHeader("Accept-Ranges", "bytes");

            // client requests a file block download start byte
            String range = request.getHeader("Range");
            if (range != null && range.trim().length() > 0 && !"null".equals(range)) {
                response.setStatus(javax.servlet.http.HttpServletResponse.SC_PARTIAL_CONTENT);
                rangBytes = range.replaceAll("bytes=", "");
                if (rangBytes.endsWith("-")) { // bytes=270000-
                    rangeSwitch = 1;
                    p = Long.parseLong(rangBytes.substring(0, rangBytes.indexOf("-")));
                    contentLength = fileLength - p; // 270000?bytes270000
                } else { // bytes=270000-320000
                    rangeSwitch = 2;
                    String temp1 = rangBytes.substring(0, rangBytes.indexOf("-"));
                    String temp2 = rangBytes.substring(rangBytes.indexOf("-") + 1, rangBytes.length());
                    p = Long.parseLong(temp1);
                    toLength = Long.parseLong(temp2);
                    contentLength = toLength - p + 1; // 
                    // 270000-320000
                    // 
                }
            } else {
                contentLength = fileLength;
            }

            // Content-Length?????
            // Content-Length: [?] - [?]
            response.setHeader("Content-Length", new Long(contentLength).toString());

            // 
            // ??:
            // Content-Range: bytes [?]-[? - 1]/[?]
            if (rangeSwitch == 1) {
                String contentRange = new StringBuffer("bytes ").append(new Long(p).toString()).append("-")
                        .append(new Long(fileLength - 1).toString()).append("/")
                        .append(new Long(fileLength).toString()).toString();
                response.setHeader("Content-Range", contentRange);
                bis.skip(p);
            } else if (rangeSwitch == 2) {
                String contentRange = range.replace("=", " ") + "/" + new Long(fileLength).toString();
                response.setHeader("Content-Range", contentRange);
                bis.skip(p);
            } else {
                String contentRange = new StringBuffer("bytes ").append("0-").append(fileLength - 1).append("/")
                        .append(fileLength).toString();
                response.setHeader("Content-Range", contentRange);
            }

            response.setContentType("application/octet-stream");
            response.addHeader("Content-Disposition", getContentDisposition(request, uuid));

            OutputStream out = response.getOutputStream();

            int n = 0;
            long readLength = 0;
            int bsize = 1024;
            byte[] bytes = new byte[bsize];
            if (rangeSwitch == 2) {
                //  bytes=27000-39000 27000?
                while (readLength <= contentLength - bsize) {
                    n = bis.read(bytes);
                    readLength += n;
                    out.write(bytes, 0, n);
                }
                if (readLength <= contentLength) {
                    n = bis.read(bytes, 0, (int) (contentLength - readLength));
                    out.write(bytes, 0, n);
                }
            } else {
                while ((n = bis.read(bytes)) != -1) {
                    out.write(bytes, 0, n);
                }
            }
            out.flush();
            out.close();
            bis.close();
            return true;
        } else {
            return false;
        }
    } catch (IOException ex) {
        //  ClientAbortException 
        Logger.getLogger(UploadUtils.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    } catch (Exception ex) {
        Logger.getLogger(UploadUtils.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    }

}

From source file:com.enonic.cms.framework.util.HttpServletRangeUtilTest.java

@Test
public void test_process_request_multipart_zero_to_zero() throws Exception {
    final MockHttpServletRequest httpServletRequest = new MockHttpServletRequest();
    httpServletRequest.setMethod("GET");
    httpServletRequest.setPathInfo("/input.dat");
    httpServletRequest.addHeader(HttpHeaders.RANGE, "bytes=0-0,-1");

    final MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse();
    HttpServletRangeUtil.processRequest(httpServletRequest, mockHttpServletResponse, "input.dat",
            "application/pdf", INPUT_FILE, false);

    assertEquals(readFromFile("response1.dat"), mockHttpServletResponse.getContentAsString());

    assertEquals(HttpServletResponse.SC_PARTIAL_CONTENT, mockHttpServletResponse.getStatus());
    assertEquals("multipart/byteranges; boundary=THIS_STRING_SEPARATES",
            mockHttpServletResponse.getContentType());
    assertEquals("attachment;filename=\"input.dat\"",
            mockHttpServletResponse.getHeader(HttpHeaders.CONTENT_DISPOSITION));

}

From source file:net.sourceforge.subsonic.controller.StreamController.java

public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {

    TransferStatus status = null;/*from ww  w  .  j av a  2  s.c o  m*/
    PlaylistInputStream in = null;
    Player player = playerService.getPlayer(request, response, false, true);
    User user = securityService.getUserByName(player.getUsername());

    try {

        if (!user.isStreamRole()) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN,
                    "Streaming is forbidden for user " + user.getUsername());
            return null;
        }

        // If "playlist" request parameter is set, this is a Podcast request. In that case, create a separate
        // playlist (in order to support multiple parallel Podcast streams).
        String playlistName = request.getParameter("playlist");
        boolean isPodcast = playlistName != null;
        if (isPodcast) {
            Playlist playlist = new Playlist();
            playlistService.loadPlaylist(playlist, playlistName);
            player.setPlaylist(playlist);
            Util.setContentLength(response, playlist.length());
            LOG.info("Incoming Podcast request for playlist " + playlistName);
        }

        String contentType = StringUtil.getMimeType(request.getParameter("suffix"));
        response.setContentType(contentType);

        String preferredTargetFormat = request.getParameter("format");
        Integer maxBitRate = ServletRequestUtils.getIntParameter(request, "maxBitRate");
        if (Integer.valueOf(0).equals(maxBitRate)) {
            maxBitRate = null;
        }

        VideoTranscodingSettings videoTranscodingSettings = null;

        // Is this a request for a single file (typically from the embedded Flash player)?
        // In that case, create a separate playlist (in order to support multiple parallel streams).
        // Also, enable partial download (HTTP byte range).
        MediaFile file = getSingleFile(request);
        boolean isSingleFile = file != null;
        LongRange range = null;

        if (isSingleFile) {
            Playlist playlist = new Playlist();
            playlist.addFiles(true, file);
            player.setPlaylist(playlist);

            if (!file.isVideo()) {
                response.setIntHeader("ETag", file.getId());
                response.setHeader("Accept-Ranges", "bytes");
            }

            TranscodingService.Parameters parameters = transcodingService.getParameters(file, player,
                    maxBitRate, preferredTargetFormat, videoTranscodingSettings);
            long fileLength = getFileLength(parameters);
            boolean isConversion = parameters.isDownsample() || parameters.isTranscode();
            boolean estimateContentLength = ServletRequestUtils.getBooleanParameter(request,
                    "estimateContentLength", false);

            range = getRange(request, file);
            if (range != null) {
                LOG.info("Got range: " + range);
                response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
                Util.setContentLength(response, fileLength - range.getMinimumLong());
                long firstBytePos = range.getMinimumLong();
                long lastBytePos = fileLength - 1;
                response.setHeader("Content-Range",
                        "bytes " + firstBytePos + "-" + lastBytePos + "/" + fileLength);
            } else if (!isConversion || estimateContentLength) {
                Util.setContentLength(response, fileLength);
            }

            String transcodedSuffix = transcodingService.getSuffix(player, file, preferredTargetFormat);
            response.setContentType(StringUtil.getMimeType(transcodedSuffix));

            if (file.isVideo()) {
                videoTranscodingSettings = createVideoTranscodingSettings(file, request);
            }
        }

        if (request.getMethod().equals("HEAD")) {
            return null;
        }

        // Terminate any other streams to this player.
        if (!isPodcast && !isSingleFile) {
            for (TransferStatus streamStatus : statusService.getStreamStatusesForPlayer(player)) {
                if (streamStatus.isActive()) {
                    streamStatus.terminate();
                }
            }
        }

        status = statusService.createStreamStatus(player);

        in = new PlaylistInputStream(player, status, maxBitRate, preferredTargetFormat,
                videoTranscodingSettings, transcodingService, audioScrobblerService, mediaFileService,
                searchService);
        OutputStream out = RangeOutputStream.wrap(response.getOutputStream(), range);

        // Enabled SHOUTcast, if requested.
        boolean isShoutCastRequested = "1".equals(request.getHeader("icy-metadata"));
        if (isShoutCastRequested && !isSingleFile) {
            response.setHeader("icy-metaint", "" + ShoutCastOutputStream.META_DATA_INTERVAL);
            response.setHeader("icy-notice1", "This stream is served using Subsonic");
            response.setHeader("icy-notice2", "Subsonic - Free media streamer - subsonic.org");
            response.setHeader("icy-name", "Subsonic");
            response.setHeader("icy-genre", "Mixed");
            response.setHeader("icy-url", "http://subsonic.org/");
            out = new ShoutCastOutputStream(out, player.getPlaylist(), settingsService);
        }

        final int BUFFER_SIZE = 2048;
        byte[] buf = new byte[BUFFER_SIZE];

        while (true) {

            // Check if stream has been terminated.
            if (status.terminated()) {
                return null;
            }

            if (player.getPlaylist().getStatus() == Playlist.Status.STOPPED) {
                if (isPodcast || isSingleFile) {
                    break;
                } else {
                    sendDummy(buf, out);
                }
            } else {

                int n = in.read(buf);
                if (n == -1) {
                    if (isPodcast || isSingleFile) {
                        break;
                    } else {
                        sendDummy(buf, out);
                    }
                } else {
                    out.write(buf, 0, n);
                }
            }
        }

    } finally {
        if (status != null) {
            securityService.updateUserByteCounts(user, status.getBytesTransfered(), 0L, 0L);
            statusService.removeStreamStatus(status);
        }
        IOUtils.closeQuietly(in);
    }
    return null;
}

From source file:net.ymate.platform.webmvc.view.impl.BinaryView.java

private void __doSetRangeHeader(HttpServletResponse response, PairObject<Long, Long> range) {
    // none???/*  w ww  .j  a  v a 2 s.co  m*/
    addHeader("Accept-Ranges", "bytes");
    // Content-Length: [?] - [?]
    long _totalLength = range.getValue() - range.getKey();
    addHeader("Content-Length", _totalLength + "");
    // Content-Range: bytes [?]-[? - 1]/[?]
    addHeader("Content-Range", "bytes " + range.getKey() + "-" + (range.getValue() - 1) + "/" + __length);
    // response.setHeader("Connection", "Close"); //??IE
    // Status: 206
    response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
}

From source file:com.meltmedia.cadmium.servlets.BasicFileServlet.java

public void processRequest(FileRequestContext context) throws ServletException, IOException {
    try {/*from  www. j  ava2s. co  m*/
        // Find the file to serve in the file system.  This may redirect for welcome files or send 404 responses.
        if (locateFileToServe(context))
            return;

        // Handle any conditional headers that may be present.
        if (handleConditions(context))
            return;

        // Sets the content type header.
        resolveContentType(context);

        // Sets compress if Accept-Encoding allows for gzip or identity
        if (checkAccepts(context))
            return;

        try {
            if (context.file != null) {
                context.response.setHeader(CONTENT_DISPOSITION_HEADER,
                        "inline;filename=\"" + context.file.getName() + "\"");
            }
            context.response.setHeader(ACCEPT_RANGES_HEADER, "bytes");
            if (context.eTag != null) {
                context.response.setHeader(ETAG_HEADER, context.eTag);
            }
            context.response.setDateHeader(LAST_MODIFIED_HEADER, lastUpdated);
            if (!context.ranges.isEmpty()) {
                context.response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
                String rangeBoundary = RANGE_BOUNDARY + UUID.randomUUID().toString();
                if (context.ranges.size() > 1) {
                    context.response.setContentType("multipart/byteranges; boundary=" + rangeBoundary);
                    context.response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);

                    if (context.sendEntity) {
                        context.in = new FileInputStream(context.file);
                        context.out = context.response.getOutputStream();
                        ServletOutputStream sout = (ServletOutputStream) context.out;
                        for (Range r : context.ranges) {
                            sout.println();
                            sout.println("--" + rangeBoundary);
                            sout.println("Content-Type: " + context.contentType);
                            sout.println("Context-Range: bytes " + r.start + "-" + r.end + "/"
                                    + context.file.length());

                            copyPartialContent(context.in, context.out, r);
                        }

                        sout.println();
                        sout.println("--" + rangeBoundary + "--");
                    }
                } else {
                    Range r = context.ranges.get(0);
                    context.response.setContentType(context.contentType);
                    Long rangeLength = calculateRangeLength(context, r);
                    context.response.setHeader(CONTENT_RANGE_HEADER,
                            "bytes " + r.start + "-" + r.end + "/" + context.file.length());
                    if (context.sendEntity) {
                        context.in = new FileInputStream(context.file);
                        context.out = context.response.getOutputStream();

                        context.response.setHeader(CONTENT_LENGTH_HEADER, rangeLength.toString());

                        copyPartialContent(context.in, context.out, r);
                    }
                }
            } else {
                context.response.setStatus(HttpServletResponse.SC_OK);
                context.response.setContentType(context.contentType);

                if (context.sendEntity) {
                    context.response.setHeader(CONTENT_RANGE_HEADER,
                            "bytes 0-" + context.file.length() + "/" + context.file.length());
                    context.in = new FileInputStream(context.file);
                    context.out = context.response.getOutputStream();
                    if (context.compress) {

                        context.response.setHeader(CONTENT_ENCODING_HEADER, "gzip");
                        context.out = new GZIPOutputStream(context.out);

                    } else
                        context.response.setHeader(CONTENT_LENGTH_HEADER,
                                new Long(context.file.length()).toString());

                    IOUtils.copy(context.in, context.out);
                }
            }
        } finally {
            IOUtils.closeQuietly(context.in);
            IOUtils.closeQuietly(context.out);
        }
    } catch (IOException ioe) {
        logger.error("Received an IOException serving request: " + context.path, ioe);
        throw ioe;
    } catch (Throwable t) {
        logger.error("Failed to serve request: " + context.path, t);
        throw new ServletException(t);
    }
}

From source file:org.madsonic.controller.StreamController.java

public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {

    TransferStatus status = null;//w w  w .ja va  2  s  .c om
    PlayQueueInputStream in = null;
    Player player = playerService.getPlayer(request, response, false, true);
    User user = securityService.getUserByName(player.getUsername());

    try {

        if (!user.isStreamRole()) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN,
                    "Streaming is forbidden for user " + user.getUsername());
            return null;
        }

        // If "playlist" request parameter is set, this is a Podcast request. In that case, create a separate
        // play queue (in order to support multiple parallel Podcast streams).
        Integer playlistId = ServletRequestUtils.getIntParameter(request, "playlist");
        boolean isPodcast = playlistId != null;
        if (isPodcast) {
            PlayQueue playQueue = new PlayQueue();
            playQueue.addFiles(false, playlistService.getFilesInPlaylist(playlistId));
            player.setPlayQueue(playQueue);
            Util.setContentLength(response, playQueue.length());
            LOG.info("Incoming Podcast request for playlist " + playlistId);
        }

        response.addHeader("Access-Control-Allow-Origin", "*");

        String contentType = StringUtil.getMimeType(request.getParameter("suffix"));

        //            if (player.isWeb()) {
        //               contentType = StringUtil.getMimeType("mp3");
        //            }

        response.setContentType(contentType);

        String preferredTargetFormat = request.getParameter("format");
        Integer maxBitRate = ServletRequestUtils.getIntParameter(request, "maxBitRate");
        if (Integer.valueOf(0).equals(maxBitRate)) {
            maxBitRate = null;
        }

        VideoTranscodingSettings videoTranscodingSettings = null;

        // Is this a request for a single file (typically from the embedded Flash player)?
        // In that case, create a separate playlist (in order to support multiple parallel streams).
        // Also, enable partial download (HTTP byte range).
        MediaFile file = getSingleFile(request);
        boolean isSingleFile = file != null;
        HttpRange range = null;

        if (isSingleFile) {
            PlayQueue playQueue = new PlayQueue();
            playQueue.addFiles(true, file);
            player.setPlayQueue(playQueue);

            if (!file.isVideo()) {
                response.setIntHeader("ETag", file.getId());
                response.setHeader("Accept-Ranges", "bytes");
            }

            TranscodingService.Parameters parameters = transcodingService.getParameters(file, player,
                    maxBitRate, preferredTargetFormat, null, false);
            long fileLength = getFileLength(parameters);
            boolean isConversion = parameters.isDownsample() || parameters.isTranscode();
            boolean estimateContentLength = ServletRequestUtils.getBooleanParameter(request,
                    "estimateContentLength", false);
            boolean isHls = ServletRequestUtils.getBooleanParameter(request, "hls", false);

            range = getRange(request, file);
            if (range != null) {
                LOG.info("Got HTTP range: " + range);
                response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
                Util.setContentLength(response,
                        range.isClosed() ? range.size() : fileLength - range.getFirstBytePos());
                long lastBytePos = range.getLastBytePos() != null ? range.getLastBytePos() : fileLength - 1;
                response.setHeader("Content-Range",
                        "bytes " + range.getFirstBytePos() + "-" + lastBytePos + "/" + fileLength);
            } else if (!isHls && (!isConversion || estimateContentLength)) {
                Util.setContentLength(response, fileLength);
            }

            if (isHls) {
                response.setContentType(StringUtil.getMimeType("ts")); // HLS is always MPEG TS.
            } else {

                String transcodedSuffix = transcodingService.getSuffix(player, file, preferredTargetFormat);

                //                    if (player.isWeb()) {
                //                       transcodedSuffix = "mp3";
                //                    }
                response.setContentType(StringUtil.getMimeType(transcodedSuffix));
                setContentDuration(response, file);
            }

            if (file.isVideo() || isHls) {
                videoTranscodingSettings = createVideoTranscodingSettings(file, request);
            }
        }

        if (request.getMethod().equals("HEAD")) {
            return null;
        }

        // Terminate any other streams to this player.
        if (!isPodcast && !isSingleFile) {
            for (TransferStatus streamStatus : statusService.getStreamStatusesForPlayer(player)) {
                if (streamStatus.isActive()) {
                    streamStatus.terminate();
                }
            }
        }

        status = statusService.createStreamStatus(player);

        in = new PlayQueueInputStream(player, status, maxBitRate, preferredTargetFormat,
                videoTranscodingSettings, transcodingService, audioScrobblerService, mediaFileService,
                searchService);
        OutputStream out = RangeOutputStream.wrap(response.getOutputStream(), range);

        // Enabled SHOUTcast, if requested.
        boolean isShoutCastRequested = "1".equals(request.getHeader("icy-metadata"));
        if (isShoutCastRequested && !isSingleFile) {
            response.setHeader("icy-metaint", "" + ShoutCastOutputStream.META_DATA_INTERVAL);
            response.setHeader("icy-notice1", "This stream is served using Madsonic");
            response.setHeader("icy-notice2", "Madsonic - Free media streamer - madsonic.org");
            response.setHeader("icy-name", "Madsonic");
            response.setHeader("icy-genre", "Mixed");
            response.setHeader("icy-url", "http://madsonic.org/");
            out = new ShoutCastOutputStream(out, player.getPlayQueue(), settingsService);
        }

        final int BUFFER_SIZE = 2048;
        byte[] buf = new byte[BUFFER_SIZE];

        while (true) {

            // Check if stream has been terminated.
            if (status.terminated()) {
                return null;
            }

            if (player.getPlayQueue().getStatus() == PlayQueue.Status.STOPPED) {
                if (isPodcast || isSingleFile) {
                    break;
                } else {
                    sendDummy(buf, out);
                }
            } else {

                int n = in.read(buf);
                if (n == -1) {
                    if (isPodcast || isSingleFile) {
                        break;
                    } else {
                        sendDummy(buf, out);
                    }
                } else {
                    out.write(buf, 0, n);
                }
            }
        }

    } finally {
        if (status != null) {
            securityService.updateUserByteCounts(user, status.getBytesTransfered(), 0L, 0L);
            statusService.removeStreamStatus(status);
        }
        IOUtils.closeQuietly(in);
    }
    return null;
}

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

private static void serveFullResource(HttpServletRequest httpReq, HttpServletResponse httpResp,
        MediaResource mr) {//from   w w  w  .  java 2s  .com
    boolean debug = log.isDebug();

    InputStream in = null;
    OutputStream out = null;
    BufferedInputStream bis = null;

    try {
        Long size = mr.getSize();
        Long lastModified = mr.getLastModified();

        //fxdiff FXOLAT-118: accept range to deliver videos for iPad (implementation based on Tomcat)
        List<Range> ranges = parseRange(httpReq, httpResp,
                (lastModified == null ? -1 : lastModified.longValue()), (size == null ? 0 : size.longValue()));
        if (ranges != null && mr.acceptRanges()) {
            httpResp.setHeader("Accept-Ranges", "bytes");
        }
        // maybe some more preparations
        mr.prepare(httpResp);

        in = mr.getInputStream();

        // serve the Resource
        if (in != null) {
            long rstart = 0;
            if (debug) {
                rstart = System.currentTimeMillis();
            }

            if (Settings.isDebuging()) {
                SlowBandWidthSimulator sbs = Windows
                        .getWindows(CoreSpringFactory.getImpl(UserSessionManager.class).getUserSession(httpReq))
                        .getSlowBandWidthSimulator();
                out = sbs.wrapOutputStream(httpResp.getOutputStream());
            } else {
                out = httpResp.getOutputStream();
            }

            if (ranges != null && ranges.size() == 1) {

                Range range = ranges.get(0);
                httpResp.addHeader("Content-Range",
                        "bytes " + range.start + "-" + range.end + "/" + range.length);
                long length = range.end - range.start + 1;
                if (length < Integer.MAX_VALUE) {
                    httpResp.setContentLength((int) length);
                } else {
                    // Set the content-length as String to be able to use a long
                    httpResp.setHeader("content-length", "" + length);
                }
                httpResp.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
                try {
                    httpResp.setBufferSize(2048);
                } catch (IllegalStateException e) {
                    // Silent catch
                }
                copy(out, in, range);
            } else {
                if (size != null) {
                    httpResp.setContentLength(size.intValue());
                }
                // buffer input stream
                bis = new BufferedInputStream(in);
                IOUtils.copy(bis, out);
            }

            if (debug) {
                long rstop = System.currentTimeMillis();
                log.debug("time to serve (mr=" + mr.getClass().getName() + ") "
                        + (size == null ? "n/a" : "" + size) + " bytes: " + (rstop - rstart));
            }
        }
    } catch (IOException e) {
        FileUtils.closeSafely(out);
        String className = e.getClass().getSimpleName();
        if ("ClientAbortException".equals(className)) {
            log.warn("client browser probably abort when serving media resource", e);
        } else {
            log.error("client browser probably abort when serving media resource", e);
        }
    } finally {
        IOUtils.closeQuietly(bis);
        IOUtils.closeQuietly(in);
    }
}

From source file:com.liferay.document.library.webserver.test.WebServerRangeTest.java

protected MockHttpServletResponse testRange(String rangeHeader) throws Exception {

    String fileName = "Test Range.txt";

    ServiceContext serviceContext = ServiceContextTestUtil.getServiceContext(group.getGroupId(),
            TestPropsValues.getUserId());

    FileEntry fileEntry = _dlAppLocalService.addFileEntry(TestPropsValues.getUserId(), group.getGroupId(),
            parentFolder.getFolderId(), fileName, ContentTypes.TEXT_PLAIN, _SAMPLE_DATA.getBytes(),
            serviceContext);/*from   w w  w.j a  v a2s  .c o m*/

    String path = fileEntry.getGroupId() + "/" + fileEntry.getFolderId() + "/" + fileEntry.getTitle();

    Map<String, String> headers = new HashMap<>();

    if (Validator.isNotNull(rangeHeader)) {
        headers.put(HttpHeaders.RANGE, rangeHeader);
    }

    MockHttpServletResponse mockHttpServletResponse = service(Method.GET, path, headers, null, null, null);

    int status = mockHttpServletResponse.getStatus();

    Assert.assertTrue(mockHttpServletResponse.containsHeader(HttpHeaders.ACCEPT_RANGES));

    if (Validator.isNotNull(rangeHeader)) {
        Assert.assertEquals(HttpServletResponse.SC_PARTIAL_CONTENT, status);
    } else {
        Assert.assertEquals(HttpServletResponse.SC_OK, status);
    }

    String contentType = mockHttpServletResponse.getContentType();

    if (Validator.isNotNull(rangeHeader) && rangeHeader.contains(StringPool.COMMA)) {

        Assert.assertTrue(contentType.startsWith("multipart/byteranges"));
    } else {
        Assert.assertEquals(ContentTypes.TEXT_PLAIN, contentType);
    }

    return mockHttpServletResponse;
}