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:org.kaaproject.kaa.server.admin.controller.KaaAdminController.java

/**
 * Generates an SDK for the specified target platform from an SDK profile .
 *
 * @param sdkProfileId/*w ww.j  a  v  a  2  s  .c  o  m*/
 *            the sdk profile id
 * @param targetPlatform
 *            the target platform
 * @param request
 *            the request
 * @param response
 *            the response
 * @throws KaaAdminServiceException
 *             the kaa admin service exception
 */
@RequestMapping(value = "sdk", method = RequestMethod.POST)
@ResponseStatus(value = HttpStatus.OK)
public void getSdk(@RequestParam(value = "sdkProfileId") String sdkProfileId,
        @RequestParam(value = "targetPlatform") String targetPlatform, HttpServletRequest request,
        HttpServletResponse response) throws KaaAdminServiceException {
    try {
        SdkProfileDto sdkProfile = kaaAdminService.getSdkProfile(sdkProfileId);
        FileData sdkData = kaaAdminService.getSdk(sdkProfile,
                SdkPlatform.valueOf(targetPlatform.toUpperCase()));
        response.setContentType(sdkData.getContentType());
        ServletUtils.prepareDisposition(request, response, sdkData.getFileName());
        response.setContentLength(sdkData.getFileData().length);
        response.setBufferSize(BUFFER);
        response.getOutputStream().write(sdkData.getFileData());
        response.flushBuffer();
    } catch (Exception e) {
        throw Utils.handleException(e);
    }
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.teacher.onlineTests.TestsManagementAction.java

public ActionForward showImage(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws FenixActionException {
    final String exerciseCode = getStringFromRequest(request, "exerciseCode");
    final Integer imgCode = getCodeFromRequest(request, "imgCode");
    final String imgTypeString = request.getParameter("imgType");
    final String studentCode = getStringFromRequest(request, "studentCode");
    final String optionShuffle = request.getParameter("optionShuffle");
    final String testCode = getStringFromRequest(request, "testCode");
    final Integer itemIndex = getCodeFromRequest(request, "item");
    final Integer feedbackCode = getCodeFromRequest(request, "feedbackCode");
    String img = null;/* w w w .j a  va2 s .  com*/
    if (studentCode != null && testCode != null) {
        try {
            img = ReadStudentTestQuestionImage.run(studentCode, testCode, exerciseCode, imgCode, feedbackCode,
                    itemIndex);
        } catch (FenixServiceException e) {
            throw new FenixActionException(e);
        }
    } else if (optionShuffle != null && !Strings.isNullOrEmpty(testCode)) {
        try {
            img = ReadQuestionImage.run(testCode, exerciseCode, optionShuffle, imgCode, feedbackCode);
        } catch (FenixServiceException e) {
            throw new FenixActionException(e);
        }
    } else {

        try {
            img = ReadQuestionImage.run(exerciseCode, imgCode, feedbackCode, itemIndex);
        } catch (FenixServiceException e) {
            throw new FenixActionException(e);
        }
    }
    byte[] imageData = BaseEncoding.base64().decode(img);
    try {
        response.reset();
        response.setContentType(imgTypeString);
        response.setContentLength(imageData.length);
        response.setBufferSize(imageData.length);
        String imageName = "image" + exerciseCode + imgCode + "."
                + imgTypeString.substring(imgTypeString.lastIndexOf("/") + 1, imgTypeString.length());
        response.setHeader("Content-disposition", "attachment; filename=" + imageName);
        DataOutputStream dataOut = new DataOutputStream(response.getOutputStream());
        dataOut.write(imageData);
        response.flushBuffer();
    } catch (java.io.IOException e) {
        throw new FenixActionException(e);
    }
    return null;
}

From source file:ORG.oclc.os.SRW.SRWServlet.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  w  w w  .j ava 2 s  . c om*/
 * @param res respose
 * @throws ServletException trouble
 * @throws IOException different trouble
 */
@Override
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    long t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0;
    String soapAction = null;
    MessageContext msgContext = null;
    if (isDebug)
        servletLog.debug("Enter: doPost()");
    if (tlog.isDebugEnabled()) {
        t0 = System.currentTimeMillis();
    }

    Message responseMsg = null;
    String contentType = req.getContentType().toLowerCase();
    if (log.isDebugEnabled())
        log.debug("in SRWServlet.doPost: contentType=" + contentType);
    if (contentType.indexOf("atom+xml") > 0) {
        msgContext = createMessageContext(getEngine(), req, res);
        if (!srwInfo.setSRWStuff(req, res, msgContext)) {
            servletLog.error("srwInfo.setSRWStuff failed!");
            return;
        }
        SRWDatabase db = (SRWDatabase) msgContext.getProperty("db");
        if (log.isDebugEnabled())
            log.debug("adding to database " + db);
        if (log.isDebugEnabled())
            log.debug("adding to database " + db.dbname);
        InputStream is = req.getInputStream();
        int len, offset = 0, totlen = req.getContentLength();
        byte[] b = new byte[totlen];
        while (totlen > 0) {
            len = is.read(b, offset, totlen);
            totlen -= len;
            offset += len;
        }
        db.add(b);
        if (db.httpHeaderSetter != null)
            db.httpHeaderSetter.setPostResponseHeaders(new String(b, "UTF-8"), req, res);
        res.setStatus(201);
        return;
    }

    try {
        AxisEngine engine = getEngine();

        if (engine == null) {
            // !!! should return a SOAP fault...
            ServletException se = new ServletException(Messages.getMessage("noEngine00"));
            servletLog.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);

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

        /* Get request message
         */
        Message requestMsg = new Message(req.getInputStream(), false,
                req.getHeader(HTTPConstants.HEADER_CONTENT_TYPE),
                req.getHeader(HTTPConstants.HEADER_CONTENT_LOCATION));

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

        /* Set the request(incoming) message field in the context */
        /**********************************************************/
        msgContext.setRequestMessage(requestMsg);
        //String url = HttpUtils.getRequestURL(req).toString();
        String url = req.getRequestURL().toString();
        msgContext.setProperty(MessageContext.TRANS_URL, url);

        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);
            } else { // not a SOAP request
                String content = new String(((SOAPPart) (requestMsg.getSOAPPart())).getAsBytes());
                if (content.startsWith("<")) { // must be an ATOM request
                    return;
                }
                if (content.indexOf("query=") >= 0 || content.indexOf("scanClause=") >= 0) {
                    processMethodRequest(msgContext,
                            new LateContentParsingHttpServletRequestWrapper(req, content), res);
                    return;
                }

                // nothing I recognize
                AxisFault af = new AxisFault("Client.NoSOAPAction",
                        Messages.getMessage("noHeader00", "SOAPAction"), null, null);

                exceptionLog.error(Messages.getMessage("genFault00"), af);

                throw af;
            }

            // 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();
            }

            srwInfo.setSRWStuff(req, res, msgContext);

            /* Invoke the Axis engine... */
            /*****************************/
            if (isDebug)
                servletLog.debug("Invoking Axis Engine.");
            //here we run the message by the engine
            engine.invoke(msgContext);
            if (isDebug)
                servletLog.debug("Return from Axis Engine.");
            if (tlog.isDebugEnabled()) {
                t2 = System.currentTimeMillis();
            }
            responseMsg = msgContext.getResponseMessage();
            if (responseMsg == null) {
                //tell everyone that something is wrong
                throw new Exception(Messages.getMessage("noResponse01"));
            }
        } catch (AxisFault fault) {
            //log and sanitize
            processAxisFault(fault);
            configureResponseFromAxisFault(res, fault);
            responseMsg = msgContext.getResponseMessage();
            if (responseMsg == null) {
                responseMsg = new Message(fault);
            }
        } catch (Exception e) {
            //other exceptions are internal trouble
            responseMsg = msgContext.getResponseMessage();
            res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            responseMsg = convertExceptionToAxisFault(e, responseMsg);
        }
    } catch (AxisFault fault) {
        processAxisFault(fault);
        configureResponseFromAxisFault(res, fault);
        responseMsg = msgContext.getResponseMessage();
        if (responseMsg == null) {
            responseMsg = new Message(fault);
        }
    }
    //determine content type from message response
    contentType = responseMsg.getContentType(msgContext.getSOAPConstants());
    if (tlog.isDebugEnabled()) {
        t3 = System.currentTimeMillis();
    }

    /* Send response back along the wire...  */
    /***********************************/
    if (responseMsg != null) {
        sendResponse(getProtocolVersion(req), contentType, res, responseMsg);
    }

    if (isDebug) {
        servletLog.debug("Response sent.");
        servletLog.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:org.flowerplatform.util.servlet.PublicResourcesServlet.java

/**
* @author Cristian Spiescu//  w  w w  .  j a  v a 2s.  co  m
* @author Sebastian Solomon
* @author Cristina Constantinescu
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String requestedFile = request.getPathInfo();
    if (logger.isTraceEnabled()) {
        logger.trace("Resource requested: {}", requestedFile);
    }

    // Check if file is actually supplied to the request URI.
    if (requestedFile == null) {
        send404(request, response);
        return;
    }

    // Decode the file name (might contain spaces and on) and prepare file object.

    // solution for: .../icons/0%.png
    // The URL decoder expects the %to precede a character code
    // replace(%) with %25 before decoding
    // http://stackoverflow.com/questions/6067673/urldecoder-illegal-hex-characters-in-escape-pattern-for-input-string
    requestedFile = requestedFile.replaceAll("%(?![0-9a-fA-F]{2})", "%25");

    requestedFile = URLDecoder.decode(requestedFile, "UTF-8");
    if (requestedFile.startsWith(UtilConstants.PUBLIC_RESOURCES_PATH_PREFIX)) {
        requestedFile = requestedFile.substring(UtilConstants.PUBLIC_RESOURCES_PATH_PREFIX.length());
    }

    // this may be an attempt to see files that are not public, i.e. to go to the
    // parent. From my tests, when you put in the browser (or even telnet) something like
    // parent1/parent2/../bla, it seems to be automatically translated to parent1/bla. However,
    // I wanted to make sure that we are all right
    if (requestedFile.contains("..")) {
        send404(request, response);
        return;
    }

    // we need something like /plugin/file....
    int indexOfSecondSlash = requestedFile.indexOf('/', 1); // 1, i.e. skip the first index
    if (indexOfSecondSlash < 0) {
        send404(request, response);
        return;
    }

    // both variables are prefixed with /
    String plugin = requestedFile.substring(0, indexOfSecondSlash);
    String file = requestedFile.substring(indexOfSecondSlash);

    // if | is supplied => the file is a zip, and we want what's in it
    int indexOfZipSeparator = file.indexOf(UtilConstants.RESOURCE_PATH_SEPARATOR);
    String fileInsideZipArchive = null;
    if (indexOfZipSeparator >= 0 && indexOfZipSeparator < file.length() - 1) { // has | and | is not the last char in the string
        fileInsideZipArchive = file.substring(indexOfZipSeparator + 1);
        file = file.substring(0, indexOfZipSeparator);
    }

    String mapValue = null;
    String mapKey = null;

    // if the file is in a zip, search first in the Temp folder
    if (fileInsideZipArchive != null) {
        mapKey = createMapKey(file, fileInsideZipArchive).intern();
        if (useFilesFromTemporaryDirectory) {
            mapValue = tempFilesMap.get(mapKey);
        }
    } else {
        // we don't need synchronization if the file is not inside archive (so we don't use .intern)
        mapKey = createMapKey(file, fileInsideZipArchive);
    }

    synchronized (mapKey) {
        if (useFilesFromTemporaryDirectory) {
            if (fileInsideZipArchive != null) {
                if (mapValue != null) { // file exists in 'tempFilesMap'
                    if (getTempFile(mapValue).exists()) {
                        response.reset();
                        response.setBufferSize(DEFAULT_BUFFER_SIZE);
                        response.setContentType(fileInsideZipArchive);
                        InputStream input = new FileInputStream(getTempFilePath(mapValue));
                        OutputStream output = response.getOutputStream();
                        IOUtils.copy(input, output);
                        input.close();
                        output.close();
                        logger.debug("File {} served from temp", mapValue);
                        return;
                    } else { // temporary file was deleted from disk
                        logger.debug("File {} found to be missing from temp", mapValue);
                    }
                } else {
                    synchronized (this) {
                        counter++;
                        mapValue = counter + "";
                        tempFilesMap.put(mapKey, mapValue);
                        logger.debug("mapValue '{}' added", mapValue);
                    }
                }
            }
        }

        requestedFile = "platform:/plugin" + plugin + "/" + UtilConstants.PUBLIC_RESOURCES_DIR + file;

        // Get content type by filename from the file or file inside zip
        String contentType = getServletContext()
                .getMimeType(fileInsideZipArchive != null ? fileInsideZipArchive : file);

        // 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.
        response.reset();
        response.setBufferSize(DEFAULT_BUFFER_SIZE);
        response.setContentType(contentType);
        //        response.setHeader("Content-Length", String.valueOf(file.length()));
        //        response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");

        // Prepare streams.
        URL url;
        InputStream input = null;
        Closeable inputCloseable = null;
        OutputStream output = null;

        try {
            url = new URL(requestedFile);
            try {
                input = url.openConnection().getInputStream();
                inputCloseable = input;
            } catch (IOException e) {
                // may fail if the resource is not available
                send404(request, response);
                return;
            }

            if (fileInsideZipArchive != null) {
                // we need to look for a file in the archive
                Pair<InputStream, Closeable> pair = getInputStreamForFileWithinZip(input, fileInsideZipArchive);
                if (pair == null) {
                    // the file was not found; the input streams are closed in this case
                    send404(request, response);
                    return;
                }

                input = pair.a;
                inputCloseable = pair.b;

                if (useFilesFromTemporaryDirectory) {
                    // write the file from archive in Temp folder
                    if (!UtilConstants.TEMP_FOLDER.exists()) {
                        UtilConstants.TEMP_FOLDER.mkdir();
                    }

                    Files.copy(input, getTempFile(mapValue).toPath(), StandardCopyOption.REPLACE_EXISTING);
                    logger.debug("file '{}' was writen in temp", mapValue);

                    input.close();
                    input = new FileInputStream(getTempFilePath(mapValue));
                }
            }

            output = response.getOutputStream();

            // according to the doc, no need to use Buffered..., because the method buffers internally
            IOUtils.copy(input, output);

        } finally {
            // Gently close streams.
            close(output);
            close(inputCloseable);
            close(input);
        }
    }
}

From source file:org.sakaiproject.chat2.model.impl.ChatEntityProducer.java

/**
 * {@inheritDoc}//from   w ww.j a  v a 2  s .c o  m
 */
public HttpAccess getHttpAccess() {
    return new HttpAccess() {

        public void handleAccess(HttpServletRequest req, HttpServletResponse res, Reference ref,
                Collection copyrightAcceptedRefs) throws EntityPermissionException, EntityNotDefinedException {
            try {
                //TODO: Isn't there a better way to do this than build out the whole page here??

                // We need to write to a temporary stream for better speed, plus
                // so we can get a byte count. Internet Explorer has problems
                // if we don't make the setContentLength() call.
                ByteArrayOutputStream outByteStream = new ByteArrayOutputStream();
                OutputStreamWriter sw = new OutputStreamWriter(outByteStream);

                String skin = ServerConfigurationService.getString("skin.default");
                String skinRepo = ServerConfigurationService.getString("skin.repo");

                ChatMessage message = getMessage(ref);
                String title = ref.getDescription();
                //MessageHeader messageHead = message.getHeader();
                //String date = messageHead.getDate().toStringLocalFullZ();
                String date = TimeService.newTime(message.getMessageDate().getTime()).toStringLocalFullZ();
                String from = UserDirectoryService.getUser(message.getOwner()).getDisplayName();
                //String from = messageHead.getFrom().getDisplayName();
                String groups = "";
                //Collection gr = messageHead.getGroups();
                //for (Iterator i = gr.iterator(); i.hasNext();)
                //{
                //   groups += "<li>" + i.next() + "</li>";
                //}
                String body = Web.escapeHtml(message.getBody());

                sw.write(
                        "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n"
                                + "<html xmlns=\"http://www.w3.org/1999/xhtml\" lang=\"en\" xml:lang=\"en\">\n"
                                + "<head>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />\n"
                                + "<link href=\"");
                sw.write(skinRepo);
                sw.write("/tool_base.css\" type=\"text/css\" rel=\"stylesheet\" media=\"all\" />\n"
                        + "<link href=\"");
                sw.write(skinRepo);
                sw.write("/");
                sw.write(skin);
                sw.write("/tool.css\" type=\"text/css\" rel=\"stylesheet\" media=\"all\" />\n"
                        + "<meta http-equiv=\"Content-Style-Type\" content=\"text/css\" />\n" + "<title>");
                sw.write(title);
                sw.write("</title></head><body><div class=\"portletBody\">\n" + "<h2>");
                sw.write(title);
                sw.write("</h2><ul><li>Date ");
                sw.write(date);
                sw.write("</li>");
                sw.write("<li>From ");
                sw.write(from);
                sw.write("</li>");
                sw.write(groups);
                sw.write("<ul><p>");
                sw.write(body);
                sw.write("</p></div></body></html> ");

                sw.flush();
                res.setContentType("text/html");
                res.setContentLength(outByteStream.size());

                if (outByteStream.size() > 0) {
                    // Increase the buffer size for more speed.
                    res.setBufferSize(outByteStream.size());
                }

                OutputStream out = null;
                try {
                    out = res.getOutputStream();
                    if (outByteStream.size() > 0) {
                        outByteStream.writeTo(out);
                    }
                    out.flush();
                    out.close();
                } catch (Throwable ignore) {
                } finally {
                    if (out != null) {
                        try {
                            out.close();
                        } catch (Throwable ignore) {
                        }
                    }
                }
            } catch (PermissionException e) {
                throw new EntityPermissionException(e.getUser(), e.getLocalizedMessage(), e.getResource());
            } catch (IdUnusedException e) {
                throw new EntityNotDefinedException(e.getId());
            } catch (Throwable t) {
                throw new RuntimeException("Faied to find message ", t);
            }
        }
    };
}

From source file:httpUtils.HttpUtils.java

/**
 * Parse the request headers, build the response, stream back file
 * @param request/*  w ww . j  a  v a  2s .  c om*/
 * @param response
 * @param dataStream
 * @param fileLength
 * @param fileName
 * @param fileLastModified
 * @param contentType
 * @return
 */
private static HttpServletResponse getFileAsStream(HttpServletRequest request, HttpServletResponse response,
        InputStream dataStream, long fileLength, String fileName, long fileLastModified, String contentType) {
    if (dataStream == null) {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        return response;
    }

    if (StringUtils.isEmpty(fileName) || fileLastModified == 0L) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return response;
    }

    String ifNoneMatch = request.getHeader("If-None-Match");
    if (ifNoneMatch != null && matches(ifNoneMatch, fileName)) {
        response.setHeader("ETag", fileName);
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return response;
    }

    long ifModifiedSince = request.getDateHeader("If-Modified-Since");
    if (ifNoneMatch == null && ifModifiedSince != -1 && ifModifiedSince + 1000 > fileLastModified) {
        response.setHeader("ETag", fileName);
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return response;
    }

    String ifMatch = request.getHeader("If-Match");
    if (ifMatch != null && !matches(ifMatch, fileName)) {
        response.setStatus(HttpServletResponse.SC_PRECONDITION_FAILED);
        return response;
    }

    long ifUnmodifiedSince = request.getDateHeader("If-Unmodified-Since");
    if (ifUnmodifiedSince != -1 && ifUnmodifiedSince + 1000 <= fileLastModified) {
        response.setStatus(HttpServletResponse.SC_PRECONDITION_FAILED);
        return response;
    }

    Range full = new Range(0, fileLength - 1, fileLength);
    List<Range> ranges = new ArrayList<Range>();
    String range = request.getHeader("Range");
    if (range != null) {
        if (!range.matches("^bytes=\\d*-\\d*(,\\d*-\\d*)*$")) {
            response.setHeader("Content-Range", "bytes */" + fileLength);
            response.setStatus(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
            return response;
        }

        String ifRange = request.getHeader("If-Range");
        if (ifRange != null && !ifRange.equals(fileName)) {
            try {
                long ifRangeTime = request.getDateHeader("If-Range");
                if (ifRangeTime != -1) {
                    ranges.add(full);
                }
            } catch (IllegalArgumentException ignore) {
                ranges.add(full);
            }
        }

        if (ranges.isEmpty()) {
            for (String part : range.substring(6).split(",")) {
                // Assuming a file with length of 100, the following
                // examples returns bytes at:
                // 50-80 (50 to 80), 40- (40 to length=100), -20
                // (length-20=80 to length=100).
                long start = sublong(part, 0, part.indexOf("-"));
                long end = sublong(part, part.indexOf("-") + 1, part.length());

                if (start == -1) {
                    start = fileLength - end;
                    end = fileLength - 1;
                } else if (end == -1 || end > fileLength - 1) {
                    end = fileLength - 1;
                }

                // Check if Range is syntactically valid. If not, then
                // return 416.
                if (start > end) {
                    response.setHeader("Content-Range", "bytes */" + fileLength); // Required
                    // in
                    // 416.
                    response.setStatus(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
                    return response;
                }

                // Add range.
                ranges.add(new Range(start, end, fileLength));
            }
        }
    }

    // Get content type by file name and set content disposition.
    String disposition = "inline";

    // If content type is unknown, then set the default value.
    // For all content types, see:
    // http://www.w3schools.com/media/media_mimeref.asp
    // To add new content types, add new mime-mapping entry in web.xml.
    if (contentType == null) {
        contentType = "application/octet-stream";
    } else if (!contentType.startsWith("image")) {
        // Else, expect for images, determine content disposition. If
        // content type is supported by
        // the browser, then set to inline, else attachment which will pop a
        // 'save as' dialogue.
        String accept = request.getHeader("Accept");
        disposition = accept != null && accepts(accept, contentType) ? "inline" : "attachment";
    }

    // Initialize response.
    response.reset();
    response.setBufferSize(HttpUtils.DEFAULT_BUFFER_SIZE);
    response.setHeader("Content-Disposition", disposition + ";filename=\"" + fileName + "\"");
    response.setHeader("Accept-Ranges", "bytes");
    response.setHeader("ETag", fileName);
    response.setDateHeader("Last-Modified", fileLastModified);
    response.setDateHeader("Expires", System.currentTimeMillis() + HttpUtils.DEFAULT_EXPIRE_TIME);

    // Send requested file (part(s)) to client
    // ------------------------------------------------

    // Prepare streams.
    InputStream input = null;
    OutputStream output = null;

    try {
        // Open streams.
        input = new BufferedInputStream(dataStream);
        output = response.getOutputStream();

        if (ranges.isEmpty() || ranges.get(0) == full) {

            // Return full file.
            Range r = full;
            response.setContentType(contentType);
            response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total);
            response.setHeader("Content-Length", String.valueOf(r.length));
            copy(input, output, fileLength, r.start, r.length);

        } else if (ranges.size() == 1) {

            // Return single part of file.
            Range r = ranges.get(0);
            response.setContentType(contentType);
            response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total);
            response.setHeader("Content-Length", String.valueOf(r.length));
            response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206.

            // Copy single part range.
            copy(input, output, fileLength, r.start, r.length);

        } else {

            // Return multiple parts of file.
            response.setContentType("multipart/byteranges; boundary=" + HttpUtils.MULTIPART_BOUNDARY);
            response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206.

            // Cast back to ServletOutputStream to get the easy println
            // methods.
            ServletOutputStream sos = (ServletOutputStream) output;

            // Copy multi part range.
            for (Range r : ranges) {
                // Add multipart boundary and header fields for every range.
                sos.println();
                sos.println("--" + HttpUtils.MULTIPART_BOUNDARY);
                sos.println("Content-Type: " + contentType);
                sos.println("Content-Range: bytes " + r.start + "-" + r.end + "/" + r.total);

                // Copy single part range of multi part range.
                copy(input, output, fileLength, r.start, r.length);
            }

            // End with multipart boundary.
            sos.println();
            sos.println("--" + HttpUtils.MULTIPART_BOUNDARY + "--");
        }
    } catch (Exception e) {
        log.error("get file as stream failed", e);
    } finally {
        // Gently close streams.
        close(output);
        close(input);
        close(dataStream);
    }
    return response;
}

From source file:org.bonitasoft.console.common.server.servlet.ResourceServlet.java

/**
 * Get resource file/*from   w  ww.java 2s .com*/
 *
 * @param request
 * @param response
 * @param resourceName
 * @param fileName
 * @throws ServletException
 * @throws UnsupportedEncodingException
 */
protected void getResourceFile(final HttpServletRequest request, final HttpServletResponse response,
        String resourceName, String fileName) throws ServletException, UnsupportedEncodingException {
    byte[] content = null;
    String contentType = null;
    if (resourceName == null) {
        final String errorMessage = "Error while using the servlet to get a resource: the parameter "
                + getResourceParameterName() + " is null.";
        if (LOGGER.isLoggable(Level.WARNING)) {
            LOGGER.log(Level.WARNING, errorMessage);
        }
        throw new ServletException(errorMessage);
    }
    if (fileName == null) {
        final String errorMessage = "Error while using the servlet to get a resource: the parameter "
                + LOCATION_PARAM + " is null.";
        if (LOGGER.isLoggable(Level.WARNING)) {
            LOGGER.log(Level.WARNING, errorMessage);
        }
        throw new ServletException(errorMessage);
    }
    resourceName = URLDecoder.decode(resourceName, "UTF-8");
    fileName = URLDecoder.decode(fileName, "UTF-8");
    response.setCharacterEncoding("UTF-8");

    final File resourcesParentFolder = getResourcesParentFolder(request);
    final String subFolderName = getSubFolderName();
    String subFolderSuffix;
    if (subFolderName != null) {
        subFolderSuffix = File.separator + subFolderName;
    } else {
        subFolderSuffix = "";
    }

    try {
        final File resourceFolder = new File(resourcesParentFolder, resourceName + subFolderSuffix);
        final File file = new File(resourceFolder, fileName);
        final BonitaHomeFolderAccessor tenantFolder = new BonitaHomeFolderAccessor();
        if (!tenantFolder.isInFolder(resourceFolder, resourcesParentFolder)) {
            throw new ServletException("For security reasons, access to this file paths"
                    + resourceFolder.getAbsolutePath() + " is restricted.");
        }
        if (!tenantFolder.isInFolder(file, resourceFolder)) {
            throw new ServletException("For security reasons, access to this file paths"
                    + file.getAbsolutePath() + " is restricted.");
        }
        final String lowerCaseFileName = fileName.toLowerCase();
        if (lowerCaseFileName.endsWith(".jpg")) {
            contentType = "image/jpeg";
        } else if (lowerCaseFileName.endsWith(".jpeg")) {
            contentType = "image/jpeg";
        } else if (lowerCaseFileName.endsWith(".gif")) {
            contentType = "image/gif";
        } else if (lowerCaseFileName.endsWith(".png")) {
            contentType = "image/png";
        } else if (lowerCaseFileName.endsWith(".css") || lowerCaseFileName.endsWith(".less")) {
            contentType = "text/css";
        } else if (lowerCaseFileName.endsWith(".js")) {
            contentType = "application/x-javascript";
        } else if (lowerCaseFileName.endsWith(".html")) {
            contentType = "text/html; charset=UTF-8";
        } else if (lowerCaseFileName.endsWith(".htc")) {
            contentType = "text/x-component";
        } else if (lowerCaseFileName.endsWith(".svg")) {
            contentType = "image/svg+xml";
        } else if (lowerCaseFileName.endsWith(".eot")) {
            contentType = "application/vnd.ms-fontobject";
        } else if (lowerCaseFileName.endsWith(".woff")) {
            contentType = "application/x-font-woff";
        } else if (lowerCaseFileName.endsWith(".ttf")) {
            contentType = "application/x-font-ttf";
        } else if (lowerCaseFileName.endsWith(".otf")) {
            contentType = "application/x-font-opentype";
        } else {
            final FileTypeMap mimetypesFileTypeMap = new MimetypesFileTypeMap();
            contentType = mimetypesFileTypeMap.getContentType(file);
        }
        if (contentType == null) {
            contentType = "application/octet-stream";
        }
        content = FileUtils.readFileToByteArray(file);
        response.setContentType(contentType);
        response.setContentLength(content.length);
        response.setBufferSize(content.length);
        final OutputStream out = response.getOutputStream();
        out.write(content, 0, content.length);
        response.flushBuffer();
        out.close();
    } catch (final IOException e) {
        if (LOGGER.isLoggable(Level.SEVERE)) {
            LOGGER.log(Level.SEVERE, "Error while generating the response.", e);
        }
        throw new ServletException(e.getMessage(), e);
    }
}

From source file:org.codice.proxy.http.HttpProxyCamelHttpTransportServlet.java

@Override
protected void service(HttpServletRequest oldRequest, HttpServletResponse response)
        throws ServletException, IOException {

    //Wrap request and clean the query String
    HttpProxyWrappedCleanRequest request = new HttpProxyWrappedCleanRequest(oldRequest);

    log.trace("Service: {}", request);

    // Is there a consumer registered for the request.
    HttpConsumer consumer = resolve(request);

    if (consumer == null) {
        String path = request.getPathInfo();
        log.trace("Service Request Path = {}", path);
        String endpointName = getEndpointNameFromPath(path);
        log.trace("Endpoint Name = {}", endpointName);

        Route route = camelContext.getRoute(endpointName);
        try {/*from  w  ww .j a va 2 s. c o m*/
            if (route != null) {
                connect((HttpConsumer) route.getConsumer());
            }
        } catch (Exception e) {
            log.debug("Exception while creating consumer", e);
        }
        consumer = resolve(request);
    }

    if (consumer == null) {
        log.debug("No consumer to service request {}", request);
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // are we suspended?
    if (consumer.getEndpoint().isSuspended()) {
        log.debug("Consumer suspended, cannot service request {}", request);
        response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        return;
    }

    if (consumer.getEndpoint().getHttpMethodRestrict() != null
            && !consumer.getEndpoint().getHttpMethodRestrict().equals(request.getMethod())) {
        response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        return;
    }

    if ("TRACE".equals(request.getMethod()) && !consumer.getEndpoint().isTraceEnabled()) {
        response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        return;
    }

    // create exchange and set data on it
    Exchange exchange = new DefaultExchange(consumer.getEndpoint(), ExchangePattern.InOut);

    if (consumer.getEndpoint().isBridgeEndpoint()) {
        exchange.setProperty(Exchange.SKIP_GZIP_ENCODING, Boolean.TRUE);
    }
    if (consumer.getEndpoint().isDisableStreamCache()) {
        exchange.setProperty(Exchange.DISABLE_HTTP_STREAM_CACHE, Boolean.TRUE);
    }

    // we override the classloader before building the HttpMessage just in case the binding
    // does some class resolution
    ClassLoader oldTccl = overrideTccl(exchange);
    HttpHelper.setCharsetFromContentType(request.getContentType(), exchange);
    exchange.setIn(new HttpMessage(exchange, request, response));
    // set context path as header
    String contextPath = consumer.getEndpoint().getPath();
    exchange.getIn().setHeader("CamelServletContextPath", contextPath);

    String httpPath = (String) exchange.getIn().getHeader(Exchange.HTTP_PATH);
    // here we just remove the CamelServletContextPath part from the HTTP_PATH
    if (contextPath != null && httpPath.startsWith(contextPath)) {
        exchange.getIn().setHeader(Exchange.HTTP_PATH, httpPath.substring(contextPath.length()));
    }

    // we want to handle the UoW
    try {
        consumer.createUoW(exchange);
    } catch (Exception e) {
        log.error("Error processing request", e);
        throw new ServletException(e);
    }

    try {
        if (log.isTraceEnabled()) {
            log.trace("Processing request for exchangeId: {}", exchange.getExchangeId());
        }
        // process the exchange
        consumer.getProcessor().process(exchange);
    } catch (Exception e) {
        exchange.setException(e);
    }

    try {
        // now lets output to the response
        if (log.isTraceEnabled()) {
            log.trace("Writing response for exchangeId: {}", exchange.getExchangeId());
        }
        Integer bs = consumer.getEndpoint().getResponseBufferSize();
        if (bs != null) {
            log.trace("Using response buffer size: {}", bs);
            response.setBufferSize(bs);
        }
        consumer.getBinding().writeResponse(exchange, response);
    } catch (IOException e) {
        log.error("Error processing request", e);
        throw e;
    } catch (Exception e) {
        log.error("Error processing request", e);
        throw new ServletException(e);
    } finally {
        consumer.doneUoW(exchange);
        restoreTccl(exchange, oldTccl);
    }
}

From source file:org.sakaiproject.citation.impl.CitationListAccessServlet.java

protected void handleExportRequest(HttpServletRequest req, HttpServletResponse res, Reference ref,
        String format, String subtype)
        throws EntityNotDefinedException, EntityAccessOverloadException, EntityPermissionException {
    if (!ContentHostingService.allowGetResource(req.getParameter("resourceId"))) {
        String url = (req.getRequestURL()).toString();
        String user = "";
        if (req.getUserPrincipal() != null) {
            user = req.getUserPrincipal().getName();
        }/* w  ww.  j av a 2s . c  o  m*/
        throw new EntityPermissionException(user, ContentHostingService.EVENT_RESOURCE_READ,
                ref.getReference());
    }

    String fileName = req.getParameter("resourceDisplayName");
    if (fileName == null || fileName.trim().equals("")) {
        fileName = rb.getString("export.default.filename");
    }

    if (org.sakaiproject.citation.api.CitationService.RIS_FORMAT.equals(format)) {
        String citationCollectionId = req.getParameter("citationCollectionId");
        List<String> citationIds = new java.util.ArrayList<String>();
        CitationCollection collection = null;
        try {
            collection = CitationService.getCollection(citationCollectionId);
        } catch (IdUnusedException e) {
            throw new EntityNotDefinedException(ref.getReference());
        }

        // decide whether to export selected or entire list
        if (org.sakaiproject.citation.api.CitationService.REF_TYPE_EXPORT_RIS_SEL.equals(subtype)) {
            // export selected
            String[] paramCitationIds = req.getParameterValues("citationId");

            if (paramCitationIds == null || paramCitationIds.length < 1) {
                // none selected - do not continue
                try {
                    res.sendError(HttpServletResponse.SC_BAD_REQUEST, rb.getString("export.none_selected"));
                } catch (IOException e) {
                    m_log.warn(
                            "export-selected request received with not citations selected. citationCollectionId: "
                                    + citationCollectionId);
                }

                return;
            }
            citationIds.addAll(Arrays.asList(paramCitationIds));

            fileName = rb.getFormattedMessage("export.filename.selected.ris", fileName);
        } else {
            // export all

            // iterate through ids
            List<Citation> citations = collection.getCitations();

            if (citations == null || citations.size() < 1) {
                // no citations to export - do not continue 
                try {
                    res.sendError(HttpServletResponse.SC_NO_CONTENT, rb.getString("export.empty_collection"));
                } catch (IOException e) {
                    m_log.warn(
                            "export-all request received for empty citation collection. citationCollectionId: "
                                    + citationCollectionId);
                }

                return;
            }

            for (Citation citation : citations) {
                citationIds.add(citation.getId());
            }
            fileName = rb.getFormattedMessage("export.filename.all.ris", fileName);
        }

        // We need to write to a temporary stream for better speed, plus
        // so we can get a byte count. Internet Explorer has problems
        // if we don't make the setContentLength() call.
        StringBuilder buffer = new StringBuilder(4096);
        // StringBuilder contentType = new StringBuilder();

        try {
            collection.exportRis(buffer, citationIds);
        } catch (IOException e) {
            throw new EntityAccessOverloadException(ref.getReference());
        }

        // Set the mime type for a RIS file
        res.addHeader("Content-disposition", "attachment; filename=\"" + fileName + "\"");
        //res.addHeader("Content-Disposition", "attachment; filename=\"citations.RIS\"");
        res.setContentType("application/x-Research-Info-Systems");
        res.setContentLength(buffer.length());

        if (buffer.length() > 0) {
            // Increase the buffer size for more speed.
            res.setBufferSize(buffer.length());
        }

        OutputStream out = null;
        try {
            out = res.getOutputStream();
            if (buffer.length() > 0) {
                out.write(buffer.toString().getBytes());
            }
            out.flush();
            out.close();
        } catch (Throwable ignore) {
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (Throwable ignore) {
                }
            }
        }

    }

}

From source file:org.restcomm.connect.http.filters.FileCacheServlet.java

/**
 * Process the actual request.//from  w w  w  .j  a va 2  s .  c  o  m
 *
 * @param request The request to be processed.
 * @param response The response to be created.
 * @param content Whether the request body should be written (GET) or not
 * (HEAD).
 * @throws IOException If something fails at I/O level.
 */
private void processRequest(HttpServletRequest request, HttpServletResponse response, boolean content)
        throws IOException {
    // Validate the requested file ------------------------------------------------------------

    // Get requested file by path info.
    String requestedFile = request.getPathInfo();
    if (logger.isDebugEnabled()) {
        logger.debug("Requested path:" + requestedFile);
    }

    // Check if file is actually supplied to the request URL.
    if (requestedFile == null) {
        logger.debug("No file requested, return 404.");
        // Do your thing if the file is not supplied to the request URL.
        // Throw an exception, or send 404, or show default/warning page, or just ignore it.
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    Configuration rootConfiguration = (Configuration) request.getServletContext()
            .getAttribute(Configuration.class.getName());
    Configuration runtimeConfiguration = rootConfiguration.subset("runtime-settings");

    String basePath = runtimeConfiguration.getString("cache-path");
    int bufferSize = runtimeConfiguration.getInteger("cache-buffer-size", DEFAULT_BUFFER_SIZE);
    long expireTime = runtimeConfiguration.getLong("cache-expire-time", DEFAULT_EXPIRE_TIME);

    // URL-decode the file name (might contain spaces and on) and prepare file object.
    String fDecodedPath = URLDecoder.decode(requestedFile, "UTF-8");
    File file = new File(basePath, fDecodedPath);

    // Check if file actually exists in filesystem.
    if (!file.exists()) {
        logger.debug("Requested file not found, return 404.");
        // 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);
        return;
    }

    // Prepare some variables. The ETag is an unique identifier of the file.
    String fileName = file.getName();
    long length = file.length();
    long lastModified = file.lastModified();
    String eTag = fileName + "_" + length + "_" + lastModified;
    long expires = System.currentTimeMillis() + expireTime;

    // Validate request headers for caching ---------------------------------------------------
    // If-None-Match header should contain "*" or ETag. If so, then return 304.
    String ifNoneMatch = request.getHeader("If-None-Match");
    if (ifNoneMatch != null && matches(ifNoneMatch, eTag)) {
        logger.debug("IfNoneMatch/Etag not matching, return 304.");
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        response.setHeader("ETag", eTag); // Required in 304.
        response.setDateHeader("Expires", expires); // Postpone cache with 1 week.
        return;
    }

    // If-Modified-Since header should be greater than LastModified. If so, then return 304.
    // This header is ignored if any If-None-Match header is specified.
    long ifModifiedSince = request.getDateHeader("If-Modified-Since");
    if (ifNoneMatch == null && ifModifiedSince != -1 && ifModifiedSince + 1000 > lastModified) {
        logger.debug("IfModifiedSince not matching, return 304.");
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        response.setHeader("ETag", eTag); // Required in 304.
        response.setDateHeader("Expires", expires); // Postpone cache with 1 week.
        return;
    }

    // Validate request headers for resume ----------------------------------------------------
    // If-Match header should contain "*" or ETag. If not, then return 412.
    String ifMatch = request.getHeader("If-Match");
    if (ifMatch != null && !matches(ifMatch, eTag)) {
        logger.debug("ifMatch not matching, return 412.");
        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        return;
    }

    // If-Unmodified-Since header should be greater than LastModified. If not, then return 412.
    long ifUnmodifiedSince = request.getDateHeader("If-Unmodified-Since");
    if (ifUnmodifiedSince != -1 && ifUnmodifiedSince + 1000 <= lastModified) {
        logger.debug("ifUnmodifiedSince not matching, return 412.");
        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        return;
    }

    // Prepare and initialize response --------------------------------------------------------
    // Get content type by file name and content disposition.
    String contentType = getServletContext().getMimeType(fileName);
    String disposition = "inline";

    // If content type is unknown, then set the default value.
    // For all content types, see: http://www.w3schools.com/media/media_mimeref.asp
    // To add new content types, add new mime-mapping entry in web.xml.
    if (contentType == null) {
        contentType = "application/octet-stream";
    }

    // If content type is text, expand content type with the one and right character encoding.
    if (contentType.startsWith("text")) {
        contentType += ";charset=UTF-8";
    } // Else, expect for images, determine content disposition. If content type is supported by
      // the browser, then set to inline, else attachment which will pop a 'save as' dialogue.
    else if (!contentType.startsWith("image")) {
        String accept = request.getHeader("Accept");
        disposition = accept != null && accepts(accept, contentType) ? "inline" : "attachment";
    }

    // Initialize response.
    response.reset();
    response.setBufferSize(bufferSize);
    response.setHeader("Content-Disposition", disposition + ";filename=\"" + fileName + "\"");
    response.setHeader("Accept-Ranges", "bytes");
    response.setHeader("ETag", eTag);
    response.setDateHeader("Last-Modified", lastModified);
    response.setDateHeader("Expires", expires);

    // Send requested file (part(s)) to client ------------------------------------------------
    // Prepare streams.
    FileInputStream input = null;
    OutputStream output = null;

    if (content) {
        logger.debug("Content requested,streaming.");
        // Open streams.
        input = new FileInputStream(file);
        output = response.getOutputStream();
        long streamed = stream(input, output, bufferSize);
        if (logger.isDebugEnabled()) {
            logger.debug("Bytes streamed:" + streamed);
        }
    }

}