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:com.ephesoft.gxt.foldermanager.server.UploadDownloadFilesServlet.java

private void downloadFile(HttpServletRequest req, HttpServletResponse response,
        String currentFileDownloadPath) {
    DataInputStream in = null;/*from   w w  w  . j a  v  a 2 s. co  m*/
    ServletOutputStream outStream = null;
    try {
        outStream = response.getOutputStream();
        File file = new File(currentFileDownloadPath);
        int length = 0;
        String mimetype = "application/octet-stream";
        response.setContentType(mimetype);
        response.setContentLength((int) file.length());
        String fileName = file.getName();
        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        byte[] byteBuffer = new byte[1024];
        in = new DataInputStream(new FileInputStream(file));
        while ((in != null) && ((length = in.read(byteBuffer)) != -1)) {
            outStream.write(byteBuffer, 0, length);
        }
    } catch (IOException e) {
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
            }
        }
        if (outStream != null) {
            try {
                outStream.flush();
            } catch (IOException e) {
            }
            try {
                outStream.close();
            } catch (IOException e) {
            }

        }
    }
}

From source file:org.sakaiproject.tool.assessment.ui.servlet.delivery.ShowAttachmentMediaServlet.java

public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    String resourceId = req.getParameter("resourceId");
    String mimeType = req.getParameter("mimeType");
    String filename = req.getParameter("filename");

    String cleanedFilename = TextFormat.convertPlaintextToFormattedTextNoHighUnicode(log, filename);

    res.setHeader("Content-Disposition", "inline;filename=\"" + cleanedFilename + "\";");
    log.debug("resourceId = " + resourceId);
    log.debug("mimeType = " + mimeType);
    log.debug("cleanedFilename = " + cleanedFilename);

    // ** note that res.setContentType() must be called before
    // res.getOutputStream(). see javadoc on this
    res.setContentType(mimeType);/* w  ww . j  a v a 2  s. co m*/

    ContentResource cr = null;
    byte[] media = null;
    try {
        // create a copy of the resource
        cr = AssessmentService.getContentHostingService().getResource(resourceId);
        if (cr == null) {
            return;
        }
        media = cr.getContent();
        if (media == null) {
            return;
        }
        res.setContentLength((int) cr.getContentLength());
        log.debug("**** media.length = " + media.length);

    } catch (PermissionException e) {
        log.warn("PermissionException from doPost(): " + e.getMessage());
    } catch (IdUnusedException e) {
        log.warn("IdUnusedException from doPost(): " + e.getMessage());
    } catch (TypeException e) {
        log.warn("TypeException from doPost(): " + e.getMessage());
    } catch (ServerOverloadException e) {
        log.warn("ServerOverloadException from doPost(): " + e.getMessage());
    } finally {
        // in case of any exceptions above being caught, media would still be null 
        if (media == null) {
            return;
        }
    }

    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(media);
    BufferedInputStream buf_inputStream = new BufferedInputStream(byteArrayInputStream);
    ServletOutputStream outputStream = res.getOutputStream();
    BufferedOutputStream buf_outputStream = null;
    int count = 0;
    try {

        buf_outputStream = new BufferedOutputStream(outputStream);

        int i = 0;
        while ((i = buf_inputStream.read()) != -1) {
            // System.out.print(i);
            buf_outputStream.write(i);
            count++;
        }

        //res.setContentLength(count);
        res.flushBuffer();
    } catch (Exception e) {
        log.warn(e.getMessage());
    } finally {
        if (buf_outputStream != null) {
            try {
                buf_outputStream.close();
            } catch (IOException e) {
                log.error(e.getMessage());
            }
        }
        if (buf_inputStream != null) {
            try {
                buf_inputStream.close();
            } catch (IOException e) {
                log.error(e.getMessage());
            }
        }
        if (outputStream != null) {
            try {
                outputStream.close();
            } catch (IOException e) {
                log.error(e.getMessage());
            }
        }
        if (byteArrayInputStream != null) {
            try {
                byteArrayInputStream.close();
            } catch (IOException e) {
                log.error(e.getMessage());
            }
        }
    }
}

From source file:org.itracker.web.actions.report.DisplayReportAction.java

/**
 *
 *///from w  ww  . ja  va  2s.  co  m
public static void outputReport(List<Issue> reportDataArray, Project project, Report report, Locale userLocale,
        String reportOutput, HttpServletResponse response) throws ReportException {

    try {
        // hack, we have to find a more structured way to support
        // various types of queries
        final JRBeanCollectionDataSource beanCollectionDataSource = new JRBeanCollectionDataSource(
                reportDataArray);

        final Map<String, Object> parameters = new HashMap<String, Object>();
        String reportTitle = report.getName();
        if (project != null) {
            reportTitle += " - " + project.getName();
            if (report.getNameKey() != null) {
                reportTitle = ITrackerResources.getString(report.getNameKey(), project.getName());
            }
        } else if (report.getNameKey() != null) {
            reportTitle = ITrackerResources.getString(report.getNameKey());
        }
        parameters.put("ReportTitle", reportTitle);
        parameters.put("BaseDir", new File("."));
        parameters.put("REPORT_LOCALE", userLocale);
        parameters.put("REPORT_RESOURCE_BUNDLE", ITrackerResourceBundle.getBundle(userLocale));

        final JasperPrint jasperPrint = generateReport(report, parameters, beanCollectionDataSource);

        final ServletOutputStream out = response.getOutputStream();
        final JRExporter x;
        if (ReportUtilities.REPORT_OUTPUT_PDF.equals(reportOutput)) {

            response.setHeader("Content-Type", "application/pdf");
            response.setHeader("Content-Disposition", "attachment; filename=\"" + report.getName()
                    + new SimpleDateFormat("-yyyy-MM-dd").format(new Date()) + ".pdf\"");
            x = new JRPdfExporter();

        } else if (ReportUtilities.REPORT_OUTPUT_XLS.equals(reportOutput)) {
            response.setHeader("Content-Type", "application/xls");
            response.setHeader("Content-Disposition", "attachment; filename=\"" + report.getName()
                    + new SimpleDateFormat("-yyyy-MM-dd").format(new Date()) + ".xls\"");
            x = new JRXlsExporter();

        } else if (ReportUtilities.REPORT_OUTPUT_CSV.equals(reportOutput)) {

            response.setHeader("Content-Type", "text/csv");
            response.setHeader("Content-Disposition", "attachment; filename=\"" + report.getName()
                    + new SimpleDateFormat("-yyyy-MM-dd").format(new Date()) + ".csv\"");
            x = new JRCsvExporter();

        } else if (ReportUtilities.REPORT_OUTPUT_HTML.equals(reportOutput)) {
            response.setHeader("Content-Type", "text/html");
            response.setHeader("Content-Disposition", "attachment; filename=\"" + report.getName()
                    + new SimpleDateFormat("-yyyy-MM-dd").format(new Date()) + ".html\"");
            x = new JRHtmlExporter();

        } else {
            log.error("Invalid report output format: " + reportOutput);
            throw new ReportException("Invalid report type.", "itracker.web.error.invalidreportoutput");
        }
        x.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
        x.setParameter(JRExporterParameter.OUTPUT_STREAM, out);

        x.exportReport();

        out.flush();
        out.close();
    } catch (JRException e) {
        throw new ReportException(e);
    } catch (IOException e) {
        throw new ReportException(e);
    }

}

From source file:net.sourceforge.fenixedu.presentationTier.Action.publico.candidacies.erasmus.ErasmusIndividualCandidacyProcessPublicDA.java

public ActionForward retrieveLearningAgreement(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response) throws Exception {
    MobilityIndividualApplicationProcess process = (MobilityIndividualApplicationProcess) getProcess(request);

    final LearningAgreementDocument document = new LearningAgreementDocument(process);
    byte[] data = ReportsUtils.exportMultipleToPdfAsByteArray(document);

    response.setContentLength(data.length);
    response.setContentType("application/pdf");
    response.addHeader("Content-Disposition", "attachment; filename=" + document.getReportFileName() + ".pdf");

    final ServletOutputStream writer = response.getOutputStream();
    writer.write(data);//from  www.j  a  va  2s.c om
    writer.flush();
    writer.close();

    response.flushBuffer();
    return mapping.findForward("");
}

From source file:com.globalsight.everest.webapp.pagehandler.tasks.UpdateLeverageHandler.java

@ActionHandler(action = "getPercentage", formClass = "")
public void getPercentage(HttpServletRequest p_request, HttpServletResponse p_response, Object form)
        throws Exception {
    String jobId = p_request.getParameter("jobId");
    int percentage = percentageMap.get(Long.parseLong(jobId));
    String fakeParam = p_request.getParameter("fresh");
    if (logger.isDebugEnabled()) {
        logger.debug(/*from   w w w .ja va2s. c  o  m*/
                "FakeParam is " + fakeParam + "; Current jobId is " + jobId + "; Percentage is " + percentage);
    }

    ServletOutputStream out = p_response.getOutputStream();
    try {
        p_response.setContentType("text/plain");
        out = p_response.getOutputStream();
        StringBuffer sb = new StringBuffer();
        sb.append("{\"updateLeveragePercentage\":");
        sb.append(percentage).append("}");
        out.write(sb.toString().getBytes("UTF-8"));
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    } finally {
        out.close();
        pageReturn();
    }
}

From source file:org.kuali.kra.coi.disclosure.CoiDisclosureAction.java

/**
 * /*from   w w w. j  ava2  s. co m*/
 * This method is for use with a JSON/AJAX call and should not be used as a post method
 * 
 */
public ActionForward getDisclosureEventTypeInfo(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response) throws Exception {

    String eventType = request.getParameter("eventType");
    Map<String, Object> fieldValues = new HashMap<String, Object>();
    fieldValues.put("eventTypeCode", eventType);

    List<CoiDisclosureEventType> disclosureEventTypes = (List<CoiDisclosureEventType>) getBusinessObjectService()
            .findMatching(CoiDisclosureEventType.class, fieldValues);
    StringWriter writer = new StringWriter();
    if (!CollectionUtils.isEmpty(disclosureEventTypes)) {
        CoiDisclosureEventType disclosureEventType = disclosureEventTypes.get(0);
        CoiDisclosureEventTypeAjaxBean disclosureEventTypeAjaxBean = new CoiDisclosureEventTypeAjaxBean();
        disclosureEventTypeAjaxBean.setDisclosureEventType(disclosureEventType);

        //Special code to handle select box
        if (disclosureEventType.isUseSelectBox1()) {
            try {
                String valuesFinder = disclosureEventType.getSelectBox1ValuesFinder();
                if (StringUtils.isNotBlank(valuesFinder)) {
                    Class valuesFinderClass = Class.forName(valuesFinder);
                    KeyValuesFinder keyValuesFinder = (KeyValuesFinder) valuesFinderClass.newInstance();
                    List<KeyValue> keyValues = keyValuesFinder.getKeyValues();
                    if (!CollectionUtils.isEmpty(keyValues)) {
                        disclosureEventTypeAjaxBean.setKeyValues(keyValues);
                    }
                }
            } catch (Exception e) {
                //Failed to load select box 
            }
        }

        // disclosure ID and label are always required, so put in a default
        if (StringUtils.isEmpty(disclosureEventType.getProjectIdLabel())) {
            disclosureEventType.setProjectIdLabel(CoreApiServiceLocator.getKualiConfigurationService()
                    .getPropertyValueAsString(DEFAULT_EVENT_ID_STRING));
        }
        if (StringUtils.isEmpty(disclosureEventType.getProjectTitleLabel())) {
            disclosureEventType.setProjectTitleLabel(CoreApiServiceLocator.getKualiConfigurationService()
                    .getPropertyValueAsString(DEFAULT_EVENT_TITLE_STRING));
        }
        ObjectMapper mapper = new ObjectMapper();
        mapper.writeValue(writer, disclosureEventTypeAjaxBean);

        response.setContentType("application/json");
        ServletOutputStream out = response.getOutputStream();

        try {
            out.write(writer.getBuffer().toString().getBytes());
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace(new PrintWriter(out));
        }

    }
    return null;
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.publico.candidacies.erasmus.ErasmusIndividualCandidacyProcessPublicDA.java

public ActionForward retrieveApprovedLearningAgreement(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response) throws Exception {
    final ApprovedLearningAgreementDocumentFile file = getDomainObject(request, "agreementId");
    final String hash = request.getParameter("hash");

    final MobilityIndividualApplicationProcess process = file.getProcess();
    final DegreeOfficePublicCandidacyHashCode candidacyHashCode = process.getCandidacyHashCode();
    if (candidacyHashCode.getValue().equals(hash)) {
        final byte[] content = file.getContent();
        response.setContentLength(content.length);
        response.setContentType("application/pdf");
        response.addHeader("Content-Disposition", "attachment; filename=" + file.getFilename());

        final ServletOutputStream writer = response.getOutputStream();
        writer.write(content);//from w  w w.ja  va 2s  . c  om
        writer.flush();
        writer.close();

        response.flushBuffer();
    }

    return null;
}

From source file:be.fedict.eid.idp.sp.PhotoServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    LOG.debug("doGet");
    response.setContentType("image/jpg");
    response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate, max-age=-1"); // http 1.1
    response.setHeader("Pragma", "no-cache, no-store"); // http 1.0
    response.setDateHeader("Expires", -1);
    ServletOutputStream out = response.getOutputStream();
    HttpSession session = request.getSession();

    byte[] photoData = (byte[]) session.getAttribute(PHOTO_SESSION_ATTRIBUTE);

    if (null != photoData) {
        BufferedImage photo = ImageIO.read(new ByteArrayInputStream(photoData));
        if (null == photo) {
            /*/*from w  w  w  . ja  v  a 2s .  c  o  m*/
             * In this case we render a photo containing some error message.
             */
            photo = new BufferedImage(140, 200, BufferedImage.TYPE_INT_RGB);
            Graphics2D graphics = (Graphics2D) photo.getGraphics();
            RenderingHints renderingHints = new RenderingHints(RenderingHints.KEY_TEXT_ANTIALIASING,
                    RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
            graphics.setRenderingHints(renderingHints);
            graphics.setColor(Color.WHITE);
            graphics.fillRect(1, 1, 140 - 1 - 1, 200 - 1 - 1);
            graphics.setColor(Color.RED);
            graphics.setFont(new Font("Dialog", Font.BOLD, 20));
            graphics.drawString("Photo Error", 0, 200 / 2);
            graphics.dispose();
            ImageIO.write(photo, "jpg", out);
        } else {
            out.write(photoData);
        }
    }
    out.close();
}

From source file:org.kuali.ole.web.DocumentServlet.java

/**
 * Method sends the response generated for the given request
 *
 * @param res//from  ww w.j a  v  a  2s.co m
 * @param file
 * @throws IOException
 */
private void sendResponseAsFile(HttpServletResponse res, File file) throws IOException {
    ServletOutputStream stream = res.getOutputStream();
    FileInputStream fos = new FileInputStream(file.getAbsolutePath());
    BufferedInputStream buf = new BufferedInputStream(fos);
    int readBytes = 0;
    while ((readBytes = buf.read()) != -1) {
        stream.write(readBytes);
    }
    if (stream != null) {
        stream.close();
    }
    if (buf != null) {
        buf.close();
    }
    res.flushBuffer();
}

From source file:it.cnr.icar.eric.server.interfaces.rest.FilePathURLHandler.java

/** Write the partial directory listing showing specified members for the specified folder */
private void writeDirectoryListing(String pathInfo, RegistryPackageType pkg, List<?> members)
        throws IOException, RegistryException {
    ServletOutputStream sout = null;
    try {//from   w w  w  . j a  va2 s  .com
        sout = response.getOutputStream();

        sout.println("<html>");
        sout.println("<head>");
        sout.println("<title>Index of " + pathInfo + "</title>");
        sout.println("</head>");
        sout.println("<body>");
        sout.println("<h1>Index of " + pathInfo + "</h1>");
        sout.println("<pre>ObjectType\t\t<a href=\"?N=D\">Name</a>\t\t<a ref=\"?D=A\">Description</a>");
        sout.println("<hr/>");
        sout.println("<a href=\"./..\">Goto Parent Directory</a> <br/>");

        Iterator<?> iter = members.iterator();
        while (iter.hasNext()) {
            RegistryObjectType member = (RegistryObjectType) iter.next();
            writeDirectoryListingItem(sout, member);
        }

        sout.println("</pre>");
        sout.println("<hr/>");
        sout.println("<address>freebXML Regisry Server version 3.0</address>");
        sout.println("</body>");
        sout.println("</html>");
    } finally {
        if (sout != null) {
            sout.close();
        }
    }
}