Example usage for javax.servlet.http HttpServletResponse setBufferSize

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

Introduction

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

Prototype

public void setBufferSize(int size);

Source Link

Document

Sets the preferred buffer size for the body of the response.

Usage

From source file:se.vgregion.webbisar.web.MediaServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // Get requested image by path info.
    String requestedFile = request.getPathInfo();
    LOGGER.info("requestedFile: " + requestedFile);

    if (requestedFile == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
        return;/*from  ww  w  .ja v a2  s. c o m*/
    }

    File file = new File(baseFilePath, URLDecoder.decode(requestedFile, "UTF-8"));
    LOGGER.info("filePath: " + file.getAbsolutePath());
    LOGGER.info("fileName: " + file.getName());

    // Check if file exists
    if (!file.exists()) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
        return;
    }

    // Get content type by filename.
    String contentType = getServletContext().getMimeType(file.getName().replace(".JPG", ".jpg"));
    if (contentType == null && file.getName().endsWith("3gp")) {
        contentType = "video/3gpp";
    }

    if (contentType == null || !(contentType.startsWith("image") || contentType.startsWith("video"))) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
        return;
    }

    // Init servlet response.
    response.reset();
    response.setBufferSize(DEFAULT_BUFFER_SIZE);
    response.addHeader("Content-Type", contentType);
    response.addHeader("Content-Length", String.valueOf(file.length()));

    response.addHeader("Expires", "Sun, 17 Jan 2038 19:14:07 GMT");
    response.addHeader("Cache-Control", "public");

    response.addHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\"");

    // Prepare streams.
    BufferedInputStream input = null;
    BufferedOutputStream output = null;

    try {
        // Open streams.
        input = new BufferedInputStream(new FileInputStream(file), DEFAULT_BUFFER_SIZE);
        output = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE);

        // Write file contents to response.
        byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
        int length;
        while ((length = input.read(buffer)) > 0) {
            output.write(buffer, 0, length);
        }

        // Finalize task.
        output.flush();
    } finally {
        // Gently close streams.
        close(output);
        close(input);
    }
}

From source file:org.kurento.repository.internal.http.RepositoryHttpServlet.java

/**
 * Copy the contents of the specified input stream to the specified output stream, and ensure that
 * both streams are closed before returning (even in the face of an exception).
 *
 * @param repoItemHttpElem/*from w  ww. java2 s.c  om*/
 *          The cache entry for the source resource
 * @param response
 *          The response we are writing to
 * @param ranges
 *          Enumeration of the ranges the client wanted to retrieve
 * @param contentType
 *          Content type of the resource
 * @exception IOException
 *              if an input/output error occurs
 */
protected void copy(RepositoryHttpEndpointImpl repoItemHttpElem, HttpServletResponse response,
        List<Range> ranges, String contentType) throws IOException {

    try {
        response.setBufferSize(OUTPUT_BUFFER_SIZE);
    } catch (IllegalStateException e) {
        // Silent catch
    }

    IOException exception = null;
    try (ServletOutputStream ostream = response.getOutputStream()) {

        for (Range currentRange : ranges) {

            try (InputStream istream = new BufferedInputStream(repoItemHttpElem.createRepoItemInputStream(),
                    INPUT_BUFFER_SIZE)) {

                // Writing MIME header.
                ostream.println();
                ostream.println("--" + MIME_SEPARATION);

                if (contentType != null) {
                    ostream.println("Content-Type: " + contentType);
                }

                ostream.println("Content-Range: bytes " + currentRange.start + "-" + currentRange.end + "/"
                        + currentRange.length);
                ostream.println();

                exception = copyStreamsRange(istream, ostream, currentRange);

                if (exception != null) {
                    break;
                }
            }
        }

        ostream.println();
        ostream.print("--" + MIME_SEPARATION + "--");
    }
    // Rethrow any exception that has occurred
    if (exception != null) {
        throw exception;
    }

}

From source file:org.nema.medical.mint.server.controller.StudyBinaryItemsController.java

@RequestMapping("/studies/{uuid}/{type}/binaryitems/{seq}")
public void studiesBinaryItems(final HttpServletResponse res, HttpServletRequest req,
        @PathVariable("uuid") final String uuid, @PathVariable("type") final String type,
        @PathVariable("seq") final String seq) throws IOException {

    final Utils.StudyStatus studyStatus = Utils.validateStudyStatus(studiesRoot, uuid, res, studyDAO);
    if (studyStatus != Utils.StudyStatus.OK) {
        return;//from   w w w  .  j  a v  a 2 s  . c  om
    }

    final File studyRoot = new File(studiesRoot, uuid);

    final Iterator<Integer> itemList;
    try {
        itemList = parseItemList(seq, type, studyRoot);
    } catch (final NumberFormatException e) {
        res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid binary item requested: NaN");
        return;
    }

    if (!itemList.hasNext()) {
        res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "Unable to retrieve binary items. See server log for details.");
        LOG.error("Unable to locate binary items: " + seq + " or there are no binary items.");
        return;
    }

    LOG.debug("output buffer size was " + res.getBufferSize());
    res.setBufferSize(binaryItemResponseBufferSize);
    LOG.debug("output buffer size is now " + res.getBufferSize());
    final OutputStream out = res.getOutputStream();

    int i = itemList.next();

    File file = new File(
            studyRoot + "/" + type + "/binaryitems/" + i + "." + StorageUtil.BINARY_FILE_EXTENSION);
    if (!file.exists() || !file.canRead()) {
        final File newFile = new File(studyRoot + "/" + type + "/binaryitems/" + i + "."
                + StorageUtil.EXCLUDED_BINARY_FILE_EXTENSION);
        if (newFile.exists() && newFile.canRead()) {
            file = newFile;
        } else {
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "Unable to retrieve requested binary items. See server error log.");
            LOG.error("BinaryItemsFile " + file + " does not exist");
            return;
        }
    }

    // write the appropriate header
    final boolean multipart = itemList.hasNext();
    if (multipart) {
        res.setContentType("multipart/x-mixed-replace; boundary=\"" + MP_BOUNDARY + "\"");
        out.write(("--" + MP_BOUNDARY).getBytes());

        final long itemsize = file.length();
        String index = Integer.toString(i);
        out.write("\nContent-Type: application/octet-stream\n".getBytes());
        out.write(("Content-ID: <" + index + "@" + uuid + ">\n").getBytes());
        out.write(("Content-Length: " + itemsize + "\n\n").getBytes());
    } else {
        res.setContentType("application/octet-stream");
        res.setContentLength((int) file.length());
    }

    out.flush();
    streamBinaryItem(file, out, binaryItemStreamBufferSize);

    if (multipart) {
        out.write(("\n--" + MP_BOUNDARY).getBytes());
    }

    for (; itemList.hasNext();) {
        i = itemList.next();

        file = new File(studyRoot + "/" + type + "/binaryitems/" + i + "." + StorageUtil.BINARY_FILE_EXTENSION);
        if (!file.exists() || !file.canRead()) {
            final File newFile = new File(studyRoot + "/" + type + "/binaryitems/" + i + "."
                    + StorageUtil.EXCLUDED_BINARY_FILE_EXTENSION);
            if (newFile.exists() && newFile.canRead()) {
                file = newFile;
            } else {
                res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        "Unable to retrieve requested binary items. See server error log.");
                LOG.error("BinaryItemsFile " + file + " does not exist");
                return;
            }

        }

        final long itemsize = file.length();
        String index = Integer.toString(i);
        out.write("\nContent-Type: application/octet-stream\n".getBytes());
        out.write(("Content-ID: <" + index + "@" + uuid + ">\n").getBytes());
        out.write(("Content-Length: " + itemsize + "\n\n").getBytes());

        streamBinaryItem(file, out, binaryItemStreamBufferSize);

        out.write(("\n--" + MP_BOUNDARY).getBytes());
    }

    if (multipart) {
        out.write("--".getBytes());
    }

    out.flush();
}

From source file:com.zimbra.soap.SoapServlet.java

private void sendResponse(HttpServletRequest req, HttpServletResponse resp, Element envelope)
        throws IOException {
    SoapProtocol soapProto = SoapProtocol.determineProtocol(envelope);
    int statusCode = soapProto.hasFault(envelope) ? HttpServletResponse.SC_INTERNAL_SERVER_ERROR
            : HttpServletResponse.SC_OK;

    boolean chunkingEnabled = LC.soap_response_chunked_transfer_encoding_enabled.booleanValue();

    if (chunkingEnabled) {
        // disable chunking if proto < HTTP 1.1
        String proto = req.getProtocol();
        try {//from ww  w.  j  a v  a 2  s. c  o m
            HttpVersion httpVer = HttpVersion.parse(proto);
            chunkingEnabled = !httpVer.lessEquals(HttpVersion.HTTP_1_0);
        } catch (ProtocolException e) {
            ZimbraLog.soap.warn(
                    "cannot parse http version in request: %s, http chunked transfer encoding disabled", proto,
                    e);
            chunkingEnabled = false;
        }
    }

    // use jetty default if the LC key is not set
    int responseBufferSize = soapResponseBufferSize();
    if (responseBufferSize != -1)
        resp.setBufferSize(responseBufferSize);

    resp.setContentType(soapProto.getContentType());
    resp.setStatus(statusCode);
    resp.setHeader("Cache-Control", "no-store, no-cache");

    if (chunkingEnabled) {
        // Let jetty chunk the response if applicable.
        ZimbraServletOutputStream out = new ZimbraServletOutputStream(resp.getOutputStream());
        envelope.output(out);
        out.flush();
    } else {
        // serialize the envelope to a byte array and send the response with Content-Length header.
        byte[] soapBytes = envelope.toUTF8();
        resp.setContentLength(soapBytes.length);
        resp.getOutputStream().write(soapBytes);
        resp.getOutputStream().flush();
    }
    envelope.destroy();
}

From source file:org.acegisecurity.ui.AbstractProcessingFilter.java

protected void sendRedirect(HttpServletRequest request, HttpServletResponse response, String url)
        throws IOException {
    String finalUrl;//from  ww  w  .j  a  v  a 2s .  c o m
    if (!url.startsWith("http://") && !url.startsWith("https://")) {
        if (useRelativeContext) {
            finalUrl = url;
        } else {
            finalUrl = request.getContextPath() + url;
        }
    } else if (useRelativeContext) {
        // Calculate the relative URL from the fully qualifed URL, minus the
        // protocol and base context.
        int len = request.getContextPath().length();
        int index = url.indexOf(request.getContextPath()) + len;
        finalUrl = url.substring(index);
        if (finalUrl.length() > 1 && finalUrl.charAt(0) == '/') {
            finalUrl = finalUrl.substring(1);
        }
    } else {
        finalUrl = url;
    }

    Assert.isTrue(!response.isCommitted(),
            "Response already committed; the authentication mechanism must be able to modify buffer size");
    response.setBufferSize(bufferSize);
    response.sendRedirect(response.encodeRedirectURL(finalUrl));
}

From source file:lucee.runtime.net.rpc.server.RPCServer.java

/**
 * Process a POST to the servlet by handing it off to the Axis Engine.
 * Here is where SOAP messages are received
 * @param req posted request/*from ww  w . j  av a  2s .com*/
 * @param res respose
 * @throws ServletException trouble
 * @throws IOException different trouble
 */
public void doPost(HttpServletRequest req, HttpServletResponse res, Component component)
        throws ServletException, IOException {
    long t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0;
    String soapAction = null;
    MessageContext msgContext = null;

    Message rspMsg = null;
    String contentType = null;
    InputStream is = null;
    try {
        AxisEngine engine = getEngine();

        if (engine == null) {
            // !!! should return a SOAP fault...
            ServletException se = new ServletException(Messages.getMessage("noEngine00"));
            log.debug("No Engine!", se);
            throw se;
        }

        res.setBufferSize(1024 * 8); // provide performance boost.

        /** get message context w/ various properties set
         */
        msgContext = createMessageContext(engine, req, res, component);
        ComponentController.set(msgContext);

        // ? OK to move this to 'getMessageContext',
        // ? where it would also be picked up for 'doGet()' ?
        if (securityProvider != null) {
            if (isDebug) {
                log.debug("securityProvider:" + securityProvider);
            }
            msgContext.setProperty(MessageContext.SECURITY_PROVIDER, securityProvider);
        }

        is = req.getInputStream();
        Message requestMsg = new Message(is, false, req.getHeader(HTTPConstants.HEADER_CONTENT_TYPE),
                req.getHeader(HTTPConstants.HEADER_CONTENT_LOCATION));
        // Transfer HTTP headers to MIME headers for request message.
        MimeHeaders requestMimeHeaders = requestMsg.getMimeHeaders();
        for (Enumeration e = req.getHeaderNames(); e.hasMoreElements();) {
            String headerName = (String) e.nextElement();
            for (Enumeration f = req.getHeaders(headerName); f.hasMoreElements();) {
                String headerValue = (String) f.nextElement();
                requestMimeHeaders.addHeader(headerName, headerValue);
            }
        }

        if (isDebug) {
            log.debug("Request Message:" + requestMsg);

            /* Set the request(incoming) message field in the context */
            /**********************************************************/
        }
        msgContext.setRequestMessage(requestMsg);
        String url = HttpUtils.getRequestURL(req).toString().toLowerCase();
        msgContext.setProperty(MessageContext.TRANS_URL, url);
        // put character encoding of request to message context
        // in order to reuse it during the whole process.

        try {
            String reqEnc = (String) requestMsg.getProperty(SOAPMessage.CHARACTER_SET_ENCODING);
            if (reqEnc != null)
                msgContext.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, reqEnc);
        } catch (SOAPException e1) {
        }

        try {
            /**
             * Save the SOAPAction header in the MessageContext bag.
             * This will be used to tell the Axis Engine which service
             * is being invoked.  This will save us the trouble of
             * having to parse the Request message - although we will
             * need to double-check later on that the SOAPAction header
             * does in fact match the URI in the body.
             */
            // (is this last stmt true??? (I don't think so - Glen))
            /********************************************************/
            soapAction = getSoapAction(req);
            if (soapAction != null) {
                msgContext.setUseSOAPAction(true);
                msgContext.setSOAPActionURI(soapAction);
            }

            // Create a Session wrapper for the HTTP session.
            // These can/should be pooled at some point.
            // (Sam is Watching! :-)
            msgContext.setSession(new AxisHttpSession(req));

            if (tlog.isDebugEnabled()) {
                t1 = System.currentTimeMillis();
            }
            /* Invoke the Axis engine... */
            /*****************************/
            if (isDebug) {
                log.debug("Invoking Axis Engine.");
                //here we run the message by the engine
            }
            //msgContext.setProperty("disablePrettyXML", "false");
            engine.invoke(msgContext);
            if (isDebug) {
                log.debug("Return from Axis Engine.");
            }
            if (tlog.isDebugEnabled()) {
                t2 = System.currentTimeMillis();
            }

            rspMsg = msgContext.getResponseMessage();

            // We used to throw exceptions on null response messages.
            // They are actually OK in certain situations (asynchronous
            // services), so fall through here and return an ACCEPTED
            // status code below.  Might want to install a configurable
            // error check for this later.
        } catch (AxisFault fault) {

            //log and sanitize
            processAxisFault(fault);
            configureResponseFromAxisFault(res, fault);
            rspMsg = msgContext.getResponseMessage();
            if (rspMsg == null) {
                rspMsg = new Message(fault);
                ((org.apache.axis.SOAPPart) rspMsg.getSOAPPart()).getMessage().setMessageContext(msgContext);
            }
        } catch (Throwable t) {
            if (t instanceof InvocationTargetException)
                t = ((InvocationTargetException) t).getTargetException();
            // Exception
            if (t instanceof Exception) {
                Exception e = (Exception) t;
                //other exceptions are internal trouble
                rspMsg = msgContext.getResponseMessage();
                res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                rspMsg = convertExceptionToAxisFault(e, rspMsg);
                ((org.apache.axis.SOAPPart) rspMsg.getSOAPPart()).getMessage().setMessageContext(msgContext);

            }
            // throwable
            else {
                logException(t);
                //other exceptions are internal trouble
                rspMsg = msgContext.getResponseMessage();
                res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                rspMsg = new Message(new AxisFault(t.toString(), t));
                ((org.apache.axis.SOAPPart) rspMsg.getSOAPPart()).getMessage().setMessageContext(msgContext);
            }
        }
    } catch (AxisFault fault) {

        processAxisFault(fault);
        configureResponseFromAxisFault(res, fault);
        rspMsg = msgContext.getResponseMessage();
        if (rspMsg == null) {
            rspMsg = new Message(fault);
            ((org.apache.axis.SOAPPart) rspMsg.getSOAPPart()).getMessage().setMessageContext(msgContext);
        }
    } finally {
        IOUtil.closeEL(is);
    }

    if (tlog.isDebugEnabled()) {
        t3 = System.currentTimeMillis();
    }

    // Send response back along the wire... 
    if (rspMsg != null) {

        // Transfer MIME headers to HTTP headers for response message.
        MimeHeaders responseMimeHeaders = rspMsg.getMimeHeaders();
        for (Iterator i = responseMimeHeaders.getAllHeaders(); i.hasNext();) {
            MimeHeader responseMimeHeader = (MimeHeader) i.next();
            res.addHeader(responseMimeHeader.getName(), responseMimeHeader.getValue());
        }
        // synchronize the character encoding of request and response
        String responseEncoding = (String) msgContext.getProperty(SOAPMessage.CHARACTER_SET_ENCODING);
        if (responseEncoding != null) {
            try {
                rspMsg.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, responseEncoding);
            } catch (SOAPException e) {
            }
        }

        //determine content type from message response
        contentType = rspMsg.getContentType(msgContext.getSOAPConstants());
        if (isDebug)
            log.debug("Returned Content-Type:" + contentType);

        // write result to response stream
        try {
            res.setContentType(contentType);
            rspMsg.writeTo(res.getOutputStream());
        } catch (SOAPException e) {
            logException(e);
        }

        if (!res.isCommitted())
            res.flushBuffer(); // Force it right now.
    } else {
        // No content, so just indicate accepted
        res.setStatus(202);
    }

    if (isDebug) {
        log.debug("Response sent.");
        log.debug("Exit: doPost()");
    }
    if (tlog.isDebugEnabled()) {
        t4 = System.currentTimeMillis();
        tlog.debug("axisServlet.doPost: " + soapAction + " pre=" + (t1 - t0) + " invoke=" + (t2 - t1) + " post="
                + (t3 - t2) + " send=" + (t4 - t3) + " " + msgContext.getTargetService() + "."
                + ((msgContext.getOperation() == null) ? "" : msgContext.getOperation().getName()));
    }

}

From source file:com.geminimobile.web.DownloadCSVController.java

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    String msisdn = (String) request.getParameter("msisdn");
    String startTime = (String) request.getParameter("starttime");
    String endTime = (String) request.getParameter("endtime");
    String market = (String) request.getParameter("market");
    String type = (String) request.getParameter("type");

    Date toDate = SearchCommand.m_sdf.parse(endTime);
    //String maxTimestamp = Long.toString(toDate.getTime());

    Date fromDate = SearchCommand.m_sdf.parse(startTime);
    //String minTimestamp = Long.toString(fromDate.getTime());

    CDRDataAccess cdrAccess = new CDRDataAccess();
    Vector<CDREntry> cdrs = cdrAccess.getCDRsByMSISDN(msisdn, fromDate.getTime(), toDate.getTime(), market,
            type, 100000); // 100,000 entries max

    //Vector<CDREntry> cdrs = (Vector<CDREntry>) request.getSession().getAttribute("cdrResults");

    StringBuffer sb = new StringBuffer();

    // Write column headers 
    sb.append("Date/Time,Market,Type,MSISDN,MO IP address,MT IP Address,Sender Domain,Recipient Domain\n");

    for (CDREntry entry : cdrs) {
        sb.append(entry.getDisplayTimestamp() + "," + entry.getMarket() + "," + entry.getType() + ","
                + entry.getMsisdn() + "," + entry.getMoIPAddress() + "," + entry.getMtIPAddress() + ","
                + entry.getSenderDomain() + "," + entry.getRecipientDomain() + "\n");
    }/*from   ww w .  j  a v a 2s .  c o m*/

    String csvString = sb.toString();

    response.setBufferSize(sb.length());
    response.setContentLength(sb.length());

    response.setContentType("text/plain; charset=UTF-8");
    //response.setContentType( "text/csv" );
    //response.setContentType("application/ms-excel");
    //response.setHeader("Content-disposition", "attachment;filename=cdrResults.csv");
    response.setHeader("Content-Disposition", "attachment; filename=" + "cdrResults.csv" + ";");
    ServletOutputStream os = response.getOutputStream();

    os.write(csvString.getBytes());

    os.flush();
    os.close();

    return null;
}

From source file:edu.stanford.muse.webapp.JSPHelper.java

public static void writeFileToResponse(HttpSession session, HttpServletResponse response, String filePath,
        boolean asAttachment) throws IOException {
    // Decode the file name (might contain spaces and on) and prepare file object.
    File file = new File(filePath);

    // Check if file actually exists in filesystem.
    if (!file.exists()) {
        log.warn("Returing 404, serveFile can't find file: " + filePath);

        // Do your thing if the file appears to be non-existing.
        // Throw an exception, or send 404, or show default/warning page, or just ignore it.
        response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
        return;//from w  w w .  j a v  a2s.c  o  m
    }

    // Get content type by filename.

    String contentType = session.getServletContext().getMimeType(file.getName());

    // 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";
    }

    // Init servlet response.
    int DEFAULT_BUFFER_SIZE = 100000;
    response.reset();
    response.setBufferSize(DEFAULT_BUFFER_SIZE);
    response.setContentType(contentType);

    // not really sure why this is needed, but we have to ensure that these headers are not present when rendering e.g. xwordImage (directly rendered into web browser, instead of piclens)
    if (asAttachment) {
        response.setHeader("Content-Length", String.valueOf(file.length()));
        response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");
    }
    // Prepare streams.
    BufferedInputStream input = null;
    BufferedOutputStream output = null;

    try {
        // Open streams.
        input = new BufferedInputStream(new FileInputStream(file), DEFAULT_BUFFER_SIZE);
        output = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE);

        // Write file contents to response.
        byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
        int length;
        while ((length = input.read(buffer)) > 0) {
            output.write(buffer, 0, length);
        }
    } finally {
        // Gently close streams.
        Util.close(output);
        Util.close(input);
    }
}

From source file:org.nema.medical.mint.server.controller.StudyMetadataController.java

@RequestMapping("/studies/{uuid}/{type}/metadata")
public void studiesMetadata(final @PathVariable("uuid") String uuid, final @PathVariable("type") String type,
        final HttpServletRequest req, final HttpServletResponse res) throws IOException {
    final Utils.StudyStatus studyStatus = Utils.validateStudyStatus(studiesRoot, uuid, res, studyDAO);
    if (studyStatus != Utils.StudyStatus.OK) {
        return;// w w w  .j av  a 2 s  .com
    }

    final File studyDir = new File(studiesRoot, uuid);
    final File typeDir = new File(studyDir, type);
    if (!typeDir.exists() || !typeDir.canRead()) {
        LOG.error("Unable to locate directory for study: " + studyDir);
        res.sendError(HttpServletResponse.SC_NOT_FOUND, "Invalid study requested: Not found");
        return;
    }

    try {
        String filename;

        String uri = req.getRequestURI();
        boolean gzip = uri.endsWith(".gz");
        uri = StringUtils.substringBeforeLast(uri, ".gz");
        String extension = StringUtils.substringAfterLast(uri, ".");

        if ("gpb".equals(extension)) {
            res.setContentType("application/octet-stream");
            filename = "metadata.gpb";
        } else if ("xml".equals(extension) || uri.endsWith("metadata")) {
            res.setContentType("text/xml");
            filename = "metadata.xml";
        } else {
            res.sendError(HttpServletResponse.SC_NOT_FOUND, "Unknown metadata type.");
            return;
        }

        if (gzip) {
            filename = filename + ".gz";
            res.setContentType("application/gzip");
        }

        final File file = new File(typeDir, filename);
        if (!file.exists()) {
            StudyMetadata study = StudyIO.loadStudy(typeDir);
            StudyIO.writeFile(study, file);
        }

        res.setContentLength(Long.valueOf(file.length()).intValue());
        res.setBufferSize(fileResponseBufferSize);
        Utils.streamFile(file, res.getOutputStream(), fileStreamBufferSize);
    } catch (final IOException e) {
        if (!res.isCommitted()) {
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "Unable to provide study metadata. See server logs.");
        }
    }
}

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

private static void serveFullResource(HttpServletRequest httpReq, HttpServletResponse httpResp,
        MediaResource mr) {/* www.j av a 2 s . c o  m*/
    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);
    }
}