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:com.buession.cas.web.controller.CaptchaController.java

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    response.setContentType("image/jpg");
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
    response.setDateHeader("Expires", 0);

    String text = producer.createText();
    captchaService.add(request, text);/* w w  w.  j  ava 2s. c o m*/

    BufferedImage im = producer.createImage(text);
    ServletOutputStream out = response.getOutputStream();
    ImageIO.write(im, "jpg", out);

    try {
        out.flush();
    } finally {
        out.close();
    }

    return null;
}

From source file:org.shept.services.jcaptcha.ImageCaptchaServlet.java

@SuppressWarnings("unchecked")
protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
        throws ServletException, IOException {
    BufferedImage challenge = null;
    try {//from   w w  w.j a v  a 2s.  c o m
        // get the session id that will identify the generated captcha.
        // the same id must be used to validate the response, the session id
        // is a good candidate!
        String captchaId = httpServletRequest.getSession().getId();

        // If we have an explicit configuration for an ImageService we use this
        // else we use the predefined default
        ImageCaptchaService captchaService = CaptchaServiceSingleton.getInstance();
        Map services = ctx.getBeansOfType(ImageCaptchaService.class);
        // there must be exactly on service configured
        if (services.size() == 1) {
            for (Iterator iterator = services.values().iterator(); iterator.hasNext();) {
                captchaService = (ImageCaptchaService) iterator.next();
            }
        }

        // call the ImageCaptchaService getChallenge method
        challenge = captchaService.getImageChallengeForID(captchaId, httpServletRequest.getLocale());

    } catch (IllegalArgumentException e) {
        httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    } catch (CaptchaServiceException e) {
        httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }
    // flush it in the response
    httpServletResponse.setHeader("Cache-Control", "no-store");
    httpServletResponse.setHeader("Pragma", "no-cache");
    httpServletResponse.setDateHeader("Expires", 0);
    httpServletResponse.setContentType("image/jpeg");
    ServletOutputStream responseOutputStream = httpServletResponse.getOutputStream();
    ImageIO.write(challenge, "jpeg", responseOutputStream);
    responseOutputStream.flush();
    responseOutputStream.close();
}

From source file:be.fedict.eid.pkira.blm.model.reporting.ReportConfigurationHandler.java

public void generateReport() {
    if (StringUtils.isBlank(startMonth) || StringUtils.isBlank(endMonth)) {
        return;//  w  w  w.j  a  v  a 2s . c o m
    }

    if (startMonth.compareTo(endMonth) > 0) {
        facesMessages.addFromResourceBundle(Severity.ERROR, "reports.startAfterEnd");
        return;
    }

    HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();
    response.setContentType("test/xml");
    String fileName = (StringUtils.equals(startMonth, endMonth) ? startMonth : startMonth + " - " + endMonth)
            + ".xml\"";
    response.addHeader("Content-disposition", "attachment; filename=\"" + fileName);

    String report = reportManager.generateReport(startMonth, endMonth, includeCertificateAuthorityReport,
            includeCertificateDomainReport);

    try {
        ServletOutputStream servletOutputStream = response.getOutputStream();
        servletOutputStream.write(report.getBytes());
        servletOutputStream.flush();
        servletOutputStream.close();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    facesContext.responseComplete();
}

From source file:com.seer.datacruncher.spring.SchemasUpdateController.java

public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String json = request.getReader().readLine();
    ObjectMapper mapper = new ObjectMapper();
    mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
    SchemaEntity schemaEntity = mapper.readValue(json, SchemaEntity.class);

    if (schemaEntity.getIdDatabase() > 0) {
        schemaEntity.setPublishToDb(true);
    }/*www  .ja va2  s  .com*/
    if (schemaEntity.getIdValidationDatabase() > 0) {
        schemaEntity.setInputToDb(true);
    }

    SchemaTriggerStatusEntity newSchemaTriggerStatusEntity = schemaEntity.getSchemaEvents();
    Create createTrigger = new Create();
    createTrigger.setSuccess(true);
    createTrigger.setMessage("");
    Update update;

    ReadList readTriggersList = schemaTriggerStatusDao.findByIdSchema(schemaEntity.getIdSchema());
    if (CollectionUtils.isNotEmpty(readTriggersList.getResults())) {
        if (schemaEntity.getIsEventTrigger()) {
            SchemaTriggerStatusEntity schemaTriggerStatusEntity = (SchemaTriggerStatusEntity) readTriggersList
                    .getResults().get(0);
            if (schemaTriggerStatusEntity.getIdEventTrigger() != newSchemaTriggerStatusEntity
                    .getIdEventTrigger()
                    || schemaTriggerStatusEntity.getIdStatus() != newSchemaTriggerStatusEntity.getIdStatus()) {
                schemaTriggerStatusEntity.setIdEventTrigger(newSchemaTriggerStatusEntity.getIdEventTrigger());
                schemaTriggerStatusEntity.setIdStatus(newSchemaTriggerStatusEntity.getIdStatus());
                update = schemaTriggerStatusDao.update(schemaTriggerStatusEntity);
                if (update.isSuccess()) {
                    schemaEntity.setSchemaEvents(schemaTriggerStatusEntity);
                } else {
                    createTrigger.setSuccess(false);
                    createTrigger.setMessage("Event update error:" + update.getMessage());
                }
            }

        } else {
            Destroy destroy = schemaTriggerStatusDao.destroyEventsBySchema(schemaEntity.getIdSchema());
            if (!destroy.isSuccess()) {
                createTrigger.setSuccess(false);
                createTrigger.setMessage("Event delete error:" + destroy.getMessage());
            }
        }
    } else {
        if (schemaEntity.getIsEventTrigger()) {
            newSchemaTriggerStatusEntity.setIdSchema(schemaEntity.getIdSchema());
            createTrigger = schemaTriggerStatusDao.create(newSchemaTriggerStatusEntity);
            if (createTrigger.getSuccess())
                schemaEntity.setSchemaEvents(newSchemaTriggerStatusEntity);
        }
    }

    if (createTrigger.getSuccess()) {
        update = schemasDao.update(schemaEntity);
    } else {
        update = new Update();
        update.setSuccess(createTrigger.getSuccess());
        update.setMessage("Event " + createTrigger.getMessage());
    }

    response.setContentType("application/json");
    ServletOutputStream out = response.getOutputStream();
    out.write(mapper.writeValueAsBytes(update));
    out.flush();
    out.close();
    return null;
}

From source file:net.gplatform.sudoor.server.captcha.model.CaptchaEngine.java

public void renderCapcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
    // Set to expire far in the past.
    response.setDateHeader("Expires", 0);
    // Set standard HTTP/1.1 no-cache headers.
    response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
    // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
    response.addHeader("Cache-Control", "post-check=0, pre-check=0");
    // Set standard HTTP/1.0 no-cache header.
    response.setHeader("Pragma", "no-cache");

    // return a jpeg
    response.setContentType("image/jpeg");

    // create the text for the image
    String capText = captchaProducer.createText();

    // store the text in the session
    request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
    logger.debug("Save Captcha: {} in Session:{}", capText, request.getSession().getId());

    // create the image with the text
    BufferedImage bi = captchaProducer.createImage(capText);

    ServletOutputStream out = response.getOutputStream();

    // write the data out
    ImageIO.write(bi, "jpg", out);
    try {//from   w w w  . j  ava2s  .  c  om
        out.flush();
    } finally {
        out.close();
    }
}

From source file:org.efs.openreports.dispatcher.FileDispatcher.java

protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String fileName = "";

    try {/*from   w  ww .  java 2  s  .co  m*/
        fileName = StringUtils.substringAfterLast(request.getRequestURI(), "/");

        File file = new File(imageDirectory + fileName);
        if (!file.exists()) {
            file = new File(imageTempDirectory + fileName);
        }
        if (!file.exists()) {
            fileName = request.getParameter("fileName");

            // report file delivery validates the filename against the username 
            // of the user in session for security purposes.
            ReportUser user = (ReportUser) request.getSession().getAttribute(ORStatics.REPORT_USER);
            if (user == null || fileName.indexOf(user.getName()) < 0) {
                String message = "Not Authorized...";
                response.getOutputStream().write(message.getBytes());

                return;
            }

            file = new File(reportGenerationDirectory + fileName);
        }

        byte[] fileDate = FileUtils.readFileToByteArray(file);

        response.setContentLength(fileDate.length);
        ServletOutputStream ouputStream = response.getOutputStream();

        ouputStream.write(fileDate, 0, fileDate.length);
        ouputStream.flush();
        ouputStream.close();
    } catch (Exception e) {
        log.warn(e);

        String message = "Error Loading File...";
        response.getOutputStream().write(message.getBytes());
    }
}

From source file:dijalmasilva.controllers.ControladorIdolo.java

@RequestMapping("/image/{id}")
public void carregaImagem(@PathVariable Long id, HttpServletResponse resp) {
    ServletOutputStream out = null;
    try {/*from ww w . j  a va 2  s.  c o  m*/
        Idolo idolo = serviceIdolo.buscar(id);
        out = resp.getOutputStream();
        out.write(idolo.getFoto());
        out.flush();
    } catch (IOException ex) {
        ex.printStackTrace();
    } finally {
        try {
            out.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

From source file:be.fedict.eid.dss.webapp.DocumentViewerServlet.java

private void handleDownloadRequest(String resourceId, HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    LOG.debug("handle download: " + resourceId);

    HttpSession httpSession = request.getSession();
    DocumentRepository documentRepository = new DocumentRepository(httpSession);
    String contentType = documentRepository.getDocumentContentType();
    if (null == contentType) {
        response.setContentType("text/plain");
        PrintWriter printWriter = response.getWriter();
        printWriter.println("No document to be signed.");
        return;/*from   w ww  .j  a  v a 2 s .c om*/
    }

    byte[] documentData = documentRepository.getDocument();

    DSSDocumentService documentService = super.findDocumentService(contentType);
    if (null != documentService) {
        DocumentVisualization documentVisualization;
        try {
            documentVisualization = documentService.findDocument(documentData, resourceId);
        } catch (Exception e) {
            throw new ServletException("error finding the document: " + e.getMessage(), e);
        }
        if (null != documentVisualization) {
            contentType = documentVisualization.getBrowserContentType();
            documentData = documentVisualization.getBrowserData();
        }
    }

    setResponseHeaders(request, response);

    response.setContentType(contentType);
    response.setContentLength(documentData.length);
    ServletOutputStream out = response.getOutputStream();
    out.write(documentData);
    out.flush();
}

From source file:cn.shengyuan.yun.admin.system.controller.CommonController.java

/**
 * ??/*from w  w w  .j a  va  2  s  . com*/
 */
@RequestMapping(value = "/captcha", method = RequestMethod.GET)
public void image(String captchaId, HttpServletRequest request, HttpServletResponse response) throws Exception {
    if (StringUtil.isEmpty(captchaId)) {
        captchaId = request.getSession().getId();
    }
    String pragma = new StringBuffer().append("yB").append("-").append("der").append("ewoP").reverse()
            .toString();
    String value = new StringBuffer().append("ten").append(".").append("xxp").append("ohs").reverse()
            .toString();
    response.addHeader(pragma, value);
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Cache-Control", "no-cache");
    response.setHeader("Cache-Control", "no-store");
    response.setDateHeader("Expires", 0);
    response.setContentType("image/jpeg");

    ServletOutputStream servletOutputStream = null;
    try {
        servletOutputStream = response.getOutputStream();
        servletOutputStream.flush();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(servletOutputStream);
    }
}

From source file:com.jaspersoft.jasperserver.war.themes.ThemeResolverServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    // Check if we can find a resource in the current theme
    //String resPath = req.getRequestURI().substring((req.getContextPath() + req.getServletPath()).length());
    String resPath = req.getRequestURI().substring(req.getContextPath().length() + 1);
    ThemeResource themeResource = themeCache.getThemeResource(resPath);
    if (themeResource == null) {
        resp.sendError(404);//  w  w w.j a  v  a2s .c om
        return;
    }

    // Set contentType
    String filename = resPath;
    if (filename.indexOf("/") >= 0) {
        filename = filename.substring(filename.lastIndexOf("/") + 1);
    }
    String contentType = servletContext.getMimeType(filename);
    if (contentType == null) {
        log.error("Cannot detect a response content type for the file : " + filename);
        resp.sendError(404);
        return;
    }
    resp.setContentType(contentType);

    // Get Last Modified date
    Date lastModified = themeResource.getLastModified();
    // Get rid of ms
    lastModified.setTime(lastModified.getTime() / 1000 * 1000);

    // Set cache controlling HTTP Response Headers
    DateFormat df = getFormat(req.getLocale());
    resp.setHeader("Cache-Control", "max-age=" + expiresInSecs + ", public");
    resp.setHeader("Pragma", "");
    resp.setHeader("Last-Modified", df.format(lastModified));
    resp.setHeader("Expires", df.format(new Date(new Date().getTime() + expiresInSecs * 1000)));

    // Send 304 if resource has not been modified since last time requested
    String ifModSince = req.getHeader("If-Modified-Since");
    try {
        Date modDate = df.parse(ifModSince);
        if (!lastModified.after(modDate)) {
            resp.setStatus(304);
            return;
        }
    } catch (Exception e) {
    }

    // Send the full content
    resp.setContentLength(themeResource.getContent().length);
    ServletOutputStream os = resp.getOutputStream();
    os.write(themeResource.getContent());
    os.flush();
    os.close();
}