Example usage for javax.servlet ServletOutputStream close

List of usage examples for javax.servlet ServletOutputStream close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes this output stream and releases any system resources associated with this stream.

Usage

From source file:gov.nih.nci.calims2.ui.report.filledreport.FilledReportController.java

/**
 * //from  ww w.  j a  v a 2s . co  m
 * @param response The servlet response.
 * @param id The id of the filledreport to view.
 * @param formatName The format of the pdf file.
 */
@RequestMapping("/exportReport.do")
public void exportReport(HttpServletResponse response, @RequestParam("id") Long id,
        @RequestParam("format") String formatName) {

    FilledReport filledReport = getMainService().findById(FilledReport.class, id);
    Report report = filledReport.getReport();
    FilledReportFormat format = FilledReportFormat.valueOf(formatName);
    try {
        ServletOutputStream servletOutputStream = response.getOutputStream();
        File exportedFile = ((FilledReportService) getMainService()).exportJasperReport(id, tempfiledir,
                format);
        response.setContentType(format.getContentType());
        DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyyMMdd-HHmmss");
        String filename = report.getName() + fmt.print(filledReport.getExecutionTime()) + format.getExtention();
        response.setHeader("Content-Disposition", "attachment;filename=" + filename);
        FileInputStream fileInputStream = new FileInputStream(exportedFile);
        IOUtils.copyLarge(fileInputStream, servletOutputStream);
        IOUtils.closeQuietly(fileInputStream);
        servletOutputStream.flush();
        servletOutputStream.close();
        exportedFile.delete();
    } catch (IOException e1) {
        throw new RuntimeException("IOException in exportReport", e1);
    } catch (ReportingException e) {
        throw new RuntimeException("ReportingException in exportReport", e);
    }
}

From source file:SendMp3.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String fileName = (String) request.getParameter("file");
    if (fileName == null || fileName.equals(""))
        throw new ServletException("Invalid or non-existent file parameter in SendMp3 servlet.");

    if (fileName.indexOf(".mp3") == -1)
        fileName = fileName + ".mp3";

    String mp3Dir = getServletContext().getInitParameter("mp3-dir");
    if (mp3Dir == null || mp3Dir.equals(""))
        throw new ServletException("Invalid or non-existent mp3Dir context-param.");

    ServletOutputStream stream = null;
    BufferedInputStream buf = null;
    try {// ww w . ja v a  2 s .c  o  m

        stream = response.getOutputStream();
        File mp3 = new File(mp3Dir + "/" + fileName);

        //set response headers
        response.setContentType("audio/mpeg");

        response.addHeader("Content-Disposition", "attachment; filename=" + fileName);

        response.setContentLength((int) mp3.length());

        FileInputStream input = new FileInputStream(mp3);
        buf = new BufferedInputStream(input);
        int readBytes = 0;
        //read from the file; write to the ServletOutputStream
        while ((readBytes = buf.read()) != -1)
            stream.write(readBytes);
    } catch (IOException ioe) {
        throw new ServletException(ioe.getMessage());
    } finally {
        if (stream != null)
            stream.close();
        if (buf != null)
            buf.close();
    }
}

From source file:com.viewer.controller.ViewerController.java

@RequestMapping(value = "/GetFile")
@ResponseBody//from  w  w w . j  av a 2 s. c  o  m
private void GetFile(@RequestParam String path, Boolean getPdf, Boolean useHtmlBasedEngine,
        Boolean supportPageRotation, HttpServletResponse response) throws Exception {

    File file = new File(path);

    String displayName = path;
    String nameWithoutExtension = removeExtention(path);
    Stream fileStream;
    File newFile = new File(nameWithoutExtension + ".pdf");

    displayName = newFile.getPath();

    PdfFileOptions options = new PdfFileOptions();
    options.setGuid(path);

    FileContainer pdfFileResponse = _htmlHandler.getPdfFile(options);

    response.setContentType("application/octet-stream");
    response.setHeader("Content-Disposition", "attachment; filename=\"" + displayName + "\"");
    InputStream fileIn = pdfFileResponse.getStream();
    ServletOutputStream out = response.getOutputStream();

    byte[] outputByte = new byte[4096];
    while (fileIn.read(outputByte, 0, 4096) != -1) {
        out.write(outputByte, 0, 4096);
    }
    fileIn.close();
    out.flush();
    out.close();

}

From source file:com.spring.tutorial.controllers.DefaultController.java

@RequestMapping(value = "/my-drive/dropbox/downloads/**", method = RequestMethod.GET)
public String getDropboxFile(HttpServletRequest request, HttpServletResponse response)
        throws IOException, DbxException {

    config = new DbxRequestConfig("JavaTutorial/1.0", Locale.getDefault().toString());
    DbxClient client = new DbxClient(config, (String) request.getSession().getAttribute("dropbox_token"));

    String path = request.getServletPath()
            .substring(request.getServletPath().indexOf("/my-drive/dropbox/downloads/") + 27);
    ServletOutputStream outputStream = response.getOutputStream();
    try {/*from   w w w . j  av  a 2s .c o m*/

        DbxEntry.File downloadedFile = client.getFile(path, null, outputStream);
        String mimeType = "application/octet-stream";
        response.setContentType(mimeType);
        response.setContentLength((int) downloadedFile.numBytes);
        String headerKey = "Content-Disposition";
        String headerValue = String.format("attachment; filename=\"%s\"", downloadedFile.name);
    } finally {
        outputStream.close();
    }
    return "";
}

From source file:org.efs.openreports.services.servlet.ReportServiceServlet.java

protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {/*from w  ww.  j av  a2s .c  o  m*/
        ServletReportServiceInput reportInput = buildReportServiceInput(request);
        reportInput.setParameterMap(request.getParameterMap());

        ReportEngineOutput reportOutput = reportService.generateReport(reportInput);

        if (reportOutput instanceof QueryEngineOutput) {
            QueryEngineOutput queryReport = (QueryEngineOutput) reportOutput;

            request.getSession().setAttribute("properties", queryReport.getProperties());
            request.getSession().setAttribute("results", queryReport.getResults());
            request.getSession().setAttribute("reportName",
                    StringUtils.deleteWhitespace(reportInput.getReportName()));

            response.sendRedirect("report-viewer/query-report.jsp");

            //getServletContext().getRequestDispatcher("/report-viewer/query-report.jsp").forward(request, response);

            return;
        }

        ServletOutputStream out = response.getOutputStream();

        if (reportOutput.getContent() != null) {
            if (reportInput.getExportType() != ReportEngine.EXPORT_HTML) {
                response.setContentType(reportOutput.getContentType());
                response.setContentLength(reportOutput.getContent().length);
                response.setHeader("Content-disposition",
                        "inline; filename=" + StringUtils.deleteWhitespace(reportInput.getReportName())
                                + reportOutput.getContentExtension());
            }

            out.write(reportOutput.getContent(), 0, reportOutput.getContent().length);
        } else {
            out.write(reportOutput.getContentMessage().getBytes());
        }

        out.flush();
        out.close();
    } catch (Exception e) {
        response.getOutputStream().write(e.toString().getBytes());
    }
}

From source file:com.ephesoft.gxt.batchinstance.server.BatchInfoDownloadServlet.java

/**
 * Closes the open resources.//from  w  ww  .j ava 2 s.c  om
 * 
 * @param out {@link ServletOutputStream} the servlet output stream
 * @param zout {@link ZipOutputStream} the output stream for zip file
 * @param fout {@link FileOutputStream} the file output stream of zip file
 * @throws IOException if an exception occurs while closing the resources
 */
private void closeResources(final ServletOutputStream out, final ZipOutputStream zout,
        final FileOutputStream fout, final PrintWriter writer) throws IOException {
    if (writer != null) {
        writer.close();
    }
    if (zout != null) {
        zout.close();
    }
    if (out != null) {
        out.close();
    }
    if (fout != null) {
        fout.close();
    }
}

From source file:com.all.tracker.controllers.VersionController.java

private void sendFile(File updateFile, ServletOutputStream outputStream) throws Exception {
    FileInputStream fis = null;/*  www .  ja  v  a 2 s .  co m*/
    try {

        byte[] readBytes = new byte[1024 * 4];
        int amountBytesRead;
        fis = fileInputStreamFactory.create(updateFile);

        while ((amountBytesRead = fis.read(readBytes)) != -1) {
            outputStream.write(readBytes, 0, amountBytesRead);
        }

    } catch (Exception e) {
        throw e;
    } finally {
        if (fis != null) {
            try {
                fis.close();
            } catch (IOException e) {
                // ignore
            }
        }
        try {
            outputStream.close();
        } catch (IOException e) {
            // ignore
        }
        fis = null;
        outputStream = null;
    }
}

From source file:org.vasanti.controller.DropZoneFileUpload.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    if (request.getParameter("getfile") != null && !request.getParameter("getfile").isEmpty()) {
        File file = new File(ImagefileUploadPath, request.getParameter("getfile"));
        if (file.exists()) {
            int bytes = 0;
            ServletOutputStream op = response.getOutputStream();
            response.setContentType(getMimeType(file));
            response.setContentLength((int) file.length());
            response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\"");

            byte[] bbuf = new byte[1024];
            DataInputStream in = new DataInputStream(new FileInputStream(file));

            while ((in != null) && ((bytes = in.read(bbuf)) != -1)) {
                op.write(bbuf, 0, bytes);
            }//  w  w w  .  j  ava  2 s  . c  o  m

            in.close();
            op.flush();
            op.close();
        }
    } //        else if (request.getParameter("delfile") != null && !request.getParameter("delfile").isEmpty()) {
      //            File file = new File(request.getServletContext().getRealPath("/") + "imgs/" + request.getParameter("delfile"));
      //            if (file.exists()) {
      //                file.delete(); // TODO:check and report success
      //            }
      //       } 
    else if (request.getParameter("getthumb") != null && !request.getParameter("getthumb").isEmpty()) {
        File file = new File(ImagefileUploadPath, request.getParameter("getthumb"));
        if (file.exists()) {
            String mimetype = getMimeType(file);
            if (mimetype.endsWith("png") || mimetype.endsWith("jpeg") || mimetype.endsWith("jpg")
                    || mimetype.endsWith("gif")) {
                BufferedImage im = ImageIO.read(file);
                if (im != null) {
                    BufferedImage thumb = Scalr.resize(im, 75);
                    ByteArrayOutputStream os = new ByteArrayOutputStream();
                    if (mimetype.endsWith("png")) {
                        ImageIO.write(thumb, "PNG", os);
                        response.setContentType("image/png");
                    } else if (mimetype.endsWith("jpeg")) {
                        ImageIO.write(thumb, "jpg", os);
                        response.setContentType("image/jpeg");
                    } else if (mimetype.endsWith("jpg")) {
                        ImageIO.write(thumb, "jpg", os);
                        response.setContentType("image/jpeg");
                    } else {
                        ImageIO.write(thumb, "GIF", os);
                        response.setContentType("image/gif");
                    }
                    ServletOutputStream srvos = response.getOutputStream();
                    response.setContentLength(os.size());
                    response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\"");
                    os.writeTo(srvos);
                    srvos.flush();
                    srvos.close();
                }
            }
        } // TODO: check and report success
    } else {
        PrintWriter writer = response.getWriter();
        writer.write("call POST with multipart form data");
    }
}

From source file:fr.insalyon.creatis.vip.datamanager.server.rpc.FileDownloadServiceImpl.java

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

    User user = (User) req.getSession().getAttribute(CoreConstants.SESSION_USER);
    String operationId = req.getParameter("operationid");

    if (user != null && operationId != null && !operationId.isEmpty()) {

        try {// ww w.  jav  a  2 s . c  om
            GRIDAPoolClient client = CoreUtil.getGRIDAPoolClient();
            Operation operation = client.getOperationById(operationId);

            File file = new File(operation.getDest());
            if (file.isDirectory()) {
                file = new File(operation.getDest() + "/" + FilenameUtils.getName(operation.getSource()));
            }
            int length = 0;
            ServletOutputStream op = resp.getOutputStream();
            ServletContext context = getServletConfig().getServletContext();
            String mimetype = context.getMimeType(file.getName());

            logger.info("(" + user.getEmail() + ") Downloading '" + file.getAbsolutePath() + "'.");

            resp.setContentType((mimetype != null) ? mimetype : "application/octet-stream");
            resp.setContentLength((int) file.length());
            resp.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");

            byte[] bbuf = new byte[4096];
            DataInputStream in = new DataInputStream(new FileInputStream(file));

            while ((in != null) && ((length = in.read(bbuf)) != -1)) {
                op.write(bbuf, 0, length);
            }

            in.close();
            op.flush();
            op.close();
        } catch (GRIDAClientException ex) {
            logger.error(ex);
        }
    }
}

From source file:org.ff4j.web.AdministrationConsoleServlet.java

/**
 * Build Http response when invoking export features.
 * /*  w  ww . j a va 2 s .  c  o  m*/
 * @param res
 *            http response
 * @throws IOException
 *             error when building response
 */
private void buildResponseForExportFeature(HttpServletResponse res) throws IOException {
    InputStream in = new FeatureXmlParser().exportFeatures(getFf4j().getStore().readAll());
    ServletOutputStream sos = null;
    try {
        sos = res.getOutputStream();
        res.setContentType("text/xml");
        res.setHeader("Content-Disposition", "attachment; filename=\"ff4j.xml\"");
        // res.setContentLength()
        byte[] bbuf = new byte[BUFFER_SIZE];
        int length = 0;
        while ((in != null) && (length != -1)) {
            length = in.read(bbuf);
            sos.write(bbuf, 0, length);
        }
    } finally {
        if (in != null) {
            in.close();
        }
        if (sos != null) {
            sos.flush();
            sos.close();
        }
    }
}