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.beangle.web.io.SplitStreamDownloader.java

@Override
public void download(HttpServletRequest request, HttpServletResponse response, InputStream input, String name,
        String display) {/*from   w w w.j  av a2  s  .  co  m*/
    String attach = getAttachName(name, display);
    response.reset();
    addContent(request, response, attach);
    response.setHeader("Accept-Ranges", "bytes");
    response.setHeader("connection", "Keep-Alive");
    int length = 0;
    long start = 0L;
    long begin = 0L;
    long stop = 0L;
    StopWatch watch = new StopWatch();
    watch.start();
    try {
        length = input.available();
        stop = length - 1;
        response.setContentLength(length);
        String rangestr = request.getHeader("Range");
        if (null != rangestr) {
            String[] readlength = StringUtils.substringAfter(rangestr, "bytes=").split("-");
            start = Long.parseLong(readlength[0]);
            if (readlength.length > 1 && StringUtils.isNotEmpty(readlength[1])) {
                stop = Long.parseLong(readlength[1]);
            }
            if (start != 0) {
                response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
                String crange = "bytes " + start + "-" + stop + "/" + length;
                response.setHeader("Content-Range", crange);
            }
        }
        OutputStream output = response.getOutputStream();
        input.skip(start);
        begin = start;
        int size = 4 * 1024;
        byte[] buffer = new byte[size];
        for (int step = maxStep(start, stop, size); step > 0; step = maxStep(start, stop, size)) {
            int readed = input.read(buffer, 0, step);
            if (readed == -1)
                break;
            output.write(buffer, 0, readed);
            start += readed;
        }
    } catch (IOException e) {
    } catch (Exception e) {
        logger.warn("download file error " + attach, e);
    } finally {
        IOUtils.closeQuietly(input);
        if (logger.isDebugEnabled()) {
            String percent = null;
            if (length == 0) {
                percent = "100%";
            } else {
                percent = ((int) (((start - begin) * 1.0 / length) * 10000)) / 100.0f + "%";
            }
            long time = watch.getTime();
            int rate = 0;
            if (start - begin > 0) {
                rate = (int) (((start - begin) * 1.0 / time * 1000) / 1024);
            }
            logger.debug("{}({}-{}/{}) download {}[{}] in {} ms with {} KB/s",
                    array(attach, begin, stop, length, start - begin, percent, time, rate));
        }
    }
}

From source file:org.jaxygen.invoker.FileDeliveryHandler.java

private static void sendFilePartially(List<HttpRangeUtil.Range> ranges, final HttpServletResponse response,
        final Downloadable downloadable) throws IOException {
    final InputStream is = downloadable.getStream();
    final OutputStream os = response.getOutputStream();
    long pos = 0;
    HttpRangeUtil.Range range = ranges.get(0);
    HttpRangeUtil.Range normalizedRange = normalize(range, downloadable.contentSize());
    response.setHeader(HttpRangeUtil.HEADER_ACCEPT_RANGES, "bytes");
    response.setHeader(HttpRangeUtil.CONTENT_HEADER_RANGE,
            HttpRangeUtil.buildContentRange().setBegin(normalizedRange.getStart())
                    .setEnd(normalizedRange.getEnd()).setTotal(downloadable.contentSize()).toString());
    response.setHeader(HttpRangeUtil.HEADER_ETAG, downloadable.getETag());
    response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);

    sendPart(pos, normalizedRange, is, os);
}

From source file:org.scilla.util.PartialContentHandler.java

/**
 * Process servlet request.  Determine if request is a
 * request for partial content and write the needed headers
 * and status back to the client and write the request bytes
 * range.  If the request is not for partial content, just
 * write all data.//from   w  w  w  .jav  a  2 s .  co m
 * @param request HTTP request object
 * @param response HTTP response object
 * @param in stream to read data from
 * @param len length of data to be write or <tt>-1</tt> if unknown,
 * in which case partial content request are handled as normal requests
 * @throws IOException when reading or writing fails
 */
public static void process(HttpServletRequest request, HttpServletResponse response, InputStream in, long len)
        throws IOException {
    OutputStream out = response.getOutputStream();

    // can only do partial content when length is unknown
    if (len != -1) {
        String rangeHeader = request.getHeader(RANGE_HEADER);
        // was partial content requested?
        if (rangeHeader != null && rangeHeader.startsWith(BYTE_RANGE)) {
            String byteSpec = rangeHeader.substring(BYTE_RANGE.length());
            int sepPos = byteSpec.indexOf('-');
            // does the byte spec describe a range?
            if (sepPos != -1) {
                long offset = 0;
                long endpoint = -1;

                // determine offset
                if (sepPos > 0) {
                    String s = byteSpec.substring(0, sepPos).trim();
                    offset = Integer.parseInt(s);
                }
                // determine endpoint
                if (sepPos != byteSpec.length() - 1) {
                    String s = byteSpec.substring(sepPos + 1).trim();
                    endpoint = Integer.parseInt(s);
                } else {
                    endpoint = len - 1;
                }

                // notify receiver this is partial content
                response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
                String contentRange = BYTES_UNIT + " " + offset + "-" + endpoint + "/" + len;
                response.setHeader(CONTENT_RANGE_HEADER, contentRange);
                log.debug("send range header: " + CONTENT_RANGE_HEADER + ": " + contentRange);
                response.setContentLength((int) (endpoint - offset + 1));

                // skip till offset
                if (offset > 0) {
                    in.skip(offset);
                }

                // write partial data
                int n;
                byte[] b = new byte[BUFFER_SIZE];
                while ((n = in.read(b)) != -1) {
                    if (endpoint != -1) {
                        if (offset + n > endpoint) {
                            n = (int) (endpoint - offset) + 1;
                            if (n > 0) {
                                out.write(b, 0, n);
                            }
                            break;
                        }
                        offset += n;
                    }
                    out.write(b, 0, n);
                }

                // done
                return;
            }

            log.info("didn't understand request.. treat as normal request");
            if (log.isDebugEnabled()) {
                logHeaders(request);
            }
        }

        // inform client of data size
        response.setContentLength((int) len);
    }

    // write all content to client
    int n;
    byte[] b = new byte[BUFFER_SIZE];
    while ((n = in.read(b)) != -1) {
        out.write(b, 0, n);
    }
}

From source file:org.eclipse.orion.server.cf.commands.GetSpaceByNameCommand.java

public ServerStatus _doIt() {
    try {/*  w w  w . java 2s . co  m*/

        // check the org first

        URI targetURI = URIUtil.toURI(target.getUrl());
        URI orgsURI = targetURI.resolve("/v2/organizations"); //$NON-NLS-1$

        GetMethod getOrgsMethod = new GetMethod(orgsURI.toString());
        ServerStatus confStatus = HttpUtil.configureHttpMethod(getOrgsMethod, target.getCloud());
        if (!confStatus.isOK())
            return confStatus;

        ServerStatus getOrgsStatus = HttpUtil.executeMethod(getOrgsMethod);
        if (!getOrgsStatus.isOK() && getOrgsStatus.getHttpCode() != HttpServletResponse.SC_PARTIAL_CONTENT)
            return getOrgsStatus;

        JSONObject result = getOrgsStatus.getJsonData();
        JSONArray orgs = result.getJSONArray("resources"); //$NON-NLS-1$

        if (orgs.length() == 0)
            return new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, "Organization not found",
                    null);

        Org organization = getOrganization(orgs, orgName);
        if (organization == null)
            return new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, "Organization not found",
                    null);

        // now get the space

        String spaceUrl = organization.getCFJSON().getJSONObject("entity").getString("spaces_url"); //$NON-NLS-1$//$NON-NLS-2$
        URI spaceURI = targetURI.resolve(spaceUrl);

        GetMethod getSpaceMethod = new GetMethod(spaceURI.toString());
        confStatus = HttpUtil.configureHttpMethod(getSpaceMethod, target.getCloud());
        if (!confStatus.isOK())
            return confStatus;

        ServerStatus getSpaceStatus = HttpUtil.executeMethod(getSpaceMethod);
        if (!getSpaceStatus.isOK())
            return getSpaceStatus;

        result = getSpaceStatus.getJsonData();
        JSONArray spaces = result.getJSONArray("resources"); //$NON-NLS-1$

        if (spaces.length() == 0)
            return new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, "Space not found", null);

        Space space = getSpace(spaces, spaceName);
        if (space == null)
            return new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, "Space not found", null);

        return new ServerStatus(Status.OK_STATUS, HttpServletResponse.SC_OK, space.toJSON());
    } catch (Exception e) {
        String msg = NLS.bind("An error occured when performing operation {0}", commandName); //$NON-NLS-1$
        logger.error(msg, e);
        return new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e);
    }
}

From source file:us.mn.state.health.lims.analyzerimport.action.AnalyzerImportServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String password = null;//from  w w w . j ava 2 s  .  c om
    String user = null;
    AnalyzerReader reader = null;
    boolean fileRead = false;

    InputStream stream = null;

    try {
        ServletFileUpload upload = new ServletFileUpload();

        FileItemIterator iterator = upload.getItemIterator(request);
        while (iterator.hasNext()) {
            FileItemStream item = iterator.next();
            stream = item.openStream();

            String name = null;

            if (item.isFormField()) {

                if (PASSWORD.equals(item.getFieldName())) {
                    password = streamToString(stream);
                } else if (USER.equals(item.getFieldName())) {
                    user = streamToString(stream);
                }

            } else {

                name = item.getName();

                reader = AnalyzerReaderFactory.getReaderFor(name);

                if (reader != null) {
                    fileRead = reader.readStream(new InputStreamReader(stream));
                }
            }

            stream.close();
        }
    } catch (Exception ex) {
        throw new ServletException(ex);
    } finally {
        if (stream != null) {
            try {
                stream.close();
            } catch (IOException e) {
                //   LOG.warning(e.toString());
            }
        }
    }

    if (GenericValidator.isBlankOrNull(user) || GenericValidator.isBlankOrNull(password)) {
        response.getWriter().print("missing user");
        response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
        return;
    }

    if (!userValid(user, password)) {
        response.getWriter().print("invalid user/password");
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    if (fileRead) {
        boolean successful = reader.insertAnalyzerData(systemUserId);

        if (successful) {
            response.getWriter().print("success");
            response.setStatus(HttpServletResponse.SC_OK);
            return;
        } else {
            response.getWriter().print(reader.getError());
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }

    } else {
        response.getWriter().print(reader.getError());
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

}

From source file:netinf.node.cache.peerside.PeersideServlet.java

/**
 * HEAD and GET operations./*w w  w .  j  ava  2  s .  c  om*/
 * 
 * @param req
 *           The Request.
 * @param resp
 *           The response.
 * @param writeContent
 * @throws IOException
 */
private void doHeadOrGet(HttpServletRequest req, HttpServletResponse resp, boolean writeContent)
        throws IOException {
    String elementKey = req.getPathInfo();
    if (elementKey.startsWith("/") && elementKey.length() >= 1) {
        elementKey = elementKey.substring(1);
    }
    Element element = cache.get(elementKey);
    if (element == null) {
        resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
    } else {
        byte[] content = (byte[]) element.getValue();
        String range = req.getHeader("Range");
        if (range != null) {
            if (range.matches("^bytes=(\\d+-\\d*|-\\d+)$")) {
                int contentLength = content.length;
                int offset = 0;
                int length = contentLength;
                range = range.split("=")[1];
                if (range.startsWith("-")) {
                    offset = contentLength - Integer.parseInt(range.substring(1));
                } else if (range.endsWith("-")) {
                    offset = Integer.parseInt(range.substring(0, range.length() - 1));
                } else {
                    String[] rangeParts = range.split("-");
                    offset = Integer.parseInt(rangeParts[0]);
                    length = Integer.parseInt(rangeParts[1]) + 1;
                }
                if (offset <= length && offset <= contentLength) {
                    length = length > contentLength ? contentLength : length;
                    resp.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
                    resp.setContentLength(length - offset);
                    resp.setHeader("Accept-Ranges", "bytes");
                    resp.setHeader("Content-Range", offset + "-" + (length - 1) + "/" + contentLength);
                    if (writeContent) {
                        IOUtils.copy(new ByteArrayInputStream(content, offset, length - offset),
                                resp.getOutputStream());
                    }
                } else {
                    resp.setStatus(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
                }
            } else {
                resp.setStatus(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
            }
        } else {
            resp.setStatus(HttpServletResponse.SC_OK);
            resp.setContentLength(content.length);
            resp.setHeader("Accept-Ranges", "bytes");
            if (writeContent) {
                IOUtils.copy(new ByteArrayInputStream(content), resp.getOutputStream());
            }
        }
    }
}

From source file:com.openedit.generators.FileGenerator.java

public void generate(WebPageRequest inContext, Page inPage, Output inOut) throws OpenEditException {
    Page contentpage = inPage;//  w  w w.  j a va2s.  c o m

    HttpServletResponse res = inContext.getResponse();
    HttpServletRequest req = inContext.getRequest();
    if (res != null && req != null) {
        checkCors(req, res);
    }
    long start = -1;
    InputStream in = null;
    try {
        in = contentpage.getInputStream();
        if (in == null) {
            String vir = contentpage.get("virtual");
            if (!Boolean.parseBoolean(vir)) {
                log.info("Missing: " + contentpage.getPath());
                throw new ContentNotAvailableException("Missing: " + contentpage.getPath(),
                        contentpage.getPath());
            } else {
                log.debug("not found: " + contentpage);
                return; //do nothing
            }
        }
        //only bother if we are the content page and not in development
        if (res != null && inContext.getContentPage() == contentpage) {
            boolean cached = checkCache(inContext, contentpage, req, res);
            if (cached) {
                return;
            }
        }
        //sometimes we can specify the length of the document
        //long length = -1;
        long end = -1;
        if (req != null && inContext.getContentPage() == contentpage) {
            //might need to seek
            String range = req.getHeader("Range");
            if (range != null && range.startsWith("bytes=")) {
                //will need to seek
                int cutoff = range.indexOf("-");
                start = Long.parseLong(range.substring(6, cutoff));
                cutoff++;// 0 based
                if (range.length() > cutoff) // a trailing - means everything left
                {
                    end = Long.parseLong(range.substring(cutoff));
                }
                //log.info("Requested " + range);
                res.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
            }
        }

        long length = -1;
        if (res != null && !contentpage.isHtml() && !contentpage.isJson()
                && inContext.getContentPage() == contentpage) { //we can set the length unless there is a decorator on it somehow
            length = (long) contentpage.getContentItem().getLength();
            if (length != -1) {
                if (start > -1) {
                    if (end == -1) {
                        end = length - 1; //1024-1 1023
                    }
                    res.setHeader("Accept-Ranges", "bytes");
                    res.setHeader("Content-Range", "bytes " + start + "-" + end + "/" + length); //len is total
                    long sent = end + 1 - start; // 0 1024 - 1024 length

                    length = sent;
                }
                if (length > 0 && length < Integer.MAX_VALUE) {

                    res.setContentLength((int) length);
                } else {
                    log.info("Zero length file " + contentpage.getPath());
                }
                //res.removeHeader("Content-Length");
                //res.setHeader("Content-Length", String.valueOf(length));
            }
        }

        if (contentpage.isBinary()) {
            in = streamBinary(inContext, contentpage, in, start, end, length, inOut);
        } else {
            InputStreamReader reader = null;
            if (contentpage.getCharacterEncoding() != null) {
                reader = new InputStreamReader(in, contentpage.getCharacterEncoding());
            } else {
                reader = new InputStreamReader(in);
            }
            //If you get an error about content length then your character encoding is not correct. Use UTF-8
            //maybe we need to write with the correct encoding then the files should match
            getOutputFiller().fill(reader, inOut.getWriter());
        }
    } catch (Exception eof) {
        if (ignoreError(eof)) {
            //log.error(eof); ignored
            return;
        }
        if (in == null) {
            log.error("Could not load " + contentpage.getPath());
        }
        throw new OpenEditException(eof);
    } finally {
        FileUtils.safeClose(in);
    }

}

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

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

    TransferStatus status = null;/*from  w  w  w. j a v  a  2s.  co m*/
    try {

        status = statusService.createDownloadStatus(playerService.getPlayer(request, response, false, false));

        MediaFile mediaFile = getSingleFile(request);
        String dir = request.getParameter("dir");
        String playlistName = request.getParameter("playlist");
        String playerId = request.getParameter("player");
        int[] indexes = ServletRequestUtils.getIntParameters(request, "i");

        if (mediaFile != null) {
            response.setIntHeader("ETag", mediaFile.getId());
            response.setHeader("Accept-Ranges", "bytes");
        }

        LongRange range = StringUtil.parseRange(request.getHeader("Range"));
        if (range != null) {
            response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
            LOG.info("Got range: " + range);
        }

        if (mediaFile != null) {
            File file = mediaFile.getFile();
            if (!securityService.isReadAllowed(file)) {
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
                return null;
            }

            if (file.isFile()) {
                downloadFile(response, status, file, range);
            } else {
                downloadDirectory(response, status, file, range);
            }
        } else if (dir != null) {
            File file = new File(dir);
            if (!securityService.isReadAllowed(file)) {
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
                return null;
            }
            downloadFiles(response, status, file, indexes);

        } else if (playlistName != null) {
            Playlist playlist = new Playlist();
            playlistService.loadPlaylist(playlist, playlistName);
            downloadPlaylist(response, status, playlist, null, range);

        } else if (playerId != null) {
            Player player = playerService.getPlayerById(playerId);
            Playlist playlist = player.getPlaylist();
            playlist.setName("Playlist");
            downloadPlaylist(response, status, playlist, indexes.length == 0 ? null : indexes, range);
        }

    } finally {
        if (status != null) {
            statusService.removeDownloadStatus(status);
            User user = securityService.getCurrentUser(request);
            securityService.updateUserByteCounts(user, 0L, status.getBytesTransfered(), 0L);
        }
    }

    return null;
}

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

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

    TransferStatus status = null;//  w  w w .j  av  a2 s . co m
    try {

        status = statusService.createDownloadStatus(playerService.getPlayer(request, response, false, false));

        MediaFile mediaFile = getMediaFile(request);
        Integer playlistId = ServletRequestUtils.getIntParameter(request, "playlist");
        String playerId = request.getParameter("player");
        int[] indexes = request.getParameter("i") == null ? null
                : ServletRequestUtils.getIntParameters(request, "i");

        if (mediaFile != null) {
            response.setIntHeader("ETag", mediaFile.getId());
            response.setHeader("Accept-Ranges", "bytes");
        }

        HttpRange range = HttpRange.valueOf(request.getHeader("Range"));
        if (range != null) {
            response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
            LOG.info("Got HTTP range: " + range);
        }

        if (mediaFile != null) {
            if (mediaFile.isFile()) {
                downloadFile(response, status, mediaFile.getFile(), range);
            } else {
                List<MediaFile> children = mediaFileService.getChildrenOf(mediaFile, true, true, true);
                String zipFileName = FilenameUtils.getBaseName(mediaFile.getPath()) + ".zip";
                downloadFiles(response, status, children, indexes, range, zipFileName);
            }

        } else if (playlistId != null) {
            List<MediaFile> songs = playlistService.getFilesInPlaylist(playlistId);
            Playlist playlist = playlistService.getPlaylist(playlistId);
            downloadFiles(response, status, songs, null, range, playlist.getName() + ".zip");

        } else if (playerId != null) {
            Player player = playerService.getPlayerById(playerId);
            PlayQueue playQueue = player.getPlayQueue();
            playQueue.setName("Playlist");
            downloadFiles(response, status, playQueue.getFiles(), indexes, range, "download.zip");
        }

    } finally {
        if (status != null) {
            statusService.removeDownloadStatus(status);
            User user = securityService.getCurrentUser(request);
            securityService.updateUserByteCounts(user, 0L, status.getBytesTransfered(), 0L);
        }
    }

    return null;
}