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.nema.medical.mint.server.controller.ChangeLogController.java

@RequestMapping("/studies/{uuid}/changelog")
public void studyChangelog(@PathVariable("uuid") final String uuid, final HttpServletRequest req,
        final HttpServletResponse res) throws IOException, JiBXException {

    final Utils.StudyStatus studyStatus = Utils.validateStudyStatus(studiesRoot, uuid, res, studyDAO);
    if (studyStatus != Utils.StudyStatus.OK) {
        return;//w w  w  .  ja  va2s. co m
    }

    final List<org.nema.medical.mint.changelog.Change> changes = new ArrayList<org.nema.medical.mint.changelog.Change>();

    final List<Change> changesFound = changeDAO.findChanges(uuid);
    if (changesFound != null) {
        for (Change change : changesFound) {
            changes.add(new org.nema.medical.mint.changelog.Change(change.getStudyUUID(), change.getIndex(),
                    change.getType(), change.getDateTime(), change.getRemoteHost(), change.getRemoteUser(),
                    change.getOperation()));
        }
    }

    res.setBufferSize(fileResponseBufferSize);
    final ChangeSet changeSet = new ChangeSet(uuid, changes);
    final IBindingFactory bfact = BindingDirectory.getFactory("studyChangelog", ChangeSet.class);
    final IMarshallingContext mctx = bfact.createMarshallingContext();
    mctx.setIndent(2);
    mctx.startDocument("UTF-8", null, res.getOutputStream());
    mctx.getXmlWriter().writePI("xml-stylesheet", xmlStylesheet);
    mctx.marshalDocument(changeSet);
    mctx.endDocument();
}

From source file:org.sakaiproject.site.tool.SiteInfoToolServlet.java

/**
 * generate PDF file containing all site participant
 * @param data/*from  w  w w . j a  va 2s.c o  m*/
 */
public void print_participant(String siteId) {

    HttpServletResponse res = (HttpServletResponse) ThreadLocalManager.get(RequestFilter.CURRENT_HTTP_RESPONSE);

    ByteArrayOutputStream outByteStream = new ByteArrayOutputStream();

    res.addHeader("Content-Disposition", "inline; filename=\"participants.pdf\"");
    res.setContentType("application/pdf");

    Document document = docBuilder.newDocument();

    // get the participant xml document
    generateParticipantXMLDocument(document, siteId);

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

    /*
    // output xml for debugging purpose
    try
    {
       TransformerFactory transformerFactory = TransformerFactory.newInstance();
         Transformer transformer = transformerFactory.newTransformer();
         DOMSource source = new DOMSource(document);
         StreamResult result =  new StreamResult(System.out);
         transformer.transform(source, result);
    }
    catch (Exception e)
    {
               
    }*/

    OutputStream out = null;
    try {
        out = res.getOutputStream();
        if (outByteStream.size() > 0) {
            outByteStream.writeTo(out);
        }
        res.setHeader("Refresh", "0");

        out.flush();
        out.close();
    } catch (Throwable ignore) {
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (Throwable ignore) {
            }
        }
    }
}

From source file:alpha.portal.webapp.controller.PayloadVersionsController.java

/**
 * Gets the payload./*from  w w  w .  jav  a 2  s.  c  om*/
 * 
 * @param request
 *            the request
 * @param response
 *            the response
 * @return the payload
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
@RequestMapping(method = RequestMethod.GET, params = { "seqNumber" })
public String getPayload(final HttpServletRequest request, final HttpServletResponse response)
        throws IOException {
    final Locale locale = request.getLocale();
    if ((request.getParameter("card") == null) || (request.getParameter("case") == null)) {
        this.saveError(request, this.getText("payloadVersions.cardNotFound", locale));
        return "";
    }
    final String cardId = request.getParameter("card");
    final String caseId = request.getParameter("case");

    final AlphaCard currentCard = this.alphaCardManager.get(new AlphaCardIdentifier(caseId, cardId));
    final Payload payload = this.payloadManager
            .getVersion(new PayloadIdentifier(currentCard.getPayload().getPayloadIdentifier().getPayloadId(),
                    Long.parseLong(request.getParameter("seqNumber"))));

    if (payload != null) {

        final BufferedInputStream in = new BufferedInputStream(new ByteArrayInputStream(payload.getContent()));

        response.setBufferSize(payload.getContent().length);
        response.setContentType(payload.getMimeType());
        response.setHeader("Content-Disposition", "attachment; filename=\"" + payload.getFilename() + "\"");
        response.setContentLength(payload.getContent().length);

        FileCopyUtils.copy(in, response.getOutputStream());
        in.close();
        response.getOutputStream().flush();
        response.getOutputStream().close();
    }

    return "redirect:/payloadVersions?case=" + currentCard.getAlphaCardIdentifier().getCaseId() + "&card="
            + currentCard.getAlphaCardIdentifier().getCardId();
}

From source file:org.gss_project.gss.server.rest.RequestHandler.java

/**
 * @param req//from  w w  w.  ja  v a2s  . c om
 * @param resp
 * @param json
 * @throws UnsupportedEncodingException
 * @throws IOException
 */
protected void sendJson(HttpServletRequest req, HttpServletResponse resp, String json)
        throws UnsupportedEncodingException, IOException {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    OutputStreamWriter osWriter = new OutputStreamWriter(stream, "UTF8");
    PrintWriter writer = new PrintWriter(osWriter);

    writer.write(json);
    writer.flush();

    resp.setContentType("application/json;charset=UTF-8");
    resp.setBufferSize(output);
    try {
        copy(null, new ByteArrayInputStream(stream.toByteArray()), resp.getOutputStream(), req, null);
    } catch (ObjectNotFoundException e) {
        // This should never happen with a null first parameter.
        logger.error("", e);
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    } catch (InsufficientPermissionsException e) {
        // This should never happen with a null first parameter.
        logger.error("", e);
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    } catch (RpcException e) {
        logger.error("", e);
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }
}

From source file:com.zimbra.cs.servlet.ZimbraServlet.java

/**
 * Filter the request based on incoming port.  If the allowed.ports
 * parameter is specified for the servlet, the incoming port must
 * match one of the listed ports./* w  w w  . j a  v a2s .  c  o m*/
 */
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    boolean allowed = isRequestOnAllowedPort(request);
    if (!allowed) {
        SoapProtocol soapProto = SoapProtocol.Soap12;
        ServiceException e = ServiceException.FAILURE("Request not allowed on port " + request.getLocalPort(),
                null);
        ZimbraLog.soap.warn(null, e);
        Element fault = SoapProtocol.Soap12.soapFault(e);
        Element envelope = SoapProtocol.Soap12.soapEnvelope(fault);
        byte[] soapBytes = envelope.toUTF8();
        response.setContentType(soapProto.getContentType());
        response.setBufferSize(soapBytes.length + 2048);
        response.setContentLength(soapBytes.length);
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.getOutputStream().write(soapBytes);
        return;
    }
    super.service(request, response);
}

From source file:org.opensubsystems.core.util.servlet.WebUtils.java

/**
 * Serve files to the Internet.//  w w w  . j av a  2s .  c o m
 *
 * @param hsrpResponse - the servlet response.
 * @param strRealPath - real path to the file to server
 * @throws IOException - an error has occurred while accessing the file or writing response
 */
public static void serveFile(HttpServletResponse hsrpResponse, String strRealPath) throws IOException {
    // TODO: Improve: Figure out, how we don't have to serve the file, 
    // but the webserver will!!! (cos.jar has a method for it, but the license
    // is to prohibitive to use it. Maybe Jetty has one too) 
    Properties prpSettings;
    int iWebFileBufferSize;

    prpSettings = Config.getInstance().getProperties();

    // Load default size of buffer to serve files 
    iWebFileBufferSize = PropertyUtils.getIntPropertyInRange(prpSettings, WEBUTILS_WEBFILE_BUFFER_SIZE,
            WEBFILE_BUFFER_DEFAULT_SIZE, "Size of a buffer to serve files ",
            // Use some reasonable lower limit
            4096,
            // This should be really limited 
            // by size of available memory
            100000000);

    ServletOutputStream sosOut = hsrpResponse.getOutputStream();
    byte[] arBuffer = new byte[iWebFileBufferSize];
    File flImage = new File(strRealPath);
    FileInputStream fisReader = new FileInputStream(flImage);

    // get extension of the file
    String strExt = strRealPath.substring(strRealPath.lastIndexOf(".") + 1, strRealPath.length());
    // set content type for particular extension
    hsrpResponse.setContentType(MimeTypeConstants.getMimeType(strExt));
    hsrpResponse.setBufferSize(WEBFILE_BUFFER_DEFAULT_SIZE);
    hsrpResponse.setContentLength((int) flImage.length());

    // TODO: Performance: BufferedInputStream allocate additional internal 
    // buffer so we have two buffers for each file of given size, evaluate 
    // if this is faster than non buffered read and if it is not, then get 
    // rid of it. But the preference is to get rid of this method all together,
    BufferedInputStream bisReader = new BufferedInputStream(fisReader, iWebFileBufferSize);
    int iRead;

    try {
        while (true) {
            iRead = bisReader.read(arBuffer);
            if (iRead != -1) {
                sosOut.write(arBuffer, 0, iRead);
            } else {
                break;
            }
        }
    } finally {
        try {
            fisReader.close();
        } finally {
            sosOut.close();
        }
    }
}

From source file:com.nabla.wapp.server.basic.general.ExportService.java

private boolean exportFile(final String id, final UserSession userSession, final HttpServletResponse response)
        throws IOException, SQLException, InternalErrorException {
    final Connection conn = db.getConnection();
    try {/*from ww w  .  jav  a 2 s  .c om*/
        final PreparedStatement stmt = StatementFormat.prepare(conn, "SELECT * FROM export WHERE id=?;", id);
        try {
            final ResultSet rs = stmt.executeQuery();
            try {
                if (!rs.next()) {
                    if (log.isDebugEnabled())
                        log.debug("failed to find file ID= " + id);
                    return false;
                }
                if (!userSession.getSessionId().equals(rs.getString("userSessionId"))) {
                    if (log.isTraceEnabled())
                        log.trace("invalid user session ID");
                    return false;
                }
                if (log.isTraceEnabled())
                    log.trace("exporting file " + id);
                response.reset();
                response.setBufferSize(DEFAULT_BUFFER_SIZE);
                response.setContentType(rs.getString("content_type"));
                if (rs.getBoolean("output_as_file")) {
                    // IMPORTANT:
                    // MUST be done before calling getOutputStream() otherwise no SaveAs dialogbox
                    response.setHeader("Content-Disposition",
                            MessageFormat.format("attachment; filename=\"{0}\"", rs.getString("name")));
                }
                IOUtils.copy(rs.getBinaryStream("content"), response.getOutputStream());
                /*   final BufferedInputStream input = new BufferedInputStream(rs.getBinaryStream("content"), DEFAULT_BUFFER_SIZE);
                   try {
                      final BufferedOutputStream output = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE);
                      try {
                         final byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
                         int length;
                         while ((length = input.read(buffer)) > 0)
                output.write(buffer, 0, length);
                      } finally {
                         output.close();
                      }
                   } finally {
                      input.close();
                   }*/
            } finally {
                rs.close();
                try {
                    Database.executeUpdate(conn, "DELETE FROM export WHERE id=?;", id);
                } catch (final SQLException e) {
                    if (log.isErrorEnabled())
                        log.error("failed to delete export record: " + e.getErrorCode() + "-" + e.getSQLState(),
                                e);
                }
            }
        } finally {
            stmt.close();
        }
    } finally {
        // remove any orphan export records i.e. older than 48h (beware of timezone!)
        final Calendar dt = Util.dateToCalendar(new Date());
        dt.add(GregorianCalendar.DATE, -2);
        try {
            Database.executeUpdate(conn, "DELETE FROM export WHERE created < ?;", Util.calendarToSqlDate(dt));
        } catch (final SQLException __) {
        }
        conn.close();
    }
    return true;
}

From source file:org.webguitoolkit.ui.http.PageServlet.java

protected void work(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    // fixes for form login - START
    // 15.01.2009: WGTFilter will not be called before web.xml form login page is called.
    // Without WGTFilter we get a NullPointerException in BaseControl constructor.

    // set contenttype to utf-8
    response.setContentType("text/html; charset=utf-8");

    // lets see if there is a session. if not create one...
    DWRController aCompTree = (DWRController) request.getSession(true)
            .getAttribute(DWRController.class.getName());
    if (aCompTree == null) {
        //the dwrcontrool may have created a new tree by now.
        aCompTree = new DWRController();
        request.getSession().setAttribute(DWRController.class.getName(), aCompTree);
    }/*ww  w.j av a2  s.c  o  m*/
    DWRController.setInstance(aCompTree);
    // fixes for form login - END

    // Tried to fix problems with client cookies 13.11.2008 
    Page.setServletRequest(request);
    Page.setServletResponse(response);

    //      response.setContentType("text/html");
    response.setBufferSize(8192);
    PrintWriter out = response.getWriter();
    // how do we determin which Page to instanciate and call?
    // create an import mechanism here.
    String pageName = request.getPathInfo();
    if (pageName == null || pageName.length() <= 1) {
        pageNotFound(request, response);
        return;
    }
    if (pageName.startsWith("/")) {
        pageName = pageName.substring(1);
    }

    // check for page-mappings (i102455/20080220)
    if (pageMapppingMap != null && pageMapppingMap.get(pageName) != null) {
        pageName = (String) pageMapppingMap.get(pageName);
    }

    // prefix with imports....
    Page p = checkPage(pageName);
    for (int i = 0; impArray != null && i < impArray.length && p == null; i++) {
        p = checkPage(impArray[i] + pageName);
        if (p != null)
            break;
        p = checkPage(impArray[i] + '.' + pageName);
    }
    if (p == null) {
        pageNotFound(request, response);
        return;
    }
    // in our current programming model, no more than one thread is allowed
    // to access the tree.
    // with dynamic programming this would be difficult anyway.
    // it seems to be strange to sync this instance, as it is newly created
    // in method checkPage,
    // however, there will be more requests to it from ajax calls and it
    // must be sync there too.
    synchronized (p) {
        p.writePage(out);
    }
    out.close();
}

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/*w w w  . j a v a2 s . com*/
 *          The cache entry for the source resource
 * @param response
 *          The response we are writing to
 * @param range
 *          Range asked by the client
 * @exception IOException
 *              if an input/output error occurs
 */
protected void copy(RepositoryHttpEndpointImpl repoItemHttpElem, HttpServletResponse response, Range range)
        throws IOException {

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

    IOException exception;

    try (ServletOutputStream ostream = response.getOutputStream()) {
        try (InputStream istream = new BufferedInputStream(repoItemHttpElem.createRepoItemInputStream(),
                INPUT_BUFFER_SIZE)) {

            if (range != null) {
                exception = copyStreamsRange(istream, ostream, range);
            } else {
                exception = copyStreams(istream, ostream);
            }

        }
    }

    // Rethrow any exception that has occurred
    if (exception != null) {
        throw exception;
    }
}