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.jaspersoft.jasperserver.war.action.AbstractReportExporter.java

protected void exportBuffered(RequestContext context, HttpServletResponse response, JasperPrint jasperPrint,
        String reportUnitURI) throws IOException, JRException {
    Map parameters = new HashMap();
    parameters.put(JRExporterParameter.JASPER_PRINT, jasperPrint);

    FileBufferedOutputStream bufferedOutput = new FileBufferedOutputStream(getMemoryThreshold(),
            getInitialMemoryBufferSize());
    parameters.put(JRExporterParameter.OUTPUT_STREAM, bufferedOutput);

    try {/*from w  w  w  .  j a  v  a 2 s .  c  om*/
        export(context, getExecutionContext(context), reportUnitURI, parameters);
        bufferedOutput.close();

        int exportSize = bufferedOutput.size();
        if (log.isDebugEnabled()) {
            log.debug("exported to buffer of size " + exportSize);
        }

        response.setContentType(getContentType(context));
        setAdditionalResponseHeaders(context, response);
        response.setContentLength(exportSize);
        ServletOutputStream ouputStream = response.getOutputStream();

        try {
            bufferedOutput.writeData(ouputStream);
            bufferedOutput.dispose();

            ouputStream.flush();
        } finally {
            if (ouputStream != null) {
                try {
                    ouputStream.close();
                } catch (IOException ex) {
                    log.warn("Error closing output stream", ex);
                }
            }
        }
    } finally {
        bufferedOutput.close();
        bufferedOutput.dispose();
    }
}

From source file:org.apache.struts2.views.jasperreports.JasperReportsResult.java

protected void doExecute(String finalLocation, ActionInvocation invocation) throws Exception {
    // Will throw a runtime exception if no "datasource" property. TODO Best place for that is...?
    initializeProperties(invocation);//from   www  .jav  a 2s .c om

    if (LOG.isDebugEnabled()) {
        LOG.debug("Creating JasperReport for dataSource = " + dataSource + ", format = " + format);
    }

    HttpServletRequest request = (HttpServletRequest) invocation.getInvocationContext()
            .get(ServletActionContext.HTTP_REQUEST);
    HttpServletResponse response = (HttpServletResponse) invocation.getInvocationContext()
            .get(ServletActionContext.HTTP_RESPONSE);

    // Handle IE special case: it sends a "contype" request first.
    // TODO Set content type to config settings?
    if ("contype".equals(request.getHeader("User-Agent"))) {
        try {
            response.setContentType("application/pdf");
            response.setContentLength(0);

            ServletOutputStream outputStream = response.getOutputStream();
            outputStream.close();
        } catch (IOException e) {
            LOG.error("Error writing report output", e);
            throw new ServletException(e.getMessage(), e);
        }
        return;
    }

    // Construct the data source for the report.
    ValueStack stack = invocation.getStack();
    ValueStackDataSource stackDataSource = null;

    Connection conn = (Connection) stack.findValue(connection);
    if (conn == null)
        stackDataSource = new ValueStackDataSource(stack, dataSource);

    // Determine the directory that the report file is in and set the reportDirectory parameter
    // For WW 2.1.7:
    //  ServletContext servletContext = ((ServletConfig) invocation.getInvocationContext().get(ServletActionContext.SERVLET_CONFIG)).getServletContext();
    ServletContext servletContext = (ServletContext) invocation.getInvocationContext()
            .get(ServletActionContext.SERVLET_CONTEXT);
    String systemId = servletContext.getRealPath(finalLocation);
    Map parameters = new ValueStackShadowMap(stack);
    File directory = new File(systemId.substring(0, systemId.lastIndexOf(File.separator)));
    parameters.put("reportDirectory", directory);
    parameters.put(JRParameter.REPORT_LOCALE, invocation.getInvocationContext().getLocale());

    // put timezone in jasper report parameter
    if (timeZone != null) {
        timeZone = conditionalParse(timeZone, invocation);
        final TimeZone tz = TimeZone.getTimeZone(timeZone);
        if (tz != null) {
            // put the report time zone
            parameters.put(JRParameter.REPORT_TIME_ZONE, tz);
        }
    }

    // Add any report parameters from action to param map.
    Map reportParams = (Map) stack.findValue(reportParameters);
    if (reportParams != null) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Found report parameters; adding to parameters...");
        }
        parameters.putAll(reportParams);
    }

    byte[] output;
    JasperPrint jasperPrint;

    // Fill the report and produce a print object
    try {
        JasperReport jasperReport = (JasperReport) JRLoader.loadObject(systemId);
        if (conn == null)
            jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, stackDataSource);
        else
            jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, conn);
    } catch (JRException e) {
        LOG.error("Error building report for uri " + systemId, e);
        throw new ServletException(e.getMessage(), e);
    }

    // Export the print object to the desired output format
    try {
        if (contentDisposition != null || documentName != null) {
            final StringBuffer tmp = new StringBuffer();
            tmp.append((contentDisposition == null) ? "inline" : contentDisposition);

            if (documentName != null) {
                tmp.append("; filename=");
                tmp.append(documentName);
                tmp.append(".");
                tmp.append(format.toLowerCase());
            }

            response.setHeader("Content-disposition", tmp.toString());
        }

        JRExporter exporter;

        if (format.equals(FORMAT_PDF)) {
            response.setContentType("application/pdf");
            exporter = new JRPdfExporter();
        } else if (format.equals(FORMAT_CSV)) {
            response.setContentType("text/csv");
            exporter = new JRCsvExporter();
        } else if (format.equals(FORMAT_HTML)) {
            response.setContentType("text/html");

            // IMAGES_MAPS seems to be only supported as "backward compatible" from JasperReports 1.1.0

            Map imagesMap = new HashMap();
            request.getSession(true).setAttribute("IMAGES_MAP", imagesMap);

            exporter = new JRHtmlExporter();
            exporter.setParameter(JRHtmlExporterParameter.IMAGES_MAP, imagesMap);
            exporter.setParameter(JRHtmlExporterParameter.IMAGES_URI,
                    request.getContextPath() + imageServletUrl);

            // Needed to support chart images:
            exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
            request.getSession().setAttribute("net.sf.jasperreports.j2ee.jasper_print", jasperPrint);
        } else if (format.equals(FORMAT_XLS)) {
            response.setContentType("application/vnd.ms-excel");
            exporter = new JRXlsExporter();
        } else if (format.equals(FORMAT_XML)) {
            response.setContentType("text/xml");
            exporter = new JRXmlExporter();
        } else if (format.equals(FORMAT_RTF)) {
            response.setContentType("application/rtf");
            exporter = new JRRtfExporter();
        } else {
            throw new ServletException("Unknown report format: " + format);
        }

        Map exportParams = (Map) stack.findValue(exportParameters);
        if (exportParams != null) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Found export parameters; adding to exporter parameters...");
            }
            exporter.getParameters().putAll(exportParams);
        }

        output = exportReportToBytes(jasperPrint, exporter);
    } catch (JRException e) {
        String message = "Error producing " + format + " report for uri " + systemId;
        LOG.error(message, e);
        throw new ServletException(e.getMessage(), e);
    }

    response.setContentLength(output.length);

    // Will throw ServletException on IOException.
    writeReport(response, output);
}

From source file:com.googlecode.noweco.calendar.CaldavServlet.java

@Override
public void doGet(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
    MemoryFile locate = MemoryFileUtils.locate(ROOT, req.getRequestURI());
    if (locate == null) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;// w  w  w . ja  va2  s  . c  o  m
    }
    Getcontenttype getcontenttype = locate.getProp().getGetcontenttype();
    if (getcontenttype != null) {
        resp.setContentType(getcontenttype.getContent().get(0));
    }
    ServletOutputStream outputStream = resp.getOutputStream();
    outputStream.write(locate.getContent());
    outputStream.close();
}

From source file:com.sample.RSSAdapterResource.java

public void execute(HttpUriRequest req, HttpServletResponse resultResponse)
        throws ClientProtocolException, IOException, IllegalStateException, SAXException {
    HttpResponse RSSResponse = client.execute(host, req);
    ServletOutputStream os = resultResponse.getOutputStream();
    if (RSSResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        resultResponse.addHeader("Content-Type", "application/json");
        String json = XML.toJson(RSSResponse.getEntity().getContent());
        os.write(json.getBytes(Charset.forName("UTF-8")));

    } else {/* ww  w. j  ava2s. c o  m*/
        resultResponse.setStatus(RSSResponse.getStatusLine().getStatusCode());
        RSSResponse.getEntity().getContent().close();
        os.write(RSSResponse.getStatusLine().getReasonPhrase().getBytes());
    }
    os.flush();
    os.close();
}

From source file:de.berlios.jedi.presentation.admin.GetJispObjectAction.java

/**
 * Handle server requests./*from w ww .jav  a2 s . com*/
 * 
 * @param mapping
 *            The ActionMapping used to select this instance.
 * @param form
 *            The optional ActionForm bean for this request (if any).
 * @param request
 *            The HTTP request we are processing.
 * @param response
 *            The HTTP response we are creating.
 */
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) {

    JispIdManager jispIdManager = (JispIdManager) request.getSession()
            .getAttribute(AdminKeys.JISP_ID_MANAGER_KEY);

    String jispObjectId = request.getParameter("jispObjectId");

    if (jispObjectId == null) {
        return errorForward(mapping, request, new ActionMessage("missedId", "jispObjectId"), "adminMissedId");
    }

    JispObject jispObject = jispIdManager.getJispObject(jispObjectId);

    if (jispObject == null) {
        return errorForward(mapping, request, new ActionMessage("invalidId", "jispObjectId"), "adminInvalidId");
    }

    response.setContentType(jispObject.getMimeType());

    ServletOutputStream out = null;
    try {
        out = response.getOutputStream();
        out.write(jispObject.getData());
    } catch (IOException e) {
        LogFactory.getLog(GetJispObjectAction.class)
                .error("IOException when writing the JispObject to the" + " ServlerOutputStream", e);

        return errorForward(mapping, request, new ActionMessage("failedJispObjectWriteToOutputStream"),
                "adminFailedJispObjectWriteToOutputStream");
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
            }
        }
    }

    return null;
}

From source file:gxu.software_engineering.shen10.market.core.MappingJacksonJsonpView.java

@Override
public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    //      utf8/*  ww  w .  j av  a  2 s.  c o m*/
    // String charset = response.getCharacterEncoding();
    // if (charset == null || charset.length() == 0) {
    //    response.setCharacterEncoding(DEFAULT_CHARSET);
    // }

    if (request.getMethod().toUpperCase().equals("GET")) {
        if (request.getParameterMap().containsKey("callback")) {
            ServletOutputStream ostream = response.getOutputStream();
            //            try
            ostream.write(new String("try{" + request.getParameter("callback") + "(").getBytes());
            super.render(model, request, response);
            ostream.write(new String(");}catch(e){}").getBytes());
            //            ????closeflushspring?
            //            ?
            ostream.flush();
            ostream.close();
        } else {
            super.render(model, request, response);
        }
    } else {
        super.render(model, request, response);
    }
}

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

@RequestMapping
public ModelAndView ics(HttpServletRequest req, HttpServletResponse res) throws Exception {
    try {//  w w w. j  ava  2 s  . com
        EventSearch eventSearch = buildEventSearch(req);
        List<Event> events = eventBo.search(eventSearch);

        Calendar calendar = feedsBo.buildCalendar(events, Utilities.getBaseUrl(req));

        // flush it in the res
        res.setContentType("text/calendar");
        res.setHeader("Content-Disposition", " attachment; filename=\"JUGEventsCalendar.ics\"");
        res.setHeader("Expires", "0");
        res.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0, no-store");
        res.setHeader("Pragma", "public, no-cache");
        res.setCharacterEncoding("UTF-8");

        CalendarOutputter outputter = new CalendarOutputter(true);
        ServletOutputStream resOutputStream = res.getOutputStream();
        if (calendar.getComponents().isEmpty()) {
            outputter.setValidating(false);
        }
        outputter.output(calendar, resOutputStream);
        resOutputStream.flush();
        resOutputStream.close();
    } catch (Exception exception) {
        logger.error("Error producing ICS", exception);
        throw exception;
    }
    return null;
}

From source file:org.kuali.ext.mm.document.web.struts.CountWorksheetPrintAction.java

private void combineAndFlushReportPDFFiles(List<File> fileList, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    long startTime = System.currentTimeMillis();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ArrayList master = new ArrayList();
    int pageOffset = 0;
    int f = 0;/*from   ww w  .j  a v a  2  s.c om*/
    PdfCopy writer = null;
    com.lowagie.text.Document document = null;
    for (File file : fileList) {
        // we create a reader for a certain document
        String reportName = file.getAbsolutePath();
        PdfReader reader = new PdfReader(reportName);
        reader.consolidateNamedDestinations();
        // we retrieve the total number of pages
        int n = reader.getNumberOfPages();
        List bookmarks = SimpleBookmark.getBookmark(reader);
        if (bookmarks != null) {
            if (pageOffset != 0) {
                SimpleBookmark.shiftPageNumbers(bookmarks, pageOffset, null);
            }
            master.addAll(bookmarks);
        }
        pageOffset += n;

        if (f == 0) {
            // step 1: creation of a document-object
            document = new com.lowagie.text.Document(reader.getPageSizeWithRotation(1));
            // step 2: we create a writer that listens to the document
            writer = new PdfCopy(document, baos);
            // step 3: we open the document
            document.open();
        }
        // step 4: we add content
        PdfImportedPage page;
        for (int i = 0; i < n;) {
            ++i;
            page = writer.getImportedPage(reader, i);
            writer.addPage(page);
        }
        writer.freeReader(reader);
        f++;
    }

    if (!master.isEmpty())
        writer.setOutlines(master);
    // step 5: we close the document
    document.close();

    StringBuffer sbContentDispValue = new StringBuffer();
    String useJavascript = request.getParameter("useJavascript");
    if (useJavascript == null || useJavascript.equalsIgnoreCase("false")) {
        sbContentDispValue.append("attachment");
    } else {
        sbContentDispValue.append("inline");
    }
    sbContentDispValue.append("; filename=");
    sbContentDispValue.append(MMUtil.getFileName());

    String contentDisposition = sbContentDispValue.toString();

    response.setContentType("application/pdf");
    response.setHeader("Content-disposition", contentDisposition);
    response.setHeader("Expires", "0");
    response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
    response.setHeader("Pragma", "public");
    response.setContentLength(baos.size());

    // write to output
    ServletOutputStream sos = response.getOutputStream();
    baos.writeTo(sos);
    sos.flush();
    baos.close();
    sos.close();
    long endTime = System.currentTimeMillis();
    loggerAc.debug("Time taken for report Parameter settings in action " + (endTime - startTime));
}

From source file:module.workingCapital.presentationTier.action.WorkingCapitalAction.java

private ActionForward streamSpreadsheet(final HttpServletResponse response, final String fileName,
        final SpreadsheetBuilder spreadSheetBuilder) throws IOException {
    response.setContentType("application/xls ");
    response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".xls");

    ServletOutputStream outputStream = response.getOutputStream();

    spreadSheetBuilder.build(WorkbookExportFormat.EXCEL, outputStream);
    outputStream.flush();//  ww  w  .  j  ava 2 s  .com
    outputStream.close();

    return null;
}

From source file:org.wso2.carbon.application.mgt.ui.ApplicationAdminClient.java

public void downloadCappArchive(String filename, HttpServletResponse response)
        throws IOException, ApplicationAdminExceptionException {

    ServletOutputStream out = response.getOutputStream();
    DataHandler dataHandler = stub.downloadCappArchive(filename);
    if (dataHandler != null) {
        response.setHeader("Content-Disposition", "fileName=" + filename + ".car");
        response.setContentType(dataHandler.getContentType());
        InputStream in = dataHandler.getDataSource().getInputStream();
        int nextChar;
        while ((nextChar = in.read()) != -1) {
            out.write((char) nextChar);
        }/*from w  ww . j  av a2  s  .c o  m*/
        out.flush();
        in.close();
        out.close();
    } else {
        out.write("The requested capp archive was not found on the server".getBytes());
    }

}