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.energy_home.jemma.internal.shapi.HapProxy.java

private static void initResponse(HttpServletResponse response) {
    response.setContentType(HTTP_RESPONSE_TYPE);
    response.setBufferSize(HTTP_RESPONSE_BUFFER_SIZE);
}

From source file:ch.entwine.weblounge.common.impl.request.Http11ProtocolHandler.java

/**
 * Method generateResponse.//from   ww  w  .  j  ava  2s.  co m
 * 
 * @param resp
 * @param type
 * @param is
 * @return boolean
 * @throws IOException
 *           if generating the response fails
 */
public static boolean generateResponse(HttpServletResponse resp, Http11ResponseType type, InputStream is)
        throws IOException {

    /* first generate the response headers */
    generateHeaders(resp, type);

    /* adjust the statistics */
    ++stats[STATS_BODY_GENERATED];
    incResponseStats(type.type, bodyStats);

    /* generate the response body */
    try {
        if (resp.isCommitted())
            log.warn("Response is already committed!");
        switch (type.type) {
        case RESPONSE_OK:
            if (!type.isHeaderOnly() && is != null) {
                resp.setBufferSize(BUFFER_SIZE);
                OutputStream os = null;
                try {
                    os = resp.getOutputStream();
                    IOUtils.copy(is, os);
                } catch (IOException e) {
                    if (RequestUtils.isCausedByClient(e))
                        return true;
                } finally {
                    IOUtils.closeQuietly(os);
                }
            }
            break;

        case RESPONSE_PARTIAL_CONTENT:
            if (type.from < 0 || type.to < 0 || type.from > type.to || type.to > type.size) {
                resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        "Invalid partial content parameters");
                log.warn("Invalid partial content parameters");
            } else if (!type.isHeaderOnly() && is != null) {
                resp.setBufferSize(BUFFER_SIZE);
                OutputStream os = resp.getOutputStream();
                if (is.skip(type.from) != type.from) {
                    resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                            "Premature end of input stream");
                    log.warn("Premature end of input stream");
                    break;
                }
                try {

                    /* get the temporary buffer for this thread */
                    byte[] tmp = buffer.get();
                    if (tmp == null) {
                        tmp = new byte[BUFFER_SIZE];
                        buffer.set(tmp);
                    }

                    int read = type.to - type.from;
                    int copy = read;
                    int write = 0;

                    read = is.read(tmp);
                    while (copy > 0 && read >= 0) {
                        copy -= read;
                        write = copy > 0 ? read : read + copy;
                        os.write(tmp, 0, write);
                        stats[STATS_BYTES_WRITTEN] += write;
                        read = is.read(tmp);
                    }
                    if (copy > 0) {
                        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                "Premature end of input stream");
                        log.warn("Premature end of input stream");
                        break;
                    }
                    os.flush();
                    os.close();
                } catch (SocketException e) {
                    log.debug("Request cancelled by client");
                }
            }
            break;

        case RESPONSE_NOT_MODIFIED:
            /* NOTE: we MUST NOT return any content (RFC 2616)!!! */
            break;

        case RESPONSE_PRECONDITION_FAILED:
            if (type.err == null)
                resp.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
            else
                resp.sendError(HttpServletResponse.SC_PRECONDITION_FAILED, type.err);
            break;

        case RESPONSE_REQUESTED_RANGE_NOT_SATISFIABLE:
            if (type.err == null)
                resp.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
            else
                resp.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE, type.err);
            break;

        case RESPONSE_METHOD_NOT_ALLOWED:
            if (type.err == null)
                resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            else
                resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, type.err);
            break;

        case RESPONSE_INTERNAL_SERVER_ERROR:
        default:
            if (type.err == null)
                resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            else
                resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, type.err);
        }
    } catch (IOException e) {
        if (e instanceof EOFException) {
            log.debug("Request canceled by client");
            return true;
        }
        ++stats[STATS_ERRORS];
        String message = e.getCause() != null ? e.getCause().getMessage() : e.getMessage();
        Throwable cause = e.getCause() != null ? e.getCause() : e;
        log.warn("I/O exception while sending response: {}", message, cause);
        throw e;
    }

    return true;
}

From source file:action.ImageResult.java

public void execute(ActionInvocation invocation) throws IOException {
    ImageAction action = (ImageAction) invocation.getAction();
    HttpServletResponse response = ServletActionContext.getResponse();
    ServletOutputStream sos = response.getOutputStream();
    BufferedOutputStream output = null;
    byte[] imgBytes = action.getCustomImageInBytes();
    System.out.println("imgBytes--->" + imgBytes.toString());

    response.reset();/*w w  w  . j  av a  2s  .c o  m*/
    response.setBufferSize(10240);
    response.setContentType("image/png");
    response.setContentLength(action.getCustomImageInBytes().length);
    response.setHeader("Content-Disposition", "inline; filename=\"sss\"");
    //response.getOutputStream().write(action.getCustomImageInBytes());
    // response.getOutputStream().flush();
    try {
        output = new BufferedOutputStream(response.getOutputStream(), 10240);
        output.write(imgBytes);
    } finally {
        // Gently close streams.
        if (output != null) {
            try {
                output.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:org.eclipse.rwt.widgets.codemirror.internal.CodeMirrorJSService.java

public void service() throws IOException, ServletException {
    // request/*from   w  w w  .  java 2  s .com*/
    final HttpServletRequest request = RWT.getRequest();
    log.debug("Request: " + request.getPathInfo());
    String filename = request.getParameter(FILENAME_PARAM);

    // response
    final HttpServletResponse response = RWT.getResponse();
    final PrintWriter out = response.getWriter();

    if (filename.endsWith(".js")) {
        response.setContentType("text/javascript");
    } else if (filename.endsWith(".css")) {
        response.setContentType("text/css");
    }
    response.setHeader("Cache-Control", "no-cache");
    response.setBufferSize(4096);

    // copy resource to response out
    URL res = CodeMirrorPlugin.getDefault().getBundle().getResource(RESOURCE_BASE + "/" + filename);
    InputStream in = null;
    try {
        in = new BufferedInputStream(res.openStream());
        for (int c = in.read(); c != -1; c = in.read()) {
            out.write(c);
        }
    } finally {
        if (in != null) {
            in.close();
        }
    }
}

From source file:cz.zcu.kiv.eegdatabase.logic.controller.nif.NIFMultiController.java

/**
 * Generates a csv file from scenarios//  ww  w  .j  a  v a 2 s.c om
 * @param request
 * @param response
 * @return
 * @throws Exception
 */
public ModelAndView getScenariosCSVFile(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    log.debug("Controller for creating csv file for NIF");
    OutputStream out = null;
    int headerBufferSize = 8096;

    response.setHeader("Content-Type", "text/csv");
    response.setContentType("text/csv");
    response.setHeader("Content-Disposition", "attachment;filename=EEGbase_scenarios.csv");

    log.debug("Creating output stream");
    response.setStatus(HttpServletResponse.SC_OK);
    response.setBufferSize(headerBufferSize);

    log.debug("Generating csv");
    out = csvFactory.generateScenariosCsvFile();
    ByteArrayOutputStream bout = (ByteArrayOutputStream) out;
    response.getOutputStream().write(bout.toByteArray());
    return null;
}

From source file:cz.zcu.kiv.eegdatabase.logic.controller.nif.NIFMultiController.java

/**
* Generates a csv file from experiments//  w w  w. j  a  v a  2s  .  c o m
* @param request
* @param response
* @return
* @throws Exception
*/
public ModelAndView getExperimentsCSVFile(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    log.debug("Controller for csv file with creating experiments for NIF");
    OutputStream out = null;
    int headerBufferSize = 8096;

    response.setHeader("Content-Type", "text/csv");
    response.setContentType("text/csv");
    response.setHeader("Content-Disposition", "attachment;filename=EEGbase_experiments.csv");

    log.debug("Creating output stream");
    response.setStatus(HttpServletResponse.SC_OK);
    response.setBufferSize(headerBufferSize);

    log.debug("Generating csv");
    out = csvFactory.generateExperimentsCsvFile();
    ByteArrayOutputStream bout = (ByteArrayOutputStream) out;
    response.getOutputStream().write(bout.toByteArray());
    return null;
}

From source file:org.kaaproject.kaa.sandbox.web.servlet.ProjectFileServlet.java

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    ProjectDataKey key = extractKey(request);
    if (key != null) {
        try {/* w ww.  j  a  v  a 2  s. c o m*/
            FileData fileData = cacheService.getProjectFile(key);
            if (fileData != null) {
                if (fileData.getContentType() != null) {
                    response.setContentType(fileData.getContentType());
                }
                ServletUtils.prepareDisposition(request, response, fileData.getFileName());
                response.setContentLength(fileData.getFileData().length);
                response.setBufferSize(BUFFER);
                response.getOutputStream().write(fileData.getFileData());
                response.flushBuffer();
            } else {
                logger.error("File data not found in cache for requested parameters: projectId [{}]  type [{}]",
                        key.getProjectId(), key.getProjectDataType());
            }
        } catch (Exception e) {
            logger.error("Unexpected error in ProjectFileServlet.doGet: ", e);
        }
    }
}

From source file:cz.zcu.kiv.eegdatabase.logic.controller.semantic.SemanticMultiController.java

/**
 * Generates an ontology document from POJO objects.
 * This method gives the Jena's output./* w w w.  j av  a2 s .  c om*/
 *
 * @param request
 * @param response
 * @return
 * @throws Exception
 */
public ModelAndView getOntology(HttpServletRequest request, HttpServletResponse response) throws Exception {
    log.debug("Controller for transforming POJO object to resources of semantic web");
    OutputStream out = null;
    InputStream is = null;
    int headerBufferSize = 8096;
    String syntax = request.getParameter("type");

    response.setHeader("Content-Type", "application/rdf+xml");
    response.setContentType("application/rdf+xml");
    response.setHeader("Content-Disposition", "attachment;filename=eegdatabase.owl");

    log.debug("Creating output stream");
    response.setStatus(HttpServletResponse.SC_OK);
    response.setBufferSize(headerBufferSize);
    out = response.getOutputStream();
    log.debug("Generating RDF");

    is = semanticFactory.getOntology(syntax);

    copy(is, out);
    out.flush();
    out.close();
    return null;
}

From source file:cz.zcu.kiv.eegdatabase.logic.controller.semantic.SemanticMultiController.java

/**
 * Generates an ontology document from POJO objects.
 * This method gives the Jena's output.//from w w w. j ava  2  s .c  om
 *
 * @param request
 * @param response
 * @return
 * @throws Exception
 */
public ModelAndView getOntologyStructure(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    log.debug("Controller for transforming POJO object to resources of semantic web");
    OutputStream out = null;
    InputStream is = null;
    int headerBufferSize = 8096;
    String syntax = request.getParameter("type");

    response.setHeader("Content-Type", "application/rdf+xml");
    response.setContentType("application/rdf+xml");
    response.setHeader("Content-Disposition", "attachment;filename=eegdatabase.owl");

    log.debug("Creating output stream");
    response.setStatus(HttpServletResponse.SC_OK);
    response.setBufferSize(headerBufferSize);
    out = response.getOutputStream();
    log.debug("Generating RDF");

    is = semanticFactory.getOntologySchema(syntax);

    copy(is, out);
    out.flush();
    out.close();
    return null;
}

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

@RequestMapping("/types/{type}")
public String typeEntry(@PathVariable("type") final String type, final HttpServletRequest req,
        final HttpServletResponse res, final ModelMap map) {
    if (StringUtils.isBlank(type)) {
        res.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        map.put("error_msg", "must specify type");
        return "error";
    }/*from   w w w  .  j a va 2  s .  c  o  m*/

    //In case of file extension, take off .xml for name
    final String typeName = type.endsWith(".xml") ? type.substring(0, ".xml".length()) : type;
    final File typeFile = availableTypeFiles.get(typeName);

    if (typeFile.exists() && typeFile.canRead()) {
        try {
            res.setContentType("text/xml");
            res.setContentLength(Long.valueOf(typeFile.length()).intValue());
            res.setBufferSize(fileResponseBufferSize);
            Utils.streamFile(typeFile, res.getOutputStream(), fileStreamBufferSize);
        } catch (final IOException e) {
            if (!res.isCommitted()) {
                res.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                map.put("error_msg", "Failed to stream type definition document");
                return "error";
            }
        }
    } else {
        res.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        map.put("error_msg", "Type specified does not exist");
        return "error";
    }

    return null;
}