Example usage for javax.servlet.http HttpServletResponse flushBuffer

List of usage examples for javax.servlet.http HttpServletResponse flushBuffer

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse flushBuffer.

Prototype

public void flushBuffer() throws IOException;

Source Link

Document

Forces any content in the buffer to be written to the client.

Usage

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

@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public void getFile(@PathVariable("id") int id, HttpServletResponse response) throws IOException {
    Files f = fileService.get(id);
    if (f == null) {
        response.sendError(HttpServletResponse.SC_GONE, "O arquivo solicitado no foi encontrado.");
    } else {//from www  . ja va 2s .c  om
        String fileName = f.getLocation();

        try {
            // get your file as InputStream
            InputStream is = new FileInputStream(new File(fileName));

            response.setHeader("Content-Disposition", "attachment; filename=" + f.getName());
            response.setContentType(f.getContentType());
            // copy it to response's OutputStream
            IOUtils.copy(is, response.getOutputStream());

            response.flushBuffer();

        } catch (FileNotFoundException fe) {
            response.sendError(HttpServletResponse.SC_GONE, "O arquivo solicitado no foi encontrado.");
            LOG.error("O arquivo solicitado no foi encontrado.", fe);
        } catch (IOException ex) {
            LOG.error("Error writing file to output stream. Filename was '" + fileName + "'");
            throw ex;
        }
    }
}

From source file:org.jasig.ssp.service.impl.StudentDocumentServiceImpl.java

@Override
public void downloadFile(UUID id, HttpServletResponse response)
        throws ObjectNotFoundException, FileNotFoundException, IOException {
    StudentDocument studentDocument = get(id);
    if (studentDocument == null) {
        throw new ObjectNotFoundException("could not find document with id of " + id,
                StudentDocument.class.toString());
    }/*from  w  w w.jav  a2  s . c o m*/
    File file = new File(calculateAbsoluteFileLocation(studentDocument.getFileLocation()));
    InputStream is = new FileInputStream(file);
    response.setHeader("Content-Disposition", "attachment; filename=" + studentDocument.getFileName());
    // copy it to response's OutputStream
    IOUtils.copy(is, response.getOutputStream());
    response.flushBuffer();
}

From source file:com.almende.eve.transport.http.EveServlet.java

/**
 * Handle hand shake.//from  ww  w.ja  v a  2 s. c  o  m
 * 
 * @param req
 *            the req
 * @param res
 *            the res
 * @return true, if successful
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
private boolean handleHandShake(final HttpServletRequest req, final HttpServletResponse res)
        throws IOException {
    final String time = req.getHeader("X-Eve-requestToken");

    if (time == null) {
        return false;
    }
    final String url = req.getRequestURI();
    final String id = getId(url);
    final HttpTransport transport = HttpService.get(myUrl, id);
    if (transport != null) {
        final String token = transport.getTokenstore().get(time);
        if (token == null) {
            res.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        } else {
            res.setHeader("X-Eve-replyToken", token);
            res.setStatus(HttpServletResponse.SC_OK);
            res.flushBuffer();
        }
    }
    return true;
}

From source file:org.nuxeo.ecm.platform.ui.web.auth.ntlm.NTLMAuthenticator.java

public Boolean handleLoginPrompt(HttpServletRequest httpRequest, HttpServletResponse httpResponse,
        String baseURL) {// w  ww . j a  v a2s  .  c om

    log.debug("Handle NTLM login prompt");
    NtlmPasswordAuthentication ntlm = null;
    HttpSession httpSession = httpRequest.getSession(FORCE_SESSION_CREATION);

    if (httpSession != null) {
        ntlm = (NtlmPasswordAuthentication) httpSession.getAttribute(NTLM_HTTP_AUTH_SESSION_KEY);
    }

    if (httpSession == null || ntlm == null) {
        log.debug("Sending NTLM Challenge/Response request to browser");
        httpResponse.setHeader("WWW-Authenticate", "NTLM");
        httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        httpResponse.setContentLength(0);
        try {
            httpResponse.flushBuffer();
        } catch (IOException e) {
            log.error("Error while flushing buffer:" + e.getMessage());
            e.printStackTrace();
        }
        return true;
    } else {
        log.debug("No NTLM Prompt done since NTLM Auth was found :" + ntlm.getUsername());
        return false;
    }
}

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

@RequestMapping(value = "/{id}/thumbnail", method = RequestMethod.GET)
public void getThumbnail(@PathVariable("id") Long id, HttpServletResponse response) throws IOException {

    if (id == null || id == 0) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND, "O arquivo solicitado no foi encontrado.");
    } else {//w ww .j  av  a  2 s  .c  o m
        String fileName = Config.FILE_PATH + id + "/thumbnail";

        try {
            // get your file as InputStream
            InputStream is = new FileInputStream(new File(fileName));

            response.setHeader("Content-Disposition", "attachment; filename= thumbnail" + id);
            response.setStatus(HttpServletResponse.SC_CREATED);
            // copy it to response's OutputStream
            IOUtils.copy(is, response.getOutputStream());

            response.flushBuffer();

        } catch (FileNotFoundException fe) {
            // get your file as InputStream

            InputStream is = new FileInputStream(new File(DEFAULT_THUMBNAIL_PATH));

            response.setHeader("Content-Disposition", "attachment; filename=default-thumbnail.png");
            response.setContentType(MediaType.IMAGE_PNG_VALUE);
            response.setStatus(HttpServletResponse.SC_CREATED);
            // copy it to response's OutputStream
            IOUtils.copy(is, response.getOutputStream());

            response.flushBuffer();
            LOG.error("Imagen solicitada no foi encontrada.", fe);
        } catch (IOException ex) {
            LOG.error("Error writing file to output stream. Filename was '" + fileName + "'");
            throw ex;
        }
    }
}

From source file:org.pentaho.pat.server.servlet.ExportController.java

protected ModelAndView handle(final HttpServletRequest request, final HttpServletResponse response,
        final Object command, final BindException errors) throws Exception {
    final QueryExportBean queryExportBean = (QueryExportBean) command;

    try {// w  w  w .  j ava 2 s.  c  o m
        if (OlapUtil.getCellSet(queryExportBean.getQuery()) != null) {

            byte[] resultExcel = exportExcel(queryExportBean.getQuery());
            if (resultExcel != null && resultExcel.length > 0) {
                response.setContentType("application/vnd.ms-excel"); //$NON-NLS-1$
                response.setHeader("Content-Disposition", "attachment; filename=PAT_Export.xls");
                response.setHeader("Content-Length", "" + resultExcel.length);
                response.getOutputStream().write(resultExcel);
                response.flushBuffer();

            } else {
                LOG.error("Empty Excel resultset - nothing to return");
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            }

        } else {
            LOG.error("CellSet for query ID not found :" + queryExportBean.getQuery());
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        }
    } catch (Exception e) {
        LOG.error(e.getMessage());
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    }

    return null;
}

From source file:org.wrml.server.WrmlServlet.java

void writeNotFound(final HttpServletResponse response) throws IOException {

    response.setStatus(HttpServletResponse.SC_NOT_FOUND);
    response.setContentLength(0);/*  ww w .j a  va2 s .  c  o  m*/
    response.flushBuffer();
}

From source file:org.jumpmind.symmetric.web.BatchUriHandler.java

public void handleWithCompression(HttpServletRequest req, HttpServletResponse res)
        throws IOException, ServletException {
    res.setContentType("text/plain");
    String path = req.getPathInfo();
    if (!StringUtils.isBlank(path)) {
        int batchIdStartIndex = path.lastIndexOf("/") + 1;
        String nodeIdBatchId = path.substring(batchIdStartIndex);
        if (nodeIdBatchId.contains("-")) {
            int dashIndex = nodeIdBatchId.lastIndexOf("-");
            if (dashIndex > 0) {
                String nodeId = nodeIdBatchId.substring(0, dashIndex);
                String batchId = nodeIdBatchId.substring(dashIndex + 1, nodeIdBatchId.length());
                if (!dataExtractorService.extractOnlyOutgoingBatch(nodeId, Long.parseLong(batchId),
                        res.getWriter())) {
                    ServletUtils.sendError(res, HttpServletResponse.SC_NOT_FOUND);
                } else {
                    res.flushBuffer();
                }/*from  w w w  . j  a v  a2  s.c o m*/
            } else {
                ServletUtils.sendError(res, HttpServletResponse.SC_NOT_FOUND);
            }
        } else {
            ServletUtils.sendError(res, HttpServletResponse.SC_NOT_FOUND);
        }
    } else {
        res.sendError(HttpServletResponse.SC_NOT_FOUND);
    }
}

From source file:com.nec.harvest.servlet.interceptor.BackOriginGroupInterceptor.java

@Override
@SuppressWarnings("unchecked")
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
    final User userPricipal = AuthenticatedUserDetails.getUserPrincipal();
    if (userPricipal == null || userPricipal.getOrganization() == null) {
        if (logger.isDebugEnabled()) {
            logger.debug("Please login again with right permission");
        }//w ww . j  av  a2 s . c om
        logger.info("Sorry, you don't have permission to access this url");

        // Sorry, you don't have permission to access this url. Please login again with right permission
        response.setContentType(HttpServletContentType.PLAN_TEXT);
        response.sendRedirect(request.getContextPath() + "/logout");
        response.flushBuffer();
        return false;
    }

    final HandlerMethod handlerMethod = (org.springframework.web.method.HandlerMethod) handler;
    final Object controller = handlerMethod.getBean();
    if (controller instanceof MenuController) {
        return super.preHandle(request, response, handler);
    }

    final Map<String, Object> pathVariables = (Map<String, Object>) request
            .getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);

    final String PRO_GROUP_NO = "proGNo";
    final String proGroupNo = (String) pathVariables.get(PRO_GROUP_NO);
    final boolean hasMenuGroups = menuGroupService
            .hasMenuGroupByUserRoleAndSpecificGroup(userPricipal.getUsrKbn(), proGroupNo);
    if (!hasMenuGroups) {
        logger.info("Sorry, you don't have permission to access this url");

        // Sorry, you don't have permission to access this url. Please login again with right permission
        response.setContentType(HttpServletContentType.PLAN_TEXT);
        response.sendRedirect(request.getContextPath() + "/logout");
        response.flushBuffer();
        return false;
    }

    final String ORG_CODE = "orgCode";
    final HttpSession session = request.getSession();

    // Get active original code
    String orgCode = (String) pathVariables.get(ORG_CODE);
    if (StringUtils.isNotEmpty(orgCode)) {
        final String userOrgCode = (String) session.getAttribute(Constants.SESS_ORGANIZATION_CODE);
        if (!userOrgCode.equals(orgCode)) {
            logger.info("Sorry, you don't have permission to access this url");

            // Sorry, you don't have permission to access this url. Please login again with right permission
            response.setContentType(HttpServletContentType.PLAN_TEXT);
            response.sendRedirect(request.getContextPath() + "/logout");
            response.flushBuffer();
            return false;
        }
    }

    // All of original groups
    String[] processGroupNumbers = null;
    if (controller instanceof DailyReportingProGroup) {
        processGroupNumbers = ((DailyReportingProGroup) controller).getProcessGroupNumber();
    } else if (controller instanceof MasterManagementProGroup) {
        processGroupNumbers = ((MasterManagementProGroup) controller).getProcessGroupNumber();
    } else if (controller instanceof ProfitAndLossManagementProGroup) {
        processGroupNumbers = ((ProfitAndLossManagementProGroup) controller).getProcessGroupNumber();
    }

    // If the end-user already logged in into Harvest system, but have an error occurred 
    // when trying to set some information into SESSION then we can reset again that 
    // information into SESSION
    orgCode = (String) session.getAttribute(Constants.SESS_ORGANIZATION_CODE);
    if (orgCode == null) {
        session.setAttribute(Constants.SESS_ORGANIZATION_CODE, userPricipal.getOrganization().getStrCode());
    }

    final Object businessDay = session.getAttribute(Constants.SESS_BUSINESS_DAY);
    if (businessDay == null) {
        BusinessDayService businessDayService = ContextAwareContainer.getInstance()
                .getComponent(BusinessDayService.class);
        final BusinessDay businessDate = businessDayService.findLatest();

        // 
        session.setAttribute(Constants.SESS_BUSINESS_DAY, businessDate.getEigDate());
    }

    // Granted authority of user logged-in
    final String grantedAuthority = userPricipal.getUsrKbn();
    final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    for (GrantedAuthority authority : authentication.getAuthorities()) {
        logger.info("User {} was logged-in with granted role {}", authentication.getName(),
                authority.getAuthority());
    }

    /**
     * ?
     * 
     * 1?2?3??4
     */
    logger.info(
            "Granted authority of logged user: {}, NOTE: 1?2?3??4",
            grantedAuthority);

    // 
    if (StringUtils.isNotEmpty(grantedAuthority)) {
        if (ArrayUtils.isNotEmpty(processGroupNumbers)) {
            // Trying to store the original group menu into the REQUEST
            final String processGroupNumber = processGroupNumbers[Integer.valueOf(grantedAuthority) - 1];
            request.setAttribute(Constants.SESS_ORIGINAL_GROUP, processGroupNumber);

            // 
            logger.info("Were are trying to handle the sub-menu of group {}", processGroupNumber);
        }
    }

    return super.preHandle(request, response, handler);
}

From source file:net.duckling.ddl.web.controller.UploadImgController.java

@RequestMapping
public void execute(HttpServletRequest request, HttpServletResponse response) throws IOException {
    Site site = VWBContext.findSite(request);
    FileVersion attachItem = new FileVersion();
    response.setContentType("text/xml");
    response.setCharacterEncoding("UTF-8");
    ///* w  w  w . ja  va  2 s  . c  o  m*/
    String url = request.getParameter("url");
    HttpClient client = new HttpClient();
    GetMethod getMethod = new GetMethod(url);
    String fakeReferer = getFakeReferer(url);//??
    if (fakeReferer != null) {
        String thisReferer = request.getHeader("Referer");
        if (thisReferer.contains(fakeReferer)) {//????
            response.getWriter().write(getReturnXml(site, 0, "??", attachItem));
            response.flushBuffer();
            return;
        }
        getMethod.setRequestHeader("Referer", fakeReferer);
    }
    client.executeMethod(getMethod);

    //?

    try {
        attachItem = uploadImg(getMethod, request);
    } catch (NoEnoughSpaceException e) {
        JSONObject j = new JSONObject();
        j.put("result", false);
        j.put("message", e.getMessage());
        j.put("error", e.getMessage());
        JsonUtil.writeJSONObject(response, j);
        return;
    }
    //
    response.getWriter().write("");
    response.getWriter().write(getReturnXml(site, 1, "????", attachItem));
    response.flushBuffer();
}