Example usage for javax.servlet ServletOutputStream flush

List of usage examples for javax.servlet ServletOutputStream flush

Introduction

In this page you can find the example usage for javax.servlet ServletOutputStream flush.

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes this output stream and forces any buffered output bytes to be written out.

Usage

From source file:org.inbio.ait.web.ajax.controller.TaxonomyAutoCompleteController.java

/**
 * Writes the response in the output!.//from   w w  w.j  a va2 s  .  c  o m
 * @param request
 * @param response
 * @param acnList
 * @return
 * @throws Exception
 */
private ModelAndView writeReponse(HttpServletRequest request, HttpServletResponse response,
        List<AutocompleteNode> acnList) throws Exception {

    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html;charset=UTF-8");
    // Binary output
    ServletOutputStream out = response.getOutputStream();

    if (acnList != null) {

        for (AutocompleteNode sp : acnList) {
            out.println(sp.getItemName() + "\t" + sp.getItemId());
        }
    }

    out.flush();
    out.close();

    return null;
}

From source file:org.zht.framework.filter.jcaptcha.JCaptchaFilter.java

/**
 * ???./*from  ww w  . j  av a  2s  .  c  om*/
 */
protected void genernateCaptchaImage(final HttpServletRequest request, final HttpServletResponse response)
        throws IOException {

    response.setDateHeader("Expires", 0);
    response.addHeader("Pragma", "no-cache");
    response.setHeader("Cache-Control", "no-cache");
    response.setContentType("image/jpeg");

    ServletOutputStream out = response.getOutputStream();
    try {
        String captchaId = request.getSession(true).getId();
        BufferedImage challenge = (BufferedImage) captchaService.getChallengeForID(captchaId,
                request.getLocale());
        ImageIO.write(challenge, "jpg", out);
        out.flush();
    } catch (CaptchaServiceException e) {
        logger.error(e.getMessage(), e);
    } finally {
        out.close();
    }
}

From source file:org.foxbpm.web.controller.AbstWebController.java

/**
 * ?/* w ww .  jav a 2 s  .  c  o  m*/
 * 
 * @param response
 *            ?
 * @param in
 *            ??
 */
public void doResponse(HttpServletResponse response, InputStream in) {
    try {
        ServletOutputStream out = response.getOutputStream();
        response.setContentType("application/octet-stream;charset=UTF-8");
        byte[] buff = new byte[2048];
        int size = 0;
        while (in != null && (size = in.read(buff)) != -1) {
            out.write(buff, 0, size);
        }
        out.flush();
    } catch (Exception e) {
        throw new FoxbpmWebException(e);
    }
}

From source file:org.flowable.app.rest.idm.IdmProfileResource.java

@RequestMapping(value = "/profile-picture", method = RequestMethod.GET)
public void getProfilePicture(HttpServletResponse response) {
    try {//from   www  .  j  a  v a 2  s  . c om
        Pair<String, InputStream> picture = profileService.getProfilePicture();
        if (picture == null) {
            throw new NotFoundException();
        }
        response.setContentType(picture.getLeft());
        ServletOutputStream servletOutputStream = response.getOutputStream();

        byte[] buffer = new byte[32384];
        while (true) {
            int count = picture.getRight().read(buffer);
            if (count == -1)
                break;
            servletOutputStream.write(buffer, 0, count);
        }

        // Flush and close stream
        servletOutputStream.flush();
        servletOutputStream.close();
    } catch (Exception e) {
        throw new InternalServerErrorException("Could not get profile picture", e);
    }
}

From source file:gov.utah.dts.sdc.actions.StudentSearchAction.java

private void pdfOut(byte[] contents, String fileName) throws Exception {

    response.setContentType("application/pdf");
    response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
    ServletOutputStream out = response.getOutputStream();

    out.write(contents);/*from  w w w .j  ava 2s .c o  m*/

    out.flush();
    out.close();

}

From source file:org.dataconservancy.ui.api.CollectionController.java

@RequestMapping(value = "/{idpart}", method = RequestMethod.GET)
public void handleCollectionGetRequest(@RequestHeader(value = "Accept", required = false) String mimeType,
        @RequestHeader(value = "If-Match", required = false) String ifMatch,
        @RequestHeader(value = "If-None-Match", required = false) String ifNoneMatch,
        @RequestHeader(value = "If-Modified-Since", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Date modifiedSince,
        HttpServletRequest request, HttpServletResponse response)
        throws IOException, ArchiveServiceException, BizPolicyException, BizInternalException {

    // Check to see if the user is authenticated (TODO: Spring Security should be responsible for this)
    // Note that the fact that the user has to be authenticated, and further authorized, is a policy decision,
    // but the pattern for the Project and Person controllers is that the Controller has handled this.
    final Person authenticatedUser = getAuthenticatedUser();

    // Rudimentary Accept Header handling; accepted values are */*, application/*, application/xml,
    // application/octet-stream
    if (mimeType != null && !(mimeType.contains(APPLICATION_XML) || mimeType.contains(ACCEPT_WILDCARD)
            || mimeType.contains(ACCEPT_APPLICATION_WILDCARD) || mimeType.contains(ACCEPT_OCTET_STREAM))) {
        response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE,
                "Unacceptable value for 'Accept' header: '" + mimeType + "'");
        return;/* w  w w.j  av  a2  s  .c om*/
    }

    // Resolve the Request URL to the ID of the Collection (in this case URL == ID)
    String collectionId = requestUtil.buildRequestUrl(request);

    if (collectionId == null || collectionId.trim().isEmpty()) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }

    // Get the Collection
    final Collection collection = getCollection(collectionId);

    // Calculate the ETag for the Collection, may be null.
    final String etag;
    if (collection != null) {
        etag = calculateEtag(collection);
    } else {
        etag = null;
    }

    // Handle the 'If-Match' header first; RFC 2616 14.24
    if (this.responseHeaderUtil.handleIfMatch(request, response, this.requestUtil, ifMatch, collection, etag,
            collectionId, "Collection")) {
        return;
    }

    final DateTime lastModified;
    if (collection != null) {
        lastModified = getLastModified(collection.getId());
    } else {
        lastModified = null;
    }

    // Handle the 'If-None-Match' header; RFC 2616 14.26
    if (this.responseHeaderUtil.handleIfNoneMatch(request, response, ifNoneMatch, collection, etag,
            collectionId, lastModified, modifiedSince)) {
        return;
    }

    if (collection == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // Handle the 'If-Modified-Since' header; RFC 2616 14.26
    if (this.responseHeaderUtil.handleIfModifiedSince(request, response, modifiedSince, lastModified)) {
        return;
    }

    // Check to see if the user is authorized
    if (!authzService.canRetrieveCollection(authenticatedUser, collection)) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    // Compose the Business Object Package
    Bop businessPackage = new Bop();
    businessPackage.addCollection(collection);

    // Serialize the package to an output stream
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    bob.buildBusinessObjectPackage(businessPackage, out);
    out.close();

    this.responseHeaderUtil.setResponseHeaderFields(response, etag, out, lastModified);

    // Send the Response
    final ServletOutputStream servletOutputStream = response.getOutputStream();
    IOUtils.copy(new ByteArrayInputStream(out.toByteArray()), servletOutputStream);
    servletOutputStream.flush();
    servletOutputStream.close();
}

From source file:org.bigbluebuttonproject.fileupload.web.FileUploadController.java

/**
 * This handler method overwriting the method in MultiActionController.
 * Its purpose is to stream slide XML from server to the HTTP response.
 * It writes the response using HttpServletResponse.
 * /*from w w w. ja  v  a 2 s  . c  om*/
 * @param request HttpServletRequest
 * @param response HttpServletResponse where the Slide XML is sent
 * 
 * @return the xml slides
 * 
 * @throws Exception the exception
 */
public ModelAndView getXmlSlides(HttpServletRequest request, HttpServletResponse response) throws Exception {
    Integer room = new Integer(request.getParameterValues("room")[0]);

    logger.info("Getting XML Slides [" + room + "]");
    logger.info("Servlet Path = [" + request.getServletPath() + "]");
    logger.info("Host = [" + request.getServerName() + ":" + request.getServerPort() + "]");
    logger.info("Request URI = [" + request.getRequestURI() + "]");
    logger.info("Request URL = [" + request.getRequestURL() + "]");

    // get URL from client request
    int lastIndex = request.getRequestURL().lastIndexOf("/");
    String url = request.getRequestURL().substring(0, lastIndex);

    // create slide presentation descriptor XML
    String slidesXml = createXml(url, getSlidesForRoom(room));
    //      String slidesXml = this.slideDatabase.getSlidesInXml(room);

    logger.info("XML Slides = " + slidesXml);

    // before sending the xml string to the client,
    // set content type and header
    response.setContentType("text/xml");
    //Ask browser not to chache images
    response.setHeader("Cache-Control", "no-cache");

    // get ServletOutputStream from HttpServletResponse
    ServletOutputStream out = response.getOutputStream();
    // send the xml string to client
    out.print(slidesXml);
    out.flush();
    out.close();
    return null;
}

From source file:com.concursive.connect.web.modules.documents.beans.FileDownload.java

/**
 * Description of the Method//from  w w w  .  ja  va 2s .  c o m
 *
 * @param context     Description of the Parameter
 * @param bytes       Description of the Parameter
 * @param contentType Description of the Parameter
 * @throws Exception Description of the Exception
 */
public void sendFile(ActionContext context, byte[] bytes, String contentType) throws Exception {
    context.getResponse().setContentType(contentType);
    if (contentType.startsWith("application")) {
        context.getResponse().setHeader("Content-Disposition", "attachment; filename=\"" + displayName + "\";");
        context.getResponse().setContentLength(bytes.length);
    }
    ServletOutputStream outputStream = context.getResponse().getOutputStream();
    outputStream.write(bytes, 0, bytes.length);
    outputStream.flush();
    outputStream.close();
}

From source file:org.springside.modules.security.jcaptcha.JCaptchaFilter.java

/**
 * ???.//from ww w. ja  v a  2 s  .  c  o m
 */
protected void genernateCaptchaImage(final HttpServletRequest request, final HttpServletResponse response)
        throws IOException {

    ServletUtils.setDisableCacheHeader(response);
    response.setContentType("image/jpeg");

    ServletOutputStream out = response.getOutputStream();
    try {
        String captchaId = request.getSession(true).getId();
        BufferedImage challenge = (BufferedImage) captchaService.getChallengeForID(captchaId,
                request.getLocale());
        ImageIO.write(challenge, "jpg", out);
        out.flush();
    } catch (CaptchaServiceException e) {
        logger.error(e.getMessage(), e);
    } finally {
        out.close();
    }
}

From source file:com.yanbang.portal.controller.PortalController.java

/**
 * ???/*from   w  w w .  j  a v a2 s.  c o m*/
 * 
 * @param request
 * @param response
 * @return
 * @throws Exception
 */
@RequestMapping(params = "action=handleRnd")
public void handleRnd(HttpServletRequest request, HttpServletResponse response) throws Exception {
    response.setHeader("Cache-Control", "no-store");
    response.setHeader("Pragma", "no-cache");
    response.setDateHeader("Expires", 0L);
    response.setContentType("image/jpeg");
    BufferedImage image = new BufferedImage(65, 25, BufferedImage.TYPE_INT_RGB);
    Graphics g = image.getGraphics();
    g.setColor(Color.GRAY);
    g.fillRect(0, 0, 65, 25);
    g.setColor(Color.yellow);
    Font font = new Font("", Font.BOLD, 20);
    g.setFont(font);
    Random r = new Random();
    String rnd = "";
    int ir = r.nextInt(10);
    rnd = rnd + "" + ir;
    g.drawString("" + ir, 5, 18);
    g.setColor(Color.red);
    ir = r.nextInt(10);
    rnd = rnd + "" + ir;
    g.drawString("" + ir, 20, 18);
    g.setColor(Color.blue);
    ir = r.nextInt(10);
    rnd = rnd + "" + ir;
    g.drawString("" + ir, 35, 18);
    g.setColor(Color.green);
    ir = r.nextInt(10);
    rnd = rnd + "" + ir;
    g.drawString("" + ir, 50, 18);
    request.getSession().setAttribute("RND", rnd);
    ServletOutputStream out = response.getOutputStream();
    out.write(ImageUtil.imageToBytes(image, "gif"));
    out.flush();
    out.close();
}