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:info.magnolia.cms.servlets.Spool.java

/**
 * @param resource File to be returned to the client
 * @param response HttpServletResponse/*from ww  w.ja  va 2 s.  c  o  m*/
 * @return <code>true</code> if the file has been written to the servlet output stream without errors
 * @throws IOException for error in accessing the resource or the servlet output stream
 */
private boolean spool(File resource, HttpServletResponse response) throws IOException {
    FileInputStream in = new FileInputStream(resource);

    try {
        ServletOutputStream os = response.getOutputStream();
        byte[] buffer = new byte[8192];
        int read = 0;
        while ((read = in.read(buffer)) > 0) {
            os.write(buffer, 0, read);
        }
        os.flush();
        IOUtils.closeQuietly(os);
    } catch (IOException e) {
        // only log at debug level, tomcat usually throws a ClientAbortException anytime the user stop loading the
        // page
        if (log.isDebugEnabled())
            log.debug("Unable to spool resource due to a " + e.getClass().getName() + " exception", e); //$NON-NLS-1$ //$NON-NLS-2$
        return false;
    } finally {
        IOUtils.closeQuietly(in);
    }
    return true;
}

From source file:com.nzion.web.PdfServlet.java

@Override
protected void service(HttpServletRequest reqqest, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("application/plm");
    response.setHeader("Content-Disposition", "attachment; filename=2D.plm");
    ServletOutputStream outputStream = response.getOutputStream();
    BufferedInputStream bufferedInputStream = new BufferedInputStream(
            new FileInputStream(new File("F:\\PDF_Stamping\\2D\\2D.zip")));
    IOUtils.copy(bufferedInputStream, outputStream);
    bufferedInputStream.close();/*from w  w w  . j  av a 2s. com*/
    outputStream.flush();
}

From source file:com.seer.datacruncher.profiler.spring.ProfilerLoadController.java

public ModelAndView getColumnNames(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    HttpSession session = request.getSession();

    ObjectMapper mapper = new ObjectMapper();

    ServletOutputStream out;
    response.setContentType("application/text");
    out = response.getOutputStream();/*www. j  a v a  2 s  .c  o  m*/

    out.write(mapper.writeValueAsBytes(session.getAttribute("columnNames")));
    out.flush();
    out.close();

    return null;
}

From source file:com.webpagebytes.cms.utility.HttpServletToolbox.java

public void writeBodyResponseAsJson(HttpServletResponse response, String data, Map<String, String> errors) {

    try {/*from   w  w w . jav  a 2s  . c o m*/
        org.json.JSONObject jsonResponse = new org.json.JSONObject();
        org.json.JSONObject jsonErrors = new org.json.JSONObject();
        if (errors == null || errors.keySet().size() == 0) {
            jsonResponse.put("status", "OK");
        } else {
            jsonResponse.put("status", "FAIL");
            for (String key : errors.keySet()) {
                jsonErrors.put(key, errors.get(key));
            }
        }
        jsonResponse.put("errors", jsonErrors);
        jsonResponse.put("payload", data);
        String jsonString = jsonResponse.toString();
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        ServletOutputStream writer = response.getOutputStream();
        byte[] utf8bytes = jsonString.getBytes("UTF-8");
        writer.write(utf8bytes);
        response.setContentLength(utf8bytes.length);
        writer.flush();

    } catch (Exception e) {
        try {
            String errorResponse = "{\"status\":\"FAIL\",\"payload\":\"{}\",\"errors\":{\"reason\":\"WB_UNKNOWN_ERROR\"}}";
            ServletOutputStream writer = response.getOutputStream();
            response.setContentType("application/json");
            byte[] utf8bytes = errorResponse.getBytes("UTF-8");
            response.setContentLength(utf8bytes.length);
            writer.write(utf8bytes);
            writer.flush();
        } catch (IOException ioe) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

}

From source file:de.micromata.genome.logging.loghtmlwindow.LogHtmlWindowServlet.java

private void sendResponse(HttpServletResponse resp, JsonValue val) throws IOException {
    resp.setContentType("application/json");
    String sr = val.toString();
    ServletOutputStream os = resp.getOutputStream();
    os.write(sr.getBytes("UTF-8"));
    os.flush();
}

From source file:com.hyeb.back.controller.CommonController.java

/**
 * ??//w ww.  j  av  a2 s .  c  o m
 */
@RequestMapping(value = "/captcha", method = RequestMethod.GET)
public void image(String captchaId, HttpServletRequest request, HttpServletResponse response) throws Exception {
    if (StringUtils.isEmpty(captchaId)) {
        captchaId = request.getSession().getId();
    }
    String pragma = new StringBuffer().append("PowderBy").toString();
    String value = new StringBuffer().append("hyeb").toString();
    response.addHeader(pragma, value);
    response.setHeader("Pragma", "no-cache");//HTTP1.0Pragma ??Pragmano-cache,??????? Pragma
    response.setHeader("Cache-Control", "no-cache");// HTTP1.1?Cache-Control ???,no-cache?????
    response.setHeader("Cache-Control", "no-store");//HTTP1.1?Cache-Control ???no-store????
    response.setDateHeader("Expires", 0);//Expires?GMT????????
    response.setContentType("image/jpeg");

    ServletOutputStream servletOutputStream = null;
    try {
        servletOutputStream = response.getOutputStream();
        BufferedImage bufferedImage = captchaService.buildImage(captchaId);
        ImageIO.write(bufferedImage, "jpg", servletOutputStream);
        servletOutputStream.flush();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(servletOutputStream);
    }
}

From source file:com.webpagebytes.cms.utility.HttpServletToolbox.java

public void writeBodyResponseAsJson(HttpServletResponse response, org.json.JSONObject data,
        Map<String, String> errors) {

    try {/*w w w . ja  v a 2s. c om*/
        org.json.JSONObject jsonResponse = new org.json.JSONObject();
        org.json.JSONObject jsonErrors = new org.json.JSONObject();
        if (errors == null || errors.keySet().size() == 0) {
            jsonResponse.put("status", "OK");
        } else {
            jsonResponse.put("status", "FAIL");
            for (String key : errors.keySet()) {
                jsonErrors.put(key, errors.get(key));
            }
        }
        jsonResponse.put("errors", jsonErrors);
        jsonResponse.put("payload", data);
        String jsonString = jsonResponse.toString();
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        ServletOutputStream writer = response.getOutputStream();
        byte[] utf8bytes = jsonString.getBytes("UTF-8");
        writer.write(utf8bytes);
        response.setContentLength(utf8bytes.length);
        writer.flush();

    } catch (Exception e) {
        try {
            String errorResponse = "{\"status\":\"FAIL\",\"payload\":\"{}\",\"errors\":{\"reason\":\"WB_UNKNOWN_ERROR\"}}";
            ServletOutputStream writer = response.getOutputStream();
            response.setContentType("application/json");
            byte[] utf8bytes = errorResponse.getBytes("UTF-8");
            response.setContentLength(utf8bytes.length);
            writer.write(utf8bytes);
            writer.flush();
        } catch (IOException ioe) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

}

From source file:net.sourceforge.fenixedu.presentationTier.Action.externalServices.SetEmailDA.java

public ActionForward setEmail(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    final String host = HostAccessControl.getRemoteAddress(request);
    final String ip = request.getRemoteAddr();
    final String password = request.getParameter("password");
    final String userUId = request.getParameter("userUId");
    final String email = URLDecoder.decode(request.getParameter("email"), "UTF-8");

    String message = "ko";

    try {//from www .ja  va  2 s .  co  m

        SetEmail.run(host, ip, password, userUId, email);
        final User user = User.findByUsername(userUId);
        if (user.getPerson() != null && user.getPerson().getStudent() != null) {
            final Student student = user.getPerson().getStudent();
            for (final Registration registration : student.getRegistrationsSet()) {
                final StudentCandidacy candidacy = registration.getStudentCandidacy();
                if (candidacy != null
                        && (candidacy instanceof DegreeCandidacy || candidacy instanceof IMDCandidacy)
                        && candidacy.getExecutionYear().isCurrent()
                        && !candidacy.getCandidacySituationsSet().isEmpty()) {
                    new PDFGeneratorThread(candidacy.getExternalId(), request.getServerName(),
                            request.getServerPort(), request.getContextPath(), request.getServletPath())
                                    .start();
                }
            }
        }
        message = "ok";
    } catch (NotAuthorizedException ex) {
        message = "Not authorized";
    } catch (UserAlreadyHasEmailException ex) {
        message = "User already has email.";
    } catch (UserDoesNotExistException ex) {
        message = "User does not exist.";
    } catch (Throwable ex) {
        message = ex.getMessage();
        logger.error(ex.getMessage(), ex);
    } finally {
        final ServletOutputStream servletOutputStream = response.getOutputStream();
        response.setContentType("text/html");
        servletOutputStream.print(message);
        servletOutputStream.flush();
        response.flushBuffer();
    }

    return null;
}

From source file:org.apache.myfaces.custom.skin.webapp.CachingStyleSheetLoader.java

/**
 * Sends the file into the OutputStream of the response. 
 * @param file The stylesheet file.//from  w w w. j a  v a  2 s  . co  m
 * @param response
 * @throws IOException
 */
private void writeFile(File file, HttpServletResponse response) throws IOException {
    response.setContentType(STYLE_TYPE_TEXT_CSS);

    InputStream in = new FileInputStream(file);
    ServletOutputStream out = response.getOutputStream();

    byte[] buffer = new byte[1024];
    for (int size = in.read(buffer); size != -1; size = in.read(buffer)) {
        out.write(buffer, 0, size);
    }
    out.flush();
    in.close();
}

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

public ModelAndView checkValidity(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Long connId = Long.parseLong(request.getParameter("connId"));
    ConnectionsEntity connectionEntity = connectionsDao.find(connId);

    keptXSD = getFileContent(connId, connectionEntity);
    Validate result = new Validate();
    if (keptXSD == null || keptXSD.trim().length() == 0) {
        result.setSuccess(false);// w  w  w.  java2 s  . c o m
    } else {
        result.setSuccess(true);
    }
    ServletOutputStream out = null;
    response.setContentType("application/json");
    out = response.getOutputStream();
    out.write(new ObjectMapper().writeValueAsBytes(result));
    out.flush();
    out.close();

    return null;
}