Example usage for java.io BufferedInputStream skip

List of usage examples for java.io BufferedInputStream skip

Introduction

In this page you can find the example usage for java.io BufferedInputStream skip.

Prototype

public synchronized long skip(long n) throws IOException 

Source Link

Document

See the general contract of the skip method of InputStream.

Usage

From source file:org.apache.flex.compiler.filespecs.CombinedFile.java

/**
 * Get the {@link BufferedInputStream} of a file, skipping the BOM.
 * /*www  . j a  v a  2s  .c  o  m*/
 * @param filename The path to the file.
 * @return BufferedInputStream
 */
public static BufferedInputStream getStreamAndSkipBOM(String filename) throws IOException {
    final File file = new File(filename);
    BufferedInputStream strm = new BufferedInputStream(new FileInputStream(file));
    final BOM bom = getBOM(strm);
    strm.skip(bom.pattern.length);

    return strm;
}

From source file:org.sakaiproject.tool.assessment.ui.servlet.delivery.ShowMediaServlet.java

public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    String agentIdString = getAgentString(req, res);
    if (agentIdString == null) {
        String path = "/jsf/delivery/mediaAccessDenied.faces";
        RequestDispatcher dispatcher = req.getRequestDispatcher(path);
        dispatcher.forward(req, res);/* w w  w  .  j  a v  a  2 s.  co  m*/
        return;
    }
    String mediaId = req.getParameter("mediaId");
    if (mediaId == null || mediaId.trim().equals("")) {
        return;
    }

    // get media
    GradingService gradingService = new GradingService();
    MediaData mediaData = gradingService.getMedia(mediaId);
    String mediaLocation = mediaData.getLocation();
    int fileSize = mediaData.getFileSize().intValue();
    log.info("****1. media file size=" + fileSize);

    //if setMimeType="false" in query string, implies, we want to do a forced download
    //in this case, we set contentType='application/octet-stream'
    String setMimeType = req.getParameter("setMimeType");
    log.info("****2. setMimeType=" + setMimeType);

    // get assessment's ownerId
    // String assessmentCreatedBy = req.getParameter("createdBy");

    // who can access the media? You can,
    // a. if you are the creator.
    // b. if you have a assessment.grade.any or assessment.grade.own permission
    boolean accessDenied = true;
    String currentSiteId = "";
    boolean isAudio = false;
    Long assessmentGradingId = mediaData.getItemGradingData().getAssessmentGradingId();
    PublishedAssessmentIfc pub = gradingService
            .getPublishedAssessmentByAssessmentGradingId(assessmentGradingId.toString());
    if (pub != null) {
        PublishedAssessmentService service = new PublishedAssessmentService();
        currentSiteId = service.getPublishedAssessmentOwner(pub.getPublishedAssessmentId());
    }

    // some log checking
    //log.debug("agentIdString ="+agentIdString);
    //log.debug("****current site Id ="+currentSiteId);

    boolean hasPrivilege = agentIdString != null && (agentIdString.equals(mediaData.getCreatedBy()) // user is creator
            || canGrade(req, res, agentIdString, currentSiteId));
    if (hasPrivilege) {
        accessDenied = false;
    }
    if (accessDenied) {
        String path = "/jsf/delivery/mediaAccessDenied.faces";
        RequestDispatcher dispatcher = req.getRequestDispatcher(path);
        dispatcher.forward(req, res);
    } else {
        String displayType = "inline";
        if (mediaData.getMimeType() != null && !mediaData.getMimeType().equals("application/octet-stream")
                && !(setMimeType != null && ("false").equals(setMimeType))) {
            res.setContentType(mediaData.getMimeType());
        } else {
            displayType = "attachment";
            res.setContentType("application/octet-stream");
        }
        log.debug("****" + displayType + ";filename=\"" + mediaData.getFilename() + "\";");

        res.setHeader("Content-Disposition", displayType + ";filename=\"" + mediaData.getFilename() + "\";");

        int start = 0;
        int end = fileSize - 1;
        int rangeContentLength = end - start + 1;

        String range = req.getHeader("Range");

        if (StringUtils.isNotBlank(range)) {
            Matcher matcher = HTTP_RANGE_PATTERN.matcher(range);

            if (matcher.matches()) {
                String startMatch = matcher.group(1);
                start = startMatch.isEmpty() ? start : Integer.valueOf(startMatch);
                start = start < 0 ? 0 : start;

                String endMatch = matcher.group(2);
                end = endMatch.isEmpty() ? end : Integer.valueOf(endMatch);
                end = end > fileSize - 1 ? fileSize - 1 : end;

                rangeContentLength = end - start + 1;
            }

            res.setHeader("Content-Range", String.format("bytes %s-%s/%s", start, end, fileSize));
            res.setHeader("Content-Length", String.format("%s", rangeContentLength));
            res.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
        } else {
            res.setContentLength(fileSize);
        }

        //** note that res.setContentType() must be called before res.getOutputStream(). see javadoc on this
        FileInputStream inputStream = null;
        BufferedInputStream buf_inputStream = null;
        ServletOutputStream outputStream = res.getOutputStream();
        BufferedOutputStream buf_outputStream = null;
        ByteArrayInputStream byteArrayInputStream = null;
        if (mediaLocation == null || (mediaLocation.trim()).equals("")) {
            try {
                byteArrayInputStream = new ByteArrayInputStream(mediaData.getMedia());
                buf_inputStream = new BufferedInputStream(byteArrayInputStream);
            } catch (Exception e) {
                log.error("****empty media save to DB=" + e.getMessage());
            }
        } else {
            try {
                inputStream = getFileStream(mediaLocation);
                buf_inputStream = new BufferedInputStream(inputStream);
            } catch (Exception e) {
                log.error("****empty media save to file =" + e.getMessage());
            }

        }

        try {

            buf_outputStream = new BufferedOutputStream(outputStream);
            int i = 0;
            if (buf_inputStream != null) {
                // skip to the start of the possible range request
                buf_inputStream.skip(start);

                int bytesLeft = rangeContentLength;
                byte[] buffer = new byte[1024];

                while ((i = buf_inputStream.read(buffer)) != -1 && bytesLeft > 0) {
                    buf_outputStream.write(buffer);
                    bytesLeft -= i;
                }
            }
            log.debug("**** mediaLocation=" + mediaLocation);

            res.flushBuffer();
        } catch (Exception e) {
            log.warn(e.getMessage());
        } finally {
            if (buf_outputStream != null) {
                try {
                    buf_outputStream.close();
                } catch (IOException e) {
                    log.error(e.getMessage());
                }
            }
            if (buf_inputStream != null) {
                try {
                    buf_inputStream.close();
                } catch (IOException e) {
                    log.error(e.getMessage());
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    log.error(e.getMessage());
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    log.error(e.getMessage());
                }
            }
            if (byteArrayInputStream != null) {
                try {
                    byteArrayInputStream.close();
                } catch (IOException e) {
                    log.error(e.getMessage());
                }
            }
        }
    }
}