Example usage for javax.servlet ServletOutputStream flush

List of usage examples for javax.servlet ServletOutputStream flush

Introduction

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

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes this output stream and forces any buffered output bytes to be written out.

Usage

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 {//from   ww  w . ja v a2  s . c o m
            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:eionet.webq.web.controller.FileDownloadController.java

/**
 * Writes specified content to http response.
 *
 * @param response http response//from  www.j a va 2  s  . c  o m
 * @param data     content to be written to response
 */
private void writeToResponse(HttpServletResponse response, byte[] data) {
    ServletOutputStream output = null;
    try {
        response.setContentLength(data.length);
        boolean noCache = true;

        if (response.getContentType() != null && response.getContentType().startsWith("image")) {
            noCache = false;
        }
        if (noCache) {
            response.addHeader("Cache-control", "no-cache");
        }

        output = response.getOutputStream();
        IOUtils.write(data, output);
        output.flush();
    } catch (IOException e) {
        throw new RuntimeException("Unable to write response", e);
    } finally {
        IOUtils.closeQuietly(output);
    }
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.scientificCouncil.credits.ViewTeacherCreditsReportDispatchAction.java

public ActionForward exportGlobalToExcel(ActionMapping mapping, ActionForm actionForm,
        HttpServletRequest request, HttpServletResponse response)
        throws FenixServiceException, InvalidPeriodException, ParseException {

    final String fromExecutionYearID = request.getParameter("fromExecutionYearID");
    final String untilExecutionYearID = request.getParameter("untilExecutionYearID");
    final String departmentID = request.getParameter("departmentID");

    final ExecutionYear beginExecutionYear = FenixFramework.getDomainObject(fromExecutionYearID);
    final ExecutionYear endExecutionYear = FenixFramework.getDomainObject(untilExecutionYearID);
    final ExecutionSemester beginExecutionSemester;
    final ExecutionSemester endExecutionSemester = endExecutionYear.getExecutionSemesterFor(2);
    if (beginExecutionYear.getPreviousExecutionYear()
            .equals(ExecutionSemester.readStartExecutionSemesterForCredits().getExecutionYear())) {
        beginExecutionSemester = ExecutionSemester.readStartExecutionSemesterForCredits();
    } else {/*w  w  w. jav a2  s  .c om*/
        beginExecutionSemester = beginExecutionYear.getPreviousExecutionYear().getExecutionSemesterFor(1);
    }

    Set<Department> departments = new TreeSet<Department>(Department.COMPARATOR_BY_NAME);
    if (departmentID == null) {
        departments.addAll(rootDomainObject.getDepartmentsSet());
    } else {
        departments.add(FenixFramework.<Department>getDomainObject(departmentID));
    }

    SheetData<Department> data = new SheetData<Department>(departments) {
        @Override
        protected void makeLine(Department department) {
            addCell("Departamento", department.getRealName(), "Total");

            Map<ExecutionYear, PeriodCreditsReportDTO> departmentPeriodTotalCredits = null;
            try {
                departmentPeriodTotalCredits = ReadDepartmentTotalCreditsByPeriod
                        .run(department.getDepartmentUnit(), beginExecutionSemester, endExecutionSemester);
            } catch (ParseException e) {
                logger.error(e.getMessage(), e);
            }
            ExecutionYear lastExecutionYear = null;
            for (ExecutionYear executionYear = beginExecutionSemester.getExecutionYear(); executionYear != null
                    && executionYear.isBeforeOrEquals(endExecutionYear); executionYear = executionYear
                            .getNextExecutionYear()) {
                PeriodCreditsReportDTO periodCreditsReportDTO = departmentPeriodTotalCredits.get(executionYear);
                addCell(executionYear.getYear(), (short) 3, "Docentes Carreira", (short) 1,
                        periodCreditsReportDTO == null ? null
                                : periodCreditsReportDTO.getCareerCategoryTeacherCredits(),
                        (short) 1, Formula.SUM_FOOTER, (short) 1);
                addCell("Restantes Categorias",
                        periodCreditsReportDTO == null ? null
                                : periodCreditsReportDTO.getNotCareerCategoryTeacherCredits(),
                        Formula.SUM_FOOTER);
                addCell("Saldo Final",
                        periodCreditsReportDTO == null ? null : periodCreditsReportDTO.getCredits(),
                        Formula.SUM_FOOTER);
                lastExecutionYear = executionYear;
            }
            if (lastExecutionYear != null) {
                PeriodCreditsReportDTO periodCreditsReportDTO = departmentPeriodTotalCredits
                        .get(lastExecutionYear);
                addCell("N Docentes " + lastExecutionYear.getYear(), (short) 3, "Docentes Carreira",
                        (short) 1,
                        periodCreditsReportDTO == null ? null : periodCreditsReportDTO.getCareerTeachersSize(),
                        (short) 1, Formula.SUM_FOOTER, (short) 1);
                addCell("Restantes Categorias", periodCreditsReportDTO == null ? null
                        : periodCreditsReportDTO.getNotCareerTeachersSize(), Formula.SUM_FOOTER);
                addCell("Saldo Final",
                        periodCreditsReportDTO == null ? null : periodCreditsReportDTO.getTeachersSize(),
                        Formula.SUM_FOOTER);

                addCell("Saldo per capita " + lastExecutionYear.getYear(), (short) 3, "Docentes Carreira",
                        (short) 1,
                        periodCreditsReportDTO == null ? null
                                : periodCreditsReportDTO.getCareerTeachersBalance(),
                        (short) 1, Formula.SUM_FOOTER, (short) 1);
                addCell("Restantes Categorias", periodCreditsReportDTO == null ? null
                        : periodCreditsReportDTO.getNotCareerTeachersBalance(), Formula.SUM_FOOTER);
                addCell("Saldo Final",
                        periodCreditsReportDTO == null ? null : periodCreditsReportDTO.getBalance(),
                        Formula.SUM_FOOTER);
            }
        }
    };

    try {
        String filename = "RelatorioCreditos:" + getFileName(Calendar.getInstance().getTime());
        final ServletOutputStream writer = response.getOutputStream();
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-disposition", "attachment; filename=" + filename + ".xls");
        new SpreadsheetBuilder().addSheet("RelatorioCreditos", data).build(WorkbookExportFormat.EXCEL, writer);
        writer.flush();
        response.flushBuffer();

    } catch (IOException e) {
        throw new FenixServiceException();
    }
    return null;
}

From source file:com.ephesoft.gxt.admin.server.ExportIndexFieldDownloadServlet.java

/**
 * This API is used to process request to export the documents .
 * /*from w  w  w  .  j ava 2  s  .c  o m*/
 * @param fieldTypeList {@link List<{@link FieldType}>} selected document type list to export.
 * @param resp {@link HttpServletResponse}.
 * @return
 */
private void process(final List<FieldType> fieldTypeList, final HttpServletResponse resp) throws IOException {
    final BatchSchemaService bSService = this.getSingleBeanOfType(BatchSchemaService.class);
    final String exportSerDirPath = bSService.getBatchExportFolderLocation();

    final String zipFileName = fieldTypeList.get(0).getDocType().getName() + "_" + "FieldTypes";

    final String copiedParentFolderPath = exportSerDirPath + File.separator + zipFileName;

    final File copiedFd = createDirectory(copiedParentFolderPath);

    processExportFieldTypes(fieldTypeList, bSService, resp, zipFileName);
    resp.setContentType("application/x-zip\r\n");
    resp.setHeader("Content-Disposition", "attachment; filename=\"" + zipFileName + ZIP_EXT + "\"\r\n");
    ServletOutputStream out = null;
    ZipOutputStream zout = null;
    try {
        out = resp.getOutputStream();
        zout = new ZipOutputStream(out);
        FileUtils.zipDirectory(copiedParentFolderPath, zout, zipFileName);
        resp.setStatus(HttpServletResponse.SC_OK);
    } catch (final IOException e) {
        // Unable to create the temporary export file(s)/folder(s)
        log.error("Error occurred while creating the zip file." + e, e);
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unable to export.Please try again.");
    } finally {
        // clean up code
        if (zout != null) {
            zout.close();
        }
        if (out != null) {
            out.flush();
        }
        FileUtils.deleteDirectoryAndContentsRecursive(copiedFd);
    }
}

From source file:com.alkacon.opencms.formgenerator.CmsCaptchaField.java

/**
 * Writes a Captcha JPEG image to the servlet response output stream.
 * <p>/*from   w w  w .j  a v  a2 s .c  o m*/
 * 
 * @param cms an initialized Cms JSP action element
 * @throws IOException if something goes wrong
 */
public void writeCaptchaImage(CmsJspActionElement cms) throws IOException {

    // remove eventual session attribute containing captcha settings
    cms.getRequest().getSession().removeAttribute(SESSION_PARAM_CAPTCHASETTINGS);
    String sessionId = cms.getRequest().getSession().getId();
    Locale locale = cms.getRequestContext().getLocale();
    BufferedImage captchaImage = null;
    int maxTries = 10;
    do {
        try {
            maxTries--;
            captchaImage = ((ImageCaptchaService) CmsCaptchaServiceCache.getSharedInstance()
                    .getCaptchaService(m_captchaSettings, cms.getCmsObject())).getImageChallengeForID(sessionId,
                            locale);
        } catch (CaptchaException cex) {
            // image size is too small, increase dimensions and try it again
            if (LOG.isInfoEnabled()) {
                LOG.info(cex);
                LOG.info(Messages.get().getBundle().key(Messages.LOG_ERR_CAPTCHA_CONFIG_IMAGE_SIZE_2,
                        new Object[] { m_captchaSettings.getPresetPath(), new Integer(maxTries) }));
            }
            m_captchaSettings.setImageHeight((int) (m_captchaSettings.getImageHeight() * 1.1));
            m_captchaSettings.setImageWidth((int) (m_captchaSettings.getImageWidth() * 1.1));
            // IMPORTANT: store changed captcha settings in session, they have to be used when validating the phrase
            cms.getRequest().getSession().setAttribute(SESSION_PARAM_CAPTCHASETTINGS,
                    m_captchaSettings.clone());
        }
    } while ((captchaImage == null) && (maxTries > 0));

    ServletOutputStream out = null;
    try {
        CmsFlexController controller = CmsFlexController.getController(cms.getRequest());
        HttpServletResponse response = controller.getTopResponse();
        response.setHeader("Cache-Control", "no-store");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");

        ByteArrayOutputStream captchaImageOutput = new ByteArrayOutputStream();
        ImageIO.write(captchaImage, "jpg", captchaImageOutput);
        out = cms.getResponse().getOutputStream();
        out.write(captchaImageOutput.toByteArray());
        out.flush();
    } catch (Exception e) {
        if (LOG.isErrorEnabled()) {
            LOG.error(e.getLocalizedMessage(), e);
        }
        cms.getResponse().sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } finally {
        try {
            if (out != null) {
                out.close();
            }
        } catch (Throwable t) {
            // intentionally left blank
        }
    }
}

From source file:org.fenixedu.academic.ui.struts.action.administrativeOffice.lists.StudentListByDegreeDA.java

public ActionForward exportInfoToExcel(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request,
        HttpServletResponse response) throws FenixServiceException {

    final SearchStudentsByDegreeParametersBean searchBean = getOrCreateSearchParametersBean();
    if (searchBean == null) {
        return null;
    }/* w w w  . j  av  a2  s. c  o m*/
    final List<RegistrationWithStateForExecutionYearBean> registrations = search(searchBean);

    try {
        String filename = getResourceMessage("label.students");

        Degree degree = searchBean.getDegree();
        DegreeType degreeType = searchBean.getDegreeType();
        ExecutionYear executionYear = searchBean.getExecutionYear();
        if (degree != null) {
            filename += "_" + degree.getNameFor(executionYear).getContent().replace(' ', '_');
        } else if (degreeType != null) {
            filename += "_" + degreeType.getName().getContent().replace(' ', '_');
        }
        filename += "_" + executionYear.getYear();

        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-disposition", "attachment; filename=" + filename + ".xls");
        ServletOutputStream writer = response.getOutputStream();

        final String param = request.getParameter("extendedInfo");
        boolean extendedInfo = param != null && param.length() > 0 && Boolean.valueOf(param).booleanValue();

        exportToXls(registrations, writer, searchBean, extendedInfo);
        writer.flush();
        response.flushBuffer();
        return null;

    } catch (IOException e) {
        throw new FenixServiceException();
    }
}

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

/**
 * Build Http response when invoking export features.
 * //from ww  w .j  a  va 2s  .  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();
        }
    }
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.administrativeOffice.lists.StudentListByDegreeDA.java

public ActionForward exportInfoToExcel(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request,
        HttpServletResponse response) throws FenixServiceException {

    final SearchStudentsByDegreeParametersBean searchBean = getOrCreateSearchParametersBean();
    if (searchBean == null) {
        return null;
    }//from  w ww .ja  v  a2 s. co  m
    final List<RegistrationWithStateForExecutionYearBean> registrations = search(searchBean);

    try {
        String filename = getResourceMessage("label.students");

        Degree degree = searchBean.getDegree();
        DegreeType degreeType = searchBean.getDegreeType();
        ExecutionYear executionYear = searchBean.getExecutionYear();
        if (degree != null) {
            filename += "_" + degree.getNameFor(executionYear).getContent().replace(' ', '_');
        } else if (degreeType != null) {
            filename += "_" + degreeType.getLocalizedName().replace(' ', '_');
        }
        filename += "_" + executionYear.getYear();

        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-disposition", "attachment; filename=" + filename + ".xls");
        ServletOutputStream writer = response.getOutputStream();

        final String param = request.getParameter("extendedInfo");
        boolean extendedInfo = param != null && param.length() > 0 && Boolean.valueOf(param).booleanValue();

        exportToXls(registrations, writer, searchBean, extendedInfo);
        writer.flush();
        response.flushBuffer();
        return null;

    } catch (IOException e) {
        throw new FenixServiceException();
    }
}

From source file:com.ewcms.plugin.vote.manager.web.ResultServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    ServletOutputStream out = null;
    StringBuffer output = new StringBuffer();
    try {/*from  w  w w  .  j  av a 2 s. co  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);
            VoteFacable voteFac = (VoteFacable) wac.getBean("voteFac");

            String ipAddr = req.getRemoteAddr();

            output = voteFac.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:com.alfaariss.oa.helper.stylesheet.handler.StreamHandler.java

/**
 * @see com.alfaariss.oa.helper.stylesheet.handler.AbstractStyleSheetHandler#process(com.alfaariss.oa.api.session.ISession, javax.servlet.http.HttpServletResponse, boolean)
 *///w w w.  ja va2 s  .c  o m
public void process(ISession session, HttpServletResponse response, boolean isWireless)
        throws StyleSheetException {
    BufferedReader streamInput = null;
    ServletOutputStream responseOutputStream = null;
    try {
        String sStyleSheet = super.resolveStyleSheetLocation(session, isWireless);
        if (sStyleSheet != null) {
            URL oURL = new URL(sStyleSheet);
            streamInput = new BufferedReader(new InputStreamReader(oURL.openStream()));

            responseOutputStream = response.getOutputStream();

            String sInput = null;
            while ((sInput = streamInput.readLine()) != null) {
                sInput += "\r\n";
                responseOutputStream.write(sInput.getBytes(CHARSET));
            }
        }
    } catch (Exception e) {
        _logger.error("Could not stream stylesheet", e);
        throw new StyleSheetException(SystemErrors.ERROR_INTERNAL);
    } finally {
        try {
            if (responseOutputStream != null) {
                responseOutputStream.flush();
                responseOutputStream.close();
            }
        } catch (Exception e) {
            _logger.error("Could not close output stream", e);
        }

        try {
            if (streamInput != null)
                streamInput.close();
        } catch (Exception e) {
            _logger.error("Could not close input stream", e);
        }

    }

}