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:gov.utah.dts.det.ccl.actions.facility.information.license.LicensesPrintAction.java

@Action(value = "print-license-letter")
public void doPrintLetter() {
    loadLicense();//w w w .jav  a2 s  .co m

    try {
        ByteArrayOutputStream ba = LicenseLetter.generate(license, request);
        if (ba != null && ba.size() > 0) {
            // This is where the response is set
            String filename = "license_letter.pdf";
            response.setContentLength(ba.size());
            response.setContentType("application/pdf");
            response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
            response.setHeader("Pragma", "no-cache");
            response.setDateHeader("Expires", 0);
            response.setHeader("Content-disposition", "attachment; filename=\"" + filename + "\"");

            ServletOutputStream out = response.getOutputStream();
            ba.writeTo(out);
            out.flush();
        }
    } catch (Exception ex) {
        // Generate an error pdf
        ByteArrayOutputStream ba = null;
        try {
            ba = new ByteArrayOutputStream();
            Document document = new Document(PageSize.A4, 50, 50, 100, 100);
            @SuppressWarnings("unused")
            PdfWriter writer = PdfWriter.getInstance(document, ba);
            document.open();
            document.add(new Paragraph("An error occurred while generating the letter document.",
                    FontFactory.getFont("Times-Roman", 12, Font.NORMAL)));
            document.close();
            if (ba != null && ba.size() > 0) {
                // This is where the response is set
                // String filename = getTrackingRecordScreening().getPerson().getFirstAndLastName() + " - " +
                // screeningLetter.getLetterType() + ".pdf";
                response.setContentLength(ba.size());
                response.setContentType("application/pdf");
                response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
                response.setHeader("Pragma", "no-cache");
                response.setDateHeader("Expires", 0);
                // response.setHeader("Content-disposition", "attachment; filename=\"" + filename + "\"");
                response.setHeader("Content-disposition", "attachment");

                ServletOutputStream out = response.getOutputStream();
                ba.writeTo(out);
                out.flush();
            }

        } catch (Exception e) {
            log.error("AN ERROR OCCURRED GENERATING ERROR PDF DOCUMENT: " + e);
        }
    }
}

From source file:com.hp.security.jauth.admin.controller.BaseController.java

@RequestMapping("index")
public void index(HttpServletRequest request, HttpServletResponse response)
        throws IOException, TemplateException {
    Map<String, Object> root = new HashMap<String, Object>();
    String view = freemarkerUtil.buildView(root, "main");
    response.setContentType("text/html");
    ServletOutputStream out = response.getOutputStream();
    out.write(view.getBytes());// w w w. j  av  a  2s.  c o  m
    out.flush();
    out.close();
}

From source file:org.obm.push.impl.ResponderImpl.java

private void writeData(byte[] data, String type) throws IOException {
    resp.setContentType(type);//from   w  w  w.  jav a2s .  c  o  m
    resp.setContentLength(data.length);
    ServletOutputStream out = resp.getOutputStream();
    out.write(data);
    out.flush();
    out.close();
}

From source file:org.exoplatform.frameworks.jcr.command.web.DisplayResourceCommand.java

public boolean execute(Context context) throws Exception {
    GenericWebAppContext webCtx = (GenericWebAppContext) context;
    HttpServletResponse response = webCtx.getResponse();
    HttpServletRequest request = webCtx.getRequest();

    // standalone request?
    String servletPath = request.getPathInfo();
    boolean doClose = true;
    // or included?
    if (servletPath == null) {
        servletPath = (String) request.getAttribute("javax.servlet.include.path_info");
        if (servletPath != null)
            doClose = false;//from w  w  w  . ja v  a  2  s .  c o  m
    }

    Node file = (Node) webCtx.getSession().getItem((String) context.get(pathKey));
    file.refresh(false);

    Node content = null;

    try {
        content = JCRCommandHelper.getNtResourceRecursively(file);
    } catch (ItemNotFoundException e) {
        // Patch for ver 1.0 back compatibility
        // as exo:image was not primary item
        if (file.isNodeType("exo:article")) {
            try {
                content = file.getNode("exo:image");
            } catch (PathNotFoundException e1) {
                throw e; // new ItemNotFoundException("No nt:resource node found at
                // "+file.getPath()+" nor primary items of nt:resource type
                // ");
            }
        } else {
            throw e; // new ItemNotFoundException("No nt:resource node found at
            // "+file.getPath()+" nor primary items of nt:resource type
            // ");
        }

    }

    // if(file.isNodeType("nt:file")) {
    // content = file.getNode("jcr:content");
    // } else if(file.isNodeType("exo:article")) {
    // content = file.getNode("exo:image");
    // } else
    // throw new Exception("Invalid node type, expected nt:file or exo:article,
    // have "+file.getPrimaryNodeType().getName()+" at "+file.getPath());

    Property data;
    try {
        data = content.getProperty("jcr:data");
    } catch (PathNotFoundException e) {
        throw new PathNotFoundException("No jcr:data node found at " + content.getPath());
    }

    String mime = content.getProperty("jcr:mimeType").getString();
    String encoding = content.hasProperty("jcr:encoding") ? content.getProperty("jcr:encoding").getString()
            : DEFAULT_ENCODING;

    MimeTypeResolver resolver = new MimeTypeResolver();
    String fileName = file.getName();
    String fileExt = "";
    if (fileName.lastIndexOf(".") > -1) {
        fileExt = fileName.substring(fileName.lastIndexOf(".") + 1);
        fileName = fileName.substring(0, fileName.lastIndexOf("."));
    }
    String mimeExt = resolver.getExtension(mime);
    if (fileExt == null || fileExt.length() == 0) {
        fileExt = mimeExt;
    }
    response.setContentType(mime + "; charset=" + encoding);
    String parameter = (String) context.get("cache-control-max-age");
    String cacheControl = parameter == null ? "" : "public, max-age=" + parameter;
    response.setHeader("Cache-Control: ", cacheControl);
    response.setHeader("Pragma: ", ""); // leave blank to avoid IE errors
    response.setHeader("Content-disposition", "attachment; filename=\"" + fileName + "." + fileExt + "\"");

    if (mime.startsWith("text")) {
        PrintWriter out = response.getWriter();
        out.write(data.getString());
        out.flush();
        if (doClose)
            out.close();
    } else {
        InputStream is = data.getStream();
        byte[] buf = new byte[is.available()];
        is.read(buf);
        ServletOutputStream os = response.getOutputStream();
        os.write(buf);
        os.flush();
        if (doClose)
            os.close();
    }

    return true;
}

From source file:com.hp.security.jauth.admin.controller.BaseController.java

@RequestMapping("login")
public void login(HttpServletRequest request, HttpServletResponse response)
        throws IOException, TemplateException {
    String error = null;/*w ww.  j a  v a2s .co  m*/
    if (null != request.getAttribute("error")) {
        error = request.getAttribute("error").toString();
    }
    Map<String, Object> root = new HashMap<String, Object>();
    root.put("error", error);
    String view = freemarkerUtil.buildView(root, "login");
    response.setContentType("text/html");
    ServletOutputStream out = response.getOutputStream();
    out.write(view.getBytes());
    out.flush();
    out.close();
}

From source file:com.hp.security.jauth.admin.controller.BaseController.java

@RequestMapping("exception")
public void exception(HttpServletRequest request, HttpServletResponse response)
        throws IOException, TemplateException {
    Map<String, Object> root = new HashMap<String, Object>();
    String code = "";
    Exception ex = (Exception) request.getAttribute("ex");
    if (null != ex && ex instanceof AuthException) {
        AuthException aex = (AuthException) ex;
        code = aex.getCode();// w  w w.  j a v a 2 s .c o  m
    }
    root.put("code", code);
    root.put("ex", ex);
    String view = freemarkerUtil.buildView(root, "exception");
    response.setContentType("text/html");
    ServletOutputStream out = response.getOutputStream();
    out.write(view.getBytes());
    out.flush();
    out.close();
}

From source file:it.jugpadova.controllers.ServiceController.java

@RequestMapping
public ModelAndView kml(HttpServletRequest req, HttpServletResponse res) throws Exception {
    logger.info("Requested kml from " + req.getRemoteAddr());
    Document doc = jugBo.buildKml();
    res.setHeader("Cache-Control", "no-store");
    res.setHeader("Pragma", "no-cache");
    res.setDateHeader("Expires", 0);
    res.setContentType("text/xml");
    ServletOutputStream resOutputStream = res.getOutputStream();
    Serializer serializer = new Serializer(resOutputStream);
    serializer.setIndent(4);//from w ww  .  java2  s .  co m
    serializer.setMaxLength(64);
    serializer.setLineSeparator("\n");
    serializer.write(doc);
    resOutputStream.flush();
    resOutputStream.close();
    return null;
}

From source file:com.hzc.framework.ssh.controller.WebUtil.java

/**
 * ?response?/* w  ww .  j av a 2s .  c o  m*/
 *
 * @param attachFile
 * @throws IOException
 */
public static void write(byte[] attachFile) throws RuntimeException {
    try {
        HttpServletResponse resp = ActionContext.getResp();
        ServletOutputStream outputStream = resp.getOutputStream();
        outputStream.write(attachFile);
        outputStream.flush();
        //            outputStream.close();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:edu.umd.cs.submitServer.servlets.DownloadBestSubmissions.java

/**
 * The doGet method of the servlet. <br>
 *
 * This method is called when a form has its tag value method equals to get.
 *
 * @param request/*  w  ww.j  av  a 2s . co  m*/
 *            the request send by the client to the server
 * @param response
 *            the response send by the server to the client
 * @throws ServletException
 *             if an error occurred
 * @throws IOException
 *             if an error occurred
 */
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Connection conn = null;
    File tempfile = null;
    FileOutputStream fileOutputStream = null;
    FileInputStream fis = null;
    try {
        conn = getConnection();

        // get the project and all the student registrations
        Map<Integer, Submission> bestSubmissionMap = (Map<Integer, Submission>) request
                .getAttribute("bestSubmissionMap");

        Project project = (Project) request.getAttribute("project");
        Set<StudentRegistration> registrationSet = (Set<StudentRegistration>) request
                .getAttribute("studentRegistrationSet");

        // write everything to a tempfile, then send the tempfile
        tempfile = File.createTempFile("temp", "zipfile");
        fileOutputStream = new FileOutputStream(tempfile);

        // zip aggregator
        ZipFileAggregator zipAggregator = new ZipFileAggregator(fileOutputStream);

        for (StudentRegistration registration : registrationSet) {

            Submission submission = bestSubmissionMap.get(registration.getStudentRegistrationPK());
            if (submission != null) {
                try {
                    byte[] bytes = submission.downloadArchive(conn);
                    zipAggregator.addFileFromBytes(
                            registration.getClassAccount() + "-" + submission.getStatus() + "__"
                                    + submission.getSubmissionNumber(),
                            submission.getSubmissionTimestamp().getTime(), bytes);
                } catch (ZipFileAggregator.BadInputZipFileException ignore) {
                    // ignore, since students could submit things that
                    // aren't zipfiles
                    getSubmitServerServletLog().warn(ignore.getMessage(), ignore);
                }
            }
        }

        zipAggregator.close();

        // write the zipfile to the client
        response.setContentType("application/zip");
        response.setContentLength((int) tempfile.length());

        // take into account the inability of certain browsers to download
        // zipfiles
        String filename = "p" + project.getProjectNumber() + ".zip";
        Util.setAttachmentHeaders(response, filename);

        ServletOutputStream out = response.getOutputStream();
        fis = new FileInputStream(tempfile);

        IO.copyStream(fis, out);

        out.flush();
        out.close();
    } catch (SQLException e) {
        handleSQLException(e);
        throw new ServletException(e);
    } finally {
        releaseConnection(conn);
        if (tempfile != null && !tempfile.delete())
            getSubmitServerServletLog().warn("Unable to delete temporary file " + tempfile.getAbsolutePath());
        IOUtils.closeQuietly(fileOutputStream);
        IOUtils.closeQuietly(fis);
    }
}

From source file:org.obm.push.impl.ResponderImpl.java

@Override
public void sendResponseFile(String contentType, InputStream file) {
    Preconditions.checkNotNull(contentType);
    Preconditions.checkNotNull(file);//from w ww . j av a  2s  . c  o m

    logger.debug("response: send file");
    try {
        byte[] b = FileUtils.streamBytes(file, false);
        resp.setContentType(contentType);
        resp.setContentLength(b.length);
        ServletOutputStream out = resp.getOutputStream();
        out.write(b);
        out.flush();
        out.close();
        resp.setStatus(HttpServletResponse.SC_OK);
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    }
}