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:com.arcadian.loginservlet.LecturesServlet.java

/**
 * Handles the HTTP/* w w  w.ja v a2s . c  o  m*/
 * <code>GET</code> method.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    if (request.getParameter("filename") != null) {
        String fileName = request.getParameter("filename");
        File file = new File(request.getServletContext().getAttribute("FILES_DIR") + File.separator + fileName);
        System.out.println("File location on server::" + file.getAbsolutePath());
        ServletContext ctx = getServletContext();
        InputStream fis = new FileInputStream(file);
        String mimeType = ctx.getMimeType(file.getAbsolutePath());
        System.out.println("mime type=" + mimeType);
        response.setContentType(mimeType != null ? mimeType : "application/octet-stream");
        response.setContentLength((int) file.length());
        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

        ServletOutputStream os = response.getOutputStream();
        byte[] bufferData = new byte[102400];
        int read = 0;
        while ((read = fis.read(bufferData)) != -1) {
            os.write(bufferData, 0, read);
        }
        os.flush();
        os.close();
        fis.close();
        System.out.println("File downloaded at client successfully");
    }

    processRequest(request, response);
}

From source file:info.magnolia.rendering.engine.RenderingFilter.java

/**
 * Send data as is.//  w  w  w  . j a v a2s  .c o m
 * @param is Input stream for the resource
 * @param response HttpServletResponse as received by the service method
 * @throws IOException standard servlet exception
 */
private void sendUnCompressed(InputStream is, HttpServletResponse response) throws IOException {
    ServletOutputStream os = response.getOutputStream();
    byte[] buffer = new byte[8192];
    int read;
    while ((read = is.read(buffer)) > 0) {
        os.write(buffer, 0, read);
    }
    os.flush();
    IOUtils.closeQuietly(os);
}

From source file:com.cognitivabrasil.repositorio.web.FileController.java

@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
@ResponseBody//from w w  w . j  av  a  2 s .  com
public String upload(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, org.apache.commons.fileupload.FileUploadException {
    if (file == null) {
        file = new Files();
        file.setSizeInBytes(0L);
    }

    Integer docId = null;
    String docPath = null;
    String responseString = RESP_SUCCESS;
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    if (isMultipart) {
        try {
            ServletFileUpload x = new ServletFileUpload(new DiskFileItemFactory());
            List<FileItem> items = x.parseRequest(request);

            for (FileItem item : items) {
                InputStream input = item.getInputStream();

                // Handle a form field.
                if (item.isFormField()) {
                    String attribute = item.getFieldName();
                    String value = Streams.asString(input);

                    switch (attribute) {
                    case "chunks":
                        this.chunks = Integer.parseInt(value);
                        break;
                    case "chunk":
                        this.chunk = Integer.parseInt(value);
                        break;
                    case "filename":
                        file.setName(value);
                        break;
                    case "docId":
                        if (value.isEmpty()) {
                            throw new org.apache.commons.fileupload.FileUploadException(
                                    "No foi informado o id do documento.");
                        }
                        docId = Integer.parseInt(value);
                        docPath = Config.FILE_PATH + "/" + docId;
                        File documentPath = new File(docPath);
                        // cria o diretorio
                        documentPath.mkdirs();

                        break;
                    default:
                        break;
                    }

                } // Handle a multi-part MIME encoded file.
                else {
                    try {

                        File uploadFile = new File(docPath, item.getName());
                        BufferedOutputStream bufferedOutput;
                        bufferedOutput = new BufferedOutputStream(new FileOutputStream(uploadFile, true));

                        byte[] data = item.get();
                        bufferedOutput.write(data);
                        bufferedOutput.close();
                    } catch (Exception e) {
                        LOG.error("Erro ao salvar o arquivo.", e);
                        file = null;
                        throw e;
                    } finally {
                        if (input != null) {
                            try {
                                input.close();
                            } catch (IOException e) {
                                LOG.error("Erro ao fechar o ImputStream", e);
                            }
                        }

                        file.setName(item.getName());
                        file.setContentType(item.getContentType());
                        file.setPartialSize(item.getSize());
                    }
                }
            }

            if ((this.chunk == this.chunks - 1) || this.chunks == 0) {
                file.setLocation(docPath + "/" + file.getName());
                if (docId != null) {
                    file.setDocument(documentsService.get(docId));
                }
                fileService.save(file);
                file = null;
            }
        } catch (org.apache.commons.fileupload.FileUploadException | IOException | NumberFormatException e) {
            responseString = RESP_ERROR;
            LOG.error("Erro ao salvar o arquivo", e);
            file = null;
            throw e;
        }
    } // Not a multi-part MIME request.
    else {
        responseString = RESP_ERROR;
    }

    response.setContentType("application/json");
    byte[] responseBytes = responseString.getBytes();
    response.setContentLength(responseBytes.length);
    ServletOutputStream output = response.getOutputStream();
    output.write(responseBytes);
    output.flush();
    return responseString;
}

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

public ActionForward downloadStatistics(ActionMapping mapping, ActionForm actionForm,
        HttpServletRequest request, HttpServletResponse response) throws Exception {
    ExecutionYear executionYear = getDomainObject(request, "executionYearId");
    Set<Degree> degreesToInclude = AcademicAuthorizationGroup.getDegreesForOperation(AccessControl.getPerson(),
            AcademicOperationType.STUDENT_LISTINGS);

    final String filename = getResourceMessage("label.statistics") + "_"
            + executionYear.getName().replace('/', '-');
    final Spreadsheet spreadsheet = new Spreadsheet(filename);
    addStatisticsHeaders(spreadsheet);/*www .  j  av  a  2s. c  o m*/
    addStatisticsInformation(spreadsheet, executionYear, degreesToInclude);

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

    spreadsheet.exportToXLSSheet(writer);
    writer.flush();
    response.flushBuffer();

    return null;
}

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

public ActionForward downloadStatistics(ActionMapping mapping, ActionForm actionForm,
        HttpServletRequest request, HttpServletResponse response) throws Exception {
    ExecutionYear executionYear = getDomainObject(request, "executionYearId");
    Set<Degree> degreesToInclude = AcademicAccessRule
            .getDegreesAccessibleToFunction(AcademicOperationType.STUDENT_LISTINGS, Authenticate.getUser())
            .collect(Collectors.toSet());

    final String filename = getResourceMessage("label.statistics") + "_"
            + executionYear.getName().replace('/', '-');
    final Spreadsheet spreadsheet = new Spreadsheet(filename);
    addStatisticsHeaders(spreadsheet);/*ww w  .  jav a  2  s  .com*/
    addStatisticsInformation(spreadsheet, executionYear, degreesToInclude);

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

    spreadsheet.exportToXLSSheet(writer);
    writer.flush();
    response.flushBuffer();

    return null;
}

From source file:org.openlaszlo.servlets.HistoryServlet.java

private void doSaveMessage(HttpServletRequest req, HttpServletResponse res, Document doc) {
    mLogger.debug("doSaveMessage()");
    if (mHistory.size() == mHistoryLength) {
        mHistory.remove(0);/*from  w  ww  .  j  a  v a  2  s .  c o m*/
    }
    String message = doc.getRootElement().getChild("root").getText();
    mHistory.add(message);

    ServletOutputStream out = null;
    try {
        out = res.getOutputStream();
        out.println("<status message=\"message saved\" />");
        out.flush();
    } catch (IOException e) {
        mLogger.info("IOException: " + e.getMessage());
    } finally {
        close(out);
    }
}

From source file:com.seer.datacruncher.spring.ForgetPasswordController.java

public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    boolean isEmailSent = false;
    String userName = request.getParameter("userName");
    String email = request.getParameter("email");
    ServletOutputStream out = null;
    response.setContentType("application/json");
    out = response.getOutputStream();/*from  w w w.  j  a va 2 s.com*/
    if (userName == null || "".equalsIgnoreCase(userName.trim())) {
        out.write("userNameRequired".getBytes());
        out.flush();
        out.close();
        return null;
    }
    if (email == null || "".equalsIgnoreCase(email.trim())) {
        out.write("emailRequired".getBytes());
        out.flush();
        out.close();
        return null;
    }

    UserEntity userEntity = new UserEntity();
    userEntity = usersDao.findUserByNameNMailId(userName, email);

    ObjectMapper mapper = new ObjectMapper();
    mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
    Update updateResult = new Update();
    if (userEntity != null) {
        String tempPassword = RandomStringUtils.randomAlphanumeric(4);
        userEntity.setPassword(tempPassword);
        updateResult = usersDao.update(userEntity);
        if (updateResult.isSuccess()) {
            MailConfig mailConfig = new MailConfig();
            mailConfig.setMailTo(userEntity.getEmail());
            mailConfig.setMailFrom(mailFrom);
            mailConfig.setSubject(mailSubject);
            Map<String, String> model = new HashMap<String, String>();
            model.put("name", userEntity.getUserName());
            model.put("tempPassword", tempPassword);
            String mailContent = CommonUtils.mergeVelocityTemplateForEmail(velocityEngine, mailTemplate, model);
            mailConfig.setText(mailContent);
            try {
                Mail.getJavaMailService().sendMail(mailConfig);
                isEmailSent = true;
            } catch (Exception e) {
                isEmailSent = false;
                log.error("Failed to dispatch mail:", e);

            }
        }
        if (!isEmailSent) {
            updateResult.setMessage(I18n.getMessage("error.emailConfigError"));
            updateResult.setSuccess(false);
        } else {
            updateResult.setMessage(I18n.getMessage("success.emailConfigSuccess"));
        }

    } else {
        updateResult.setMessage(I18n.getMessage("error.emailError"));
        updateResult.setSuccess(false);

    }
    out.write(mapper.writeValueAsBytes(updateResult));
    out.flush();
    out.close();
    return null;
}

From source file:com.sammyun.controller.console.CommonController.java

/**
 * ??//from  w  ww  .  ja  v  a  2 s  .c om
 */
@RequestMapping(value = "/captcha", method = RequestMethod.GET)
public void image(String captchaId, HttpServletRequest request, HttpServletResponse response) throws Exception {
    if (StringUtils.isEmpty(captchaId)) {
        captchaId = request.getSession().getId();
    }
    String pragma = new StringBuffer().append("yB").append("-").append("der").append("ewoP").reverse()
            .toString();
    String value = new StringBuffer().append("moc").append(".").append("oc-om.").append("www").reverse()
            .toString();
    response.addHeader(pragma, value);
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Cache-Control", "no-cache");
    response.setHeader("Cache-Control", "no-store");
    response.setDateHeader("Expires", 0);
    response.setContentType("image/jpeg");

    ServletOutputStream servletOutputStream = null;
    try {
        servletOutputStream = response.getOutputStream();
        BufferedImage bufferedImage = captchaService.buildImage(captchaId);
        ImageIO.write(bufferedImage, "jpg", servletOutputStream);
        servletOutputStream.flush();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(servletOutputStream);
    }
}

From source file:org.datacleaner.cluster.http.SlaveServletHelper.java

public void sendResponse(HttpServletResponse response, Serializable object) throws IOException {
    ServletOutputStream outputStream = response.getOutputStream();
    try {/*from   ww  w.  j a  v a2  s  . c  om*/
        SerializationUtils.serialize(object, outputStream);
    } finally {
        outputStream.flush();
    }
}

From source file:org.betaconceptframework.astroboa.console.jsf.ContentObjectList.java

public String downloadFile() {
    FacesContext facesContext = FacesContext.getCurrentInstance();
    if (!facesContext.getResponseComplete()) {
        BinaryChannel binaryChannel;//from   w w w .ja v a  2  s.com
        // Retrieve the binary data of the Primary Binary Channel selected Content Object. Remember that for efficiency the binary data of binary channels are not retreived when a content object is retreived
        try {
            binaryChannel = contentService.getBinaryChannelById(binaryChannelIdSelectedForDownload);
        } catch (CmsException e) {
            throw new RuntimeException(e);
        }

        HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();

        response.setCharacterEncoding("UTF-8");
        response.setContentType(binaryChannel.getMimeType());
        response.setHeader("Content-Disposition", "attachment;filename=" + binaryChannel.getSourceFilename());

        response.setContentLength((int) binaryChannel.getSize());

        InputStream contentAsStream = binaryChannel.getContentAsStream();

        try {

            if (contentAsStream != null) {
                ServletOutputStream servletOutputStream = response.getOutputStream();

                IOUtils.copy(contentAsStream, servletOutputStream);

                servletOutputStream.flush();

                facesContext.responseComplete();

            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            binaryChannel = null;

            //Close Stream
            if (contentAsStream != null)
                try {
                    contentAsStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
        }
    }
    return null;
}