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:jp.co.opentone.bsol.framework.web.view.util.ViewHelper.java

protected void doDownload(HttpServletResponse response, InputStream in) throws IOException {
    ServletOutputStream o = getServletOutputStream(response);
    try {/*from  w w  w .j  av  a2  s  . co  m*/
        final int bufLength = 4096;
        byte[] buf = new byte[bufLength];
        int i = 0;
        while ((i = in.read(buf, 0, buf.length)) != -1) {
            o.write(buf, 0, i);
        }

        o.flush();
        o.close();
    } catch (IOException e) {
        if (isDownloadCanceled(e)) {
            log.warn("Download canceled.");
        } else {
            throw e;
        }
    }
}

From source file:com.ewcms.content.vote.web.ResultServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    ServletOutputStream out = null;
    StringBuffer output = new StringBuffer();
    try {//from ww  w.  j av a2 s .  c  o  m
        String id = req.getParameter("id");

        if (!id.equals("") && StringUtils.isNumeric(id)) {
            Long questionnaireId = new Long(id);

            ServletContext application = getServletContext();
            WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(application);
            QuestionnaireService questionnaireService = (QuestionnaireService) wac
                    .getBean("questionnaireService");

            String ipAddr = req.getRemoteAddr();

            output = questionnaireService.getQuestionnaireResultClientToHtml(questionnaireId,
                    getServletContext().getContextPath(), ipAddr);
        }
        out = resp.getOutputStream();
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html; charset=UTF-8");
        out.write(output.toString().getBytes("UTF-8"));
        out.flush();
    } finally {
        if (out != null) {
            out.close();
            out = null;
        }
    }
}

From source file:org.opencastproject.manager.system.workflow.WorkflowManager.java

/**
 * Handle workflow's files.//from   w ww.ja  v  a  2s  .  com
 *
 * @param request
 * @param response
 * @throws ServletException
 * @throws IOException
 */
public void handleWorkflowFiles(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String fileName = stringValidator((String) request.getParameter("workflow_file"));
    String empty = "";

    if (empty.equals(fileName) || fileName == null)
        throw new ServletException("Invalid or non-existent file parameter in SendXml servlet.");

    String xmlDir = PluginManagerConstants.WORKFLOWS_PATH;

    if (empty.equals(xmlDir) || xmlDir == null)
        throw new ServletException("Invalid or non-existent xmlDir context-param.");

    ServletOutputStream stream = null;
    BufferedInputStream buf = null;

    try {
        stream = response.getOutputStream();
        File xml = new File(xmlDir + fileName);

        response.setContentType("text/xml");
        response.addHeader("Content-Disposition", "attachment; filename=" + fileName);
        response.setContentLength((int) xml.length());

        FileInputStream input = new FileInputStream(xml);

        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.seer.datacruncher.spring.ChecksTypeReadController.java

@SuppressWarnings("unchecked")
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    ObjectMapper mapper = new ObjectMapper();
    ServletOutputStream out = null;
    response.setContentType("application/json");
    out = response.getOutputStream();/*from w w w  .j av  a  2s. co m*/
    String idSchemaField = request.getParameter("idSchemaField");
    ReadList readList = checksTypeDao.read(-1, -1);
    List<ChecksTypeEntity> checkTypeEntites = (List<ChecksTypeEntity>) readList.getResults();
    if (StringUtils.isNotEmpty(idSchemaField)) {
        String leftPane = request.getParameter("leftPane");
        ReadList assignedReadList = checksTypeDao.readCheckTypeBySchemaFieldId(Long.parseLong(idSchemaField));
        List<ChecksTypeEntity> assignedCheckTypeEntites = (List<ChecksTypeEntity>) assignedReadList
                .getResults();
        if ("true".equalsIgnoreCase(leftPane)) {
            if (CollectionUtils.isNotEmpty(assignedCheckTypeEntites)) {
                checkTypeEntites.removeAll(assignedCheckTypeEntites);
            }
        } else {
            readList.setResults(assignedCheckTypeEntites);
        }
    }
    out.write(mapper.writeValueAsBytes(readList));
    out.flush();
    out.close();
    return null;
}

From source file:fr.insalyon.creatis.vip.query.server.rpc.FileDownload.java

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

    User user = (User) req.getSession().getAttribute(CoreConstants.SESSION_USER);
    String queryId = req.getParameter("queryid");
    String path = req.getParameter("path");
    String queryName = req.getParameter("name");
    String tab[] = path.split("/");

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

        try {/*w ww. ja  v a2s.  c  o  m*/

            String k = new String();

            int l = tab.length;
            for (int i = 0; i < l - 1; i++) {
                k += "//" + tab[i];
            }
            File file = new File(k);
            logger.info("that" + k);
            if (file.isDirectory()) {

                file = new File(k + "/" + tab[l - 1]);

            }
            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());
            //name of the file in servlet download
            resp.setHeader("Content-Disposition", "attachment; filename=\"" + queryName + "_"
                    + getCurrentTimeStamp().toString().replaceAll(" ", "_") + ".txt" + "\"");

            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 (Exception ex) {
            logger.error(ex);
        }

    }
}

From source file:org.kuali.student.core.document.ui.server.upload.UploadServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    DocumentInfo info = null;/*from  w  ww.  ja  v a 2 s.  c o m*/
    try {
        info = documentService.getDocument(request.getParameter("docId"), ContextUtils.getContextInfo());
    } catch (Exception e) {
        LOG.error("Exception occurred", e);
    }

    if (info != null && info.getDocumentBinary() != null && info.getDocumentBinary().getBinary() != null
            && !(info.getDocumentBinary().getBinary().isEmpty())) {

        ServletOutputStream op = response.getOutputStream();
        try {
            byte[] fileBytes = Base64.decodeBase64(info.getDocumentBinary().getBinary().getBytes());
            int length = fileBytes.length;

            ServletContext context = getServletConfig().getServletContext();
            String mimetype = context.getMimeType(info.getFileName());

            response.setContentType((mimetype != null) ? mimetype : "application/octet-stream");
            response.setContentLength(length);
            response.setHeader("Content-Disposition", "attachment; filename=\"" + info.getFileName() + "\"");

            //
            //  Stream to the requester.
            //
            op.write(fileBytes, 0, length);
        } catch (Exception e) {
            LOG.error("Exception occurred", e);
        } finally {
            op.flush();
            op.close();
        }

    } else {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println(
                "Sorry, the file could not be retrieved.  It may not exist, or the server could not be contacted.");
    }

}

From source file:org.fenixedu.academic.ui.struts.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.generateReport(document).getData();

    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);// w  w  w  .  j a v  a2s  .  com
    writer.flush();
    writer.close();

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

From source file:org.ff4j.console.controller.FeaturesController.java

/**
 * Build Http response when invoking export features.
 * /*from w  ww  .  ja  v  a  2s  . co m*/
 * @param res
 *            http response
 * @throws IOException
 *             error when building response
 */
private void opExportFile(FeatureStore store, HttpServletResponse res) throws IOException {
    Map<String, Feature> features = store.readAll();
    InputStream in = new FeatureXmlParser().exportFeatures(features);
    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[4096];
        int length = 0;
        while ((in != null) && (length != -1)) {
            length = in.read(bbuf);
            sos.write(bbuf, 0, length);
        }
        log.info(features.size() + " features have been exported.");
    } finally {
        if (in != null) {
            in.close();
        }
        if (sos != null) {
            sos.flush();
            sos.close();
        }
    }
}

From source file:org.inbio.ait.web.ajax.controller.ExportCsvController.java

private ModelAndView writeReponse(HttpServletRequest request, HttpServletResponse response,
        List<Specimen> specimens) throws Exception {

    response.setCharacterEncoding("ISO-8859-1");
    response.setContentType("text/html");
    ServletOutputStream out = response.getOutputStream();

    //String documento = "";
    StringBuilder documento = new StringBuilder();
    documento.append(/*w w  w.j  av a  2s.c  om*/
            "<table class=\"contacts\" cellspacing=\"0\"><tr><th class=\"species\">Nombre cientfico</th><th class=\"species\">Longitud</th><th class=\"species\">Latitud</th><th class=\"species\"># de catlogo</th><th class=\"species\">Institucin</th>");

    for (Specimen s : specimens) {
        documento.append("<tr>");
        documento.append("<td class=\"contact\">" + s.getScientificname() + "</td>");
        documento.append("<td class=\"contact\">" + s.getDecimallongitude() + "</td>");
        documento.append("<td class=\"contact\">" + s.getDecimallatitude() + "</td>");
        documento.append("<td class=\"contact\">" + s.getCatalognumber() + "</td>");
        documento.append("<td class=\"contact\">" + s.getInstitutioncode() + "</td>");
        documento.append("<tr>");
    }
    documento.append("</table>");

    out.println(documento.toString());
    out.flush();
    out.close();

    return null;
}

From source file:biz.netcentric.cq.tools.actool.dumpservice.impl.DumpserviceImpl.java

public void returnAuthorizableDumpAsFile(final SlingHttpServletResponse response,
        Set<AuthorizableConfigBean> authorizableSet) throws IOException {
    String mimetype = "application/octet-stream";
    response.setContentType(mimetype);//from ww w .j  a  va 2s. c om
    ServletOutputStream outStream = null;
    try {
        outStream = response.getOutputStream();
    } catch (IOException e) {
        LOG.error("Exception in AuthorizableDumpUtils: {}", e);
    }

    String fileName = "Authorizable_Dump_" + new Date(System.currentTimeMillis());
    response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

    try {
        writeAuthorizableConfigToStream(authorizableSet, outStream);
    } catch (IOException e) {
        LOG.error("Exception in AuthorizableDumpUtils: {}", e);
    }
    outStream.close();
}