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:org.codelabor.system.file.web.controller.xplatform.FileController.java

@RequestMapping("/view")
public String view(Model model, @RequestParam("fileId") String fileId, HttpServletResponse response)
        throws Exception {
    StringBuilder stringBuilder = null;

    FileDTO fileDTO;/*from   ww  w.  ja v a  2s .  c om*/
    fileDTO = fileManager.selectFileByFileId(fileId);
    logger.debug("fileDTO: {}", fileDTO);

    String repositoryPath = fileDTO.getRepositoryPath();
    String uniqueFilename = fileDTO.getUniqueFilename();
    String realFilename = fileDTO.getRealFilename();
    InputStream inputStream = null;

    BufferedInputStream bufferdInputStream = null;
    ServletOutputStream servletOutputStream = null;
    BufferedOutputStream bufferedOutputStream = null;

    DataSetList outputDataSetList = new DataSetList();
    VariableList outputVariableList = new VariableList();
    try {
        if (StringUtils.isNotEmpty(repositoryPath)) {
            // FILE_SYSTEM
            stringBuilder = new StringBuilder();
            stringBuilder.append(repositoryPath);
            if (!repositoryPath.endsWith(File.separator)) {
                stringBuilder.append(File.separator);
            }
            stringBuilder.append(uniqueFilename);
            File file = new File(stringBuilder.toString());
            inputStream = new FileInputStream(file);
        } else {
            // DATABASE
            byte[] bytes = new byte[] {};
            if (fileDTO.getFileSize() > 0) {
                bytes = fileDTO.getBytes();
            }
            inputStream = new ByteArrayInputStream(bytes);

        }
        response.setContentType(fileDTO.getContentType());

        // set response contenttype, header
        String encodedRealFilename = URLEncoder.encode(realFilename, "UTF-8");
        logger.debug("realFilename: {}", realFilename);
        logger.debug("encodedRealFilename: {}", encodedRealFilename);
        logger.debug("character encoding: {}", response.getCharacterEncoding());
        logger.debug("content type: {}", response.getContentType());
        logger.debug("bufferSize: {}", response.getBufferSize());
        logger.debug("locale: {}", response.getLocale());

        bufferdInputStream = new BufferedInputStream(inputStream);
        servletOutputStream = response.getOutputStream();
        bufferedOutputStream = new BufferedOutputStream(servletOutputStream);
        int bytesRead;
        byte buffer[] = new byte[2048];
        while ((bytesRead = bufferdInputStream.read(buffer)) != -1) {
            bufferedOutputStream.write(buffer, 0, bytesRead);
        }
        // flush stream
        bufferedOutputStream.flush();

        XplatformUtils.setSuccessMessage(
                messageSource.getMessage("info.success", new Object[] {}, forcedLocale), outputVariableList);
    } catch (Exception e) {
        e.printStackTrace();
        logger.error(e.getMessage());
        throw new XplatformException(messageSource.getMessage("error.failure", new Object[] {}, forcedLocale),
                e);
    } finally {
        // close stream
        inputStream.close();
        bufferdInputStream.close();
        servletOutputStream.close();
        bufferedOutputStream.close();
    }
    model.addAttribute(OUTPUT_DATA_SET_LIST, outputDataSetList);
    model.addAttribute(OUTPUT_VARIABLE_LIST, outputVariableList);
    return VIEW_NAME;

}

From source file:net.sf.ginp.GinpPictureServlet.java

/**
 *  Central Processor of HTTP GET and POST Methods. This method gets the
 *  model for the users session, and returns the correctly sized picture
 *  based on the command parameters in the request and the model state.
 *
 *@param  req                   HTTP Request
 *@param  res                   HTTP Response
 *@exception  IOException       Description of the Exception
 *///  w  w w . ja  v a 2 s  .  c  om
final void doHttpMethod(final HttpServletRequest req, final HttpServletResponse res) throws IOException {
    ServletOutputStream sos = res.getOutputStream();
    GinpModel model = null;

    //Retrieve the model for this web app
    try {
        model = ModelUtil.getModel(req);
    } catch (Exception ex) {
        log.error("Problem getting model", ex);

        return;
    }

    String filename = req.getParameter("name");
    String path = req.getParameter("path");

    res.setContentType("image/jpeg");

    //Only allow files below the given directory
    if (filename != null) {
        filename = filename.replaceAll("\\.\\./", "");
        filename = filename.replaceAll("\\.\\.\\\\", "");

        // Only deliver JPEGs
        if (!((filename.toLowerCase()).endsWith(".jpg") || (filename.toLowerCase()).endsWith(".jpeg"))) {
            filename = null;
        }
    }

    if (path != null) {
        path = path.replaceAll("\\.\\./", "");
        path = path.replaceAll("\\.\\.\\\\", "");
    }

    if (filename != null) {
        String absPath = getImagePath(model, path);

        int maxSize = 0;
        File fl;

        if (req.getParameter("maxsize") != null) {
            maxSize = GinpUtil.parseInteger(req, "maxsize", 0);
            fl = getThumbnailPath(filename, absPath, maxSize);
        } else {
            fl = new File(absPath + filename);
        }

        fl = handleMissingPicture(req, res, fl);

        FileInputStream is = new FileInputStream(fl);

        String heightParm = req.getParameter("height");
        String widthParm = req.getParameter("width");

        // debug output
        //if (log.isDebugEnabled()) {
        log.info("doHttpMethod filename=" + filename + " absPath=" + absPath + " path=" + path + " heightParm="
                + heightParm + " widthParm=" + widthParm + " maxSize=" + maxSize + " ImageFile="
                + fl.getPath());

        //}
        if ((heightParm != null) || (widthParm != null)) {
            int width = GinpUtil.parseInteger(req, "width", 0);
            int height = GinpUtil.parseInteger(req, "height", 0);
            GinpUtil.writeScaledImageToStream(sos, is, width, height);
        } else {
            // deliver raw image
            GinpUtil.writeInputStreamToOutputStream(sos, is);
        }
    } else {
        // is this a request to set client info
        if ((req.getParameter("cmd") != null) && req.getParameter("cmd").equals("setprops")) {
            if (req.getParameter("pagewidth") != null) {
                int i = GinpUtil.parseInteger(req, "pagewidth", 0);

                if (i > 0) {
                    model.setPageWidth(i);
                }
            }

            if (req.getParameter("pageheight") != null) {
                int i = GinpUtil.parseInteger(req, "pageheight", 0);

                if (i > 0) {
                    model.setPageHeight(i);
                }
            }
        }

        deliverSpacer(req, sos);
    }

    sos.flush();
    sos.close();
}

From source file:ispyb.client.mx.results.ViewResultsAction.java

public ActionForward displayCorrectionFile(ActionMapping mapping, ActionForm actForm,
        HttpServletRequest request, HttpServletResponse response) {
    ActionMessages errors = new ActionMessages();

    String filename = "";
    String fullFilePath = "";

    try {// w  w  w . j a v  a 2 s  . co  m
        if (request.getParameter("fileName") != null)
            filename = new String(request.getParameter("fileName"));
        Integer dataCollectionId = null;
        if (BreadCrumbsForm.getIt(request).getSelectedDataCollection() != null)
            dataCollectionId = BreadCrumbsForm.getIt(request).getSelectedDataCollection().getDataCollectionId();
        else {
            dataCollectionId = new Integer(request.getParameter(Constants.SESSION_ID));
        }
        if (dataCollectionId != null) {
            DataCollection3VO dataCollection = dataCollectionService.findByPk(dataCollectionId, false, false);
            String beamLineName = dataCollection.getDataCollectionGroupVO().getSessionVO().getBeamlineName();
            String[] correctionFiles = ESRFBeamlineEnum.retrieveCorrectionFilesNameWithName(beamLineName);
            if (correctionFiles != null) {
                for (int k = 0; k < correctionFiles.length; k++) {
                    String correctionFileName = correctionFiles[k];
                    if (correctionFileName != null && correctionFileName.equals(filename)) {
                        String dir = ESRFBeamlineEnum.retrieveDirectoryNameWithName(beamLineName);
                        if (dir != null) {
                            String correctionFilePath = "/data/pyarch/" + dir + "/" + correctionFileName;
                            fullFilePath = PathUtils.FitPathToOS(correctionFilePath);
                            java.io.FileInputStream in;
                            in = new java.io.FileInputStream(new File(fullFilePath));
                            response.setContentType("application/octet-stream");
                            response.setHeader("Content-Disposition", "attachment;filename=" + filename);

                            ServletOutputStream out = response.getOutputStream();

                            byte[] buf = new byte[4096];
                            int bytesRead;

                            while ((bytesRead = in.read(buf)) != -1) {
                                out.write(buf, 0, bytesRead);
                            }
                            in.close();
                            out.flush();
                            out.close();
                            return null;
                        }
                    }
                }
            }
        }

    } catch (java.io.IOException e) {
        errors.add(ActionMessages.GLOBAL_MESSAGE,
                new ActionMessage("errors.detail", "Unable to download file: " + fullFilePath));
        saveErrors(request, errors);
        e.printStackTrace();
        return mapping.findForward("error");
    } catch (Exception e) {
        e.printStackTrace();
        return mapping.findForward("error");
    }
    errors.add(ActionMessages.GLOBAL_MESSAGE,
            new ActionMessage("errors.detail", "Unable to download file: " + filename));
    saveErrors(request, errors);
    return mapping.findForward("error");
}

From source file:com.gae.ImageUpServlet.java

public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    //DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
    //ReturnValue value = new ReturnValue();
    MemoryFileItemFactory factory = new MemoryFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    resp.setContentType("image/jpeg");
    ServletOutputStream out = resp.getOutputStream();
    try {//from  w w  w  .j av a  2s  .c  om
        List<FileItem> list = upload.parseRequest(req);
        //FileItem list = upload.parseRequest(req);
        for (FileItem item : list) {
            if (!(item.isFormField())) {
                filename = item.getName();
                if (filename != null && !"".equals(filename)) {
                    int size = (int) item.getSize();
                    byte[] data = new byte[size];
                    InputStream in = item.getInputStream();
                    in.read(data);
                    ImagesService imagesService = ImagesServiceFactory.getImagesService();
                    Image newImage = ImagesServiceFactory.makeImage(data);
                    byte[] newImageData = newImage.getImageData();

                    //imgkey = KeyFactory.createKey(Imagedat.class.getSimpleName(), filename.split(".")[0]);   
                    //imgkey = KeyFactory.createKey(Imagedat.class.getSimpleName(), filename.split(".")[0]);   

                    out.write(newImageData);
                    out.flush();

                    DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
                    Key key = KeyFactory.createKey(kind, skey);
                    Blob blobImage = new Blob(newImageData);
                    DirectBeans_textjson dbeans = new DirectBeans_textjson();
                    /*  ?Date?     */
                    //Entity entity = dbeans.setentity("add", kind, true, key, id, val);

                    //ReturnValue value = dbeans.Called.setentity("add", kind, true, key, id, val);
                    //Entity entity = value.entity;
                    //DirectBeans.ReturnValue value = new DirectBeans.ReturnValue();
                    DirectBeans_textjson.entityVal eval = dbeans.setentity("add", kind, true, key, id, val);
                    Entity entity = eval.entity;

                    /*  ?Date                         */
                    //for(int i=0; i<id.length; i++ ){
                    //   if(id[i].equals("image")){
                    //      //filetitle = val[i];
                    //      //imgkey = KeyFactory.createKey(Imagedat.class.getSimpleName(), val[i]);   
                    //   }
                    //}                

                    entity.setProperty("image", blobImage);
                    Date date = new Date();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd:HHmmss");
                    sdf.setTimeZone(TimeZone.getTimeZone("JST"));
                    entity.setProperty("moddate", sdf.format(date));
                    //DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
                    ds.put(entity);
                    out.println("? KEY:" + key);
                }
            }
        }
    } catch (FileUploadException e) {
        e.printStackTrace();
    } finally {
        if (out != null) {
            out.close();
        }
    }
}

From source file:com.invbf.sistemagestionmercadeo.reportes.ReportCreator.java

public static void generadorSolicitudBono(Solicitudentrega elemento) {
    ServletOutputStream servletOutputStream = null;
    try {/*from www  .j  av a2  s . c om*/
        SolicitudBonoJuego elementoReporte = new SolicitudBonoJuego();
        if (elemento.getSolicitante().getUsuariodetalle().getIdcargo() != null) {
            elementoReporte.setCargo(elemento.getSolicitante().getUsuariodetalle().getIdcargo().getNombre());
        } else {
            elementoReporte.setCargo("");
        }
        elementoReporte.setCasino(elemento.getIdCasino().getNombre());
        SimpleDateFormat formateador = new SimpleDateFormat("dd-MMMM-yy", new Locale("es_ES"));
        elementoReporte.setFecha(formateador.format(elemento.getFecha()));
        elementoReporte.setJustificacion(elemento.getJustificacion());
        elementoReporte.setNombre(elemento.getSolicitante().getNombreUsuario());
        elementoReporte.setProposito(elemento.getPropositoEntrega().getNombre());
        elementoReporte.setTipobono(elemento.getTipoBono().getNombre());
        List<SolicitudBonoJuegoCliente> clientes = new ArrayList<SolicitudBonoJuegoCliente>();
        int item = 1;
        Float total = 0f;
        for (Solicitudentregacliente sec : elemento.getSolicitudentregaclienteList()) {
            clientes.add(new SolicitudBonoJuegoCliente((item) + "",
                    sec.getCliente().getNombres() + " " + sec.getCliente().getApellidos(),
                    sec.getValorTotal().toString(), sec.getAreaid().getNombre()));
            total += sec.getValorTotal();
            item++;
        }
        elementoReporte.setClientes(clientes);
        elementoReporte.setTotal(total.toString());
        ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
        InputStream input = externalContext
                .getResourceAsStream("/resources/reportes/solicitudbonosjuego.jasper");
        InputStream subreport = externalContext
                .getResourceAsStream("/resources/reportes/solicitudbonosjuego_cliente.jasper");
        InputStream logo = externalContext.getResourceAsStream("/resources/reportes/LogoMRCNegro.jpeg");
        InputStream logoibf = externalContext.getResourceAsStream("/resources/reportes/IBFLogo01jpeg.jpeg");
        ImageIcon tlc = new ImageIcon(IOUtils.toByteArray(logo));
        ImageIcon ibf = new ImageIcon(IOUtils.toByteArray(logoibf));
        elementoReporte.setIbf(ibf.getImage());
        elementoReporte.setLogo(tlc.getImage());
        List<SolicitudBonoJuego> lista = new ArrayList<SolicitudBonoJuego>();
        lista.add(elementoReporte);
        JRBeanCollectionDataSource beanColDataSource = new JRBeanCollectionDataSource(lista);
        JasperReport jasperMasterReport = (JasperReport) JRLoader.loadObject(input);
        JasperReport jasperSubReport = (JasperReport) JRLoader.loadObject(subreport);
        elementoReporte.setSubreportclientes(jasperSubReport);
        Map<String, Object> parameters = new HashMap<String, Object>();
        parameters.put("logo", lista.get(0).getLogo());
        parameters.put("ibf", lista.get(0).getIbf());
        parameters.put("clientes", lista.get(0).getClientes());
        parameters.put("subreportclientes", jasperSubReport);
        JasperPrint jasperPrint = JasperFillManager.fillReport(jasperMasterReport, parameters,
                beanColDataSource);
        HttpServletResponse httpServletResponse = (HttpServletResponse) FacesContext.getCurrentInstance()
                .getExternalContext().getResponse();
        httpServletResponse.addHeader("Content-disposition",
                "attachment; filename=ActaSolicitudBonosJuego" + elemento.getId() + ".pdf");
        servletOutputStream = httpServletResponse.getOutputStream();
        JasperExportManager.exportReportToPdfStream(jasperPrint, servletOutputStream);
    } catch (IOException ex) {
        Logger.getLogger(ReportCreator.class.getName()).log(Level.SEVERE, null, ex);
    } catch (JRException ex) {
        Logger.getLogger(ReportCreator.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            servletOutputStream.close();
        } catch (IOException ex) {
            Logger.getLogger(ReportCreator.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:org.codelabor.system.file.web.controller.xplatform.FileController.java

@RequestMapping("/download")
public String download(Model model, @RequestHeader("User-Agent") String userAgent,
        @RequestParam("fileId") String fileId, HttpServletResponse response) throws Exception {
    FileDTO fileDTO = fileManager.selectFileByFileId(fileId);
    logger.debug("fileDTO: {}", fileDTO);

    String repositoryPath = fileDTO.getRepositoryPath();
    String uniqueFilename = fileDTO.getUniqueFilename();
    String realFilename = fileDTO.getRealFilename();
    InputStream inputStream = null;
    BufferedInputStream bufferdInputStream = null;
    ServletOutputStream servletOutputStream = null;
    BufferedOutputStream bufferedOutputStream = null;

    StringBuilder sb = new StringBuilder();

    DataSetList outputDataSetList = new DataSetList();
    VariableList outputVariableList = new VariableList();

    try {/*from w  ww .j a  v  a2 s .  c o  m*/

        if (StringUtils.isNotEmpty(repositoryPath)) {
            // FILE_SYSTEM
            sb.append(repositoryPath);
            if (!repositoryPath.endsWith(File.separator)) {
                sb.append(File.separator);
            }
            sb.append(uniqueFilename);
            File file = new File(sb.toString());
            inputStream = new FileInputStream(file);
        } else {
            // DATABASE
            byte[] bytes = new byte[] {};
            if (fileDTO.getFileSize() > 0) {
                bytes = fileDTO.getBytes();
            }
            inputStream = new ByteArrayInputStream(bytes);

        }
        // set response contenttype, header
        String encodedRealFilename = URLEncoder.encode(realFilename, "UTF-8");
        logger.debug("realFilename: {}", realFilename);
        logger.debug("encodedRealFilename: {}", encodedRealFilename);

        response.setContentType(org.codelabor.system.file.FileConstants.CONTENT_TYPE);
        sb.setLength(0);
        if (userAgent.indexOf("MSIE5.5") > -1) {
            sb.append("filename=");
        } else {
            sb.append("attachment; filename=");
        }
        sb.append(encodedRealFilename);
        response.setHeader(HttpResponseHeaderConstants.CONTENT_DISPOSITION, sb.toString());
        logger.debug("header: {}", sb.toString());
        logger.debug("character encoding: {}", response.getCharacterEncoding());
        logger.debug("content type: {}", response.getContentType());
        logger.debug("bufferSize: {}", response.getBufferSize());
        logger.debug("locale: {}", response.getLocale());

        bufferdInputStream = new BufferedInputStream(inputStream);
        servletOutputStream = response.getOutputStream();
        bufferedOutputStream = new BufferedOutputStream(servletOutputStream);
        int bytesRead;
        byte buffer[] = new byte[2048];
        while ((bytesRead = bufferdInputStream.read(buffer)) != -1) {
            bufferedOutputStream.write(buffer, 0, bytesRead);
        }
        // flush stream
        bufferedOutputStream.flush();

        XplatformUtils.setSuccessMessage(
                messageSource.getMessage("info.success", new Object[] {}, forcedLocale), outputVariableList);
    } catch (Exception e) {
        e.printStackTrace();
        logger.error(e.getMessage());
        throw new XplatformException(messageSource.getMessage("error.failure", new Object[] {}, forcedLocale),
                e);
    } finally {
        // close stream
        inputStream.close();
        bufferdInputStream.close();
        servletOutputStream.close();
        bufferedOutputStream.close();
    }
    model.addAttribute(OUTPUT_DATA_SET_LIST, outputDataSetList);
    model.addAttribute(OUTPUT_VARIABLE_LIST, outputVariableList);
    return VIEW_NAME;

}

From source file:org.fcrepo.server.access.FedoraAccessServlet.java

/**
 * <p>/*  w w w  .  ja va2s .c  o m*/
 * This method calls the Fedora Access Subsystem to retrieve a MIME-typed
 * stream corresponding to the dissemination request.
 * </p>
 *
 * @param context
 *        The read only context of the request.
 * @param PID
 *        The persistent identifier of the Digital Object.
 * @param sDefPID
 *        The persistent identifier of the Service Definition object.
 * @param methodName
 *        The method name.
 * @param userParms
 *        An array of user-supplied method parameters.
 * @param asOfDateTime
 *        The version datetime stamp of the digital object.
 * @param response
 *        The servlet response.
 * @param request
 *        The servlet request.
 * @throws IOException
 *         If an error occurrs with an input or output operation.
 * @throws ServerException
 *         If an error occurs in the Access Subsystem.
 */
public void getDissemination(Context context, String PID, String sDefPID, String methodName,
        Property[] userParms, Date asOfDateTime, HttpServletResponse response, HttpServletRequest request)
        throws IOException, ServerException {
    ServletOutputStream out = null;
    MIMETypedStream dissemination = null;
    dissemination = m_access.getDissemination(context, PID, sDefPID, methodName, userParms, asOfDateTime);
    out = response.getOutputStream();
    try {
        // testing to see what's in request header that might be of interest
        if (logger.isDebugEnabled()) {
            for (Enumeration<?> e = request.getHeaderNames(); e.hasMoreElements();) {
                String name = (String) e.nextElement();
                Enumeration<?> headerValues = request.getHeaders(name);
                StringBuffer sb = new StringBuffer();
                while (headerValues.hasMoreElements()) {
                    sb.append((String) headerValues.nextElement());
                }
                String value = sb.toString();
                logger.debug("FEDORASERVLET REQUEST HEADER CONTAINED: {} : {}", name, value);
            }
        }

        // Dissemination was successful;
        // Return MIMETypedStream back to browser client
        if (dissemination.getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY) {
            String location = "";
            for (Property prop : dissemination.header) {
                if (prop.name.equalsIgnoreCase(HttpHeaders.LOCATION)) {
                    location = prop.value;
                    break;
                }
            }

            response.sendRedirect(location);
        } else {
            response.setContentType(dissemination.getMIMEType());
            Property[] headerArray = dissemination.header;
            if (headerArray != null) {
                for (int i = 0; i < headerArray.length; i++) {
                    if (headerArray[i].name != null
                            && !headerArray[i].name.equalsIgnoreCase("transfer-encoding")
                            && !headerArray[i].name.equalsIgnoreCase("content-type")) {
                        response.addHeader(headerArray[i].name, headerArray[i].value);
                        logger.debug(
                                "THIS WAS ADDED TO FEDORASERVLET  RESPONSE HEADER FROM ORIGINATING  PROVIDER {} : {}",
                                headerArray[i].name, headerArray[i].value);
                    }
                }
            }
            int byteStream = 0;
            logger.debug("Started reading dissemination stream");
            InputStream dissemResult = dissemination.getStream();
            byte[] buffer = new byte[BUF];
            while ((byteStream = dissemResult.read(buffer)) != -1) {
                out.write(buffer, 0, byteStream);
            }
            buffer = null;
            dissemResult.close();
            dissemResult = null;
            out.flush();
            out.close();
            logger.debug("Finished reading dissemination stream");
        }
    } finally {
        dissemination.close();
    }
}

From source file:org.oscarehr.document.web.ManageDocumentAction.java

public ActionForward viewDocPage(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) {/* w w  w. j a v  a 2s  .co  m*/
    log.debug("in viewDocPage");
    ServletOutputStream outs = null;
    BufferedInputStream bfis = null;
    try {
        String doc_no = request.getParameter("doc_no");
        String pageNum = request.getParameter("curPage");
        if (pageNum == null) {
            pageNum = "0";
        }
        Integer pn = Integer.parseInt(pageNum);
        log.debug("Document No :" + doc_no);
        LogAction.addLog((String) request.getSession().getAttribute("user"), LogConst.READ,
                LogConst.CON_DOCUMENT, doc_no, request.getRemoteAddr());

        Document d = documentDAO.getDocument(doc_no);
        log.debug("Document Name :" + d.getDocfilename());
        String name = d.getDocfilename() + "_" + pn + ".png";
        log.debug("name " + name);

        File outfile = null;
        outs = response.getOutputStream();

        if (d.getContenttype().contains("pdf")) {
            outfile = hasCacheVersion2(d, pn);
            if (outfile != null) {
                log.debug("got cached doc " + d.getDocfilename() + " from local cache");
            } else {
                outfile = createCacheVersion2(d, pn);
                if (outfile != null) {
                    log.debug("cache doc " + d.getDocfilename());
                }
            }
            response.setContentType("image/png");
            bfis = new BufferedInputStream(new FileInputStream(outfile));
            int data;
            while ((data = bfis.read()) != -1) {
                outs.write(data);
                // outs.flush();
            }
        } else if (d.getContenttype().contains("image")) {
            outfile = new File(EDocUtil.getDocumentPath(d.getDocfilename()));
            response.setContentType(d.getContenttype());
            response.setContentLength((int) outfile.length());
            response.setHeader("Content-Disposition", "inline; filename=" + d.getDocfilename());

            bfis = new BufferedInputStream(new FileInputStream(outfile));

            byte[] buffer = new byte[1024];
            int bytesRead = 0;
            while ((bytesRead = bfis.read(buffer)) != -1) {
                outs.write(buffer, 0, bytesRead);
            }
        }
        response.setHeader("Content-Disposition", "attachment;filename=" + d.getDocfilename());

        outs.flush();
    } catch (java.net.SocketException se) {
        MiscUtils.getLogger().error("Error", se);
    } catch (Exception e) {
        MiscUtils.getLogger().error("Error", e);
    } finally {
        if (bfis != null)
            try {
                bfis.close();
            } catch (IOException e) {
            }
        if (outs != null)
            try {
                outs.close();
            } catch (IOException e) {
            }
    }
    return null;
}

From source file:com.ibm.ioes.actions.NewOrderAction.java

/**
 * Method to get all data for Masters Download
 * @param mapping/*  ww  w  .java2  s  .  co m*/
 * @param form
 * @param request
 * @param response
 * @return
 */
public ActionForward downloadMasters(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) {

    NewOrderModel objModel = new NewOrderModel();
    NewOrderBean formBean = (NewOrderBean) form;
    //formBean.getProductID()
    HSSFWorkbook wb = objModel.downloadMasters(Long.parseLong(formBean.getHdnSelectedServiceDetailId()));
    formBean.setExcelWorkbookFormaster(wb);

    response.setHeader("Content-Disposition", "attachment; filename=Masters.xls");

    try {
        ServletOutputStream out = response.getOutputStream();
        formBean.getExcelWorkbookFormaster().write(out);
        out.flush();
        out.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return null;
}