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.nec.harvest.security.handler.HarvestLogoutSuccessHandler.java

/**
 * Causes a logout to be completed. The method must complete successfully
 * //  w  ww .  j  a v  a 2s.  c o m
 * @param request
 * @param response
 * @param authentication
 * @throws IOException
 * @throws ServletException
 */
protected void onLogout(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
        throws IOException, ServletException {
    final HttpSession session = request.getSession();
    if (session != null) {
        // ??????????
        session.invalidate();

        // Invalidates this session then unbinds any objects bound to it
        logger.info(
                "??????????");
    }

    // Remove from LRU Cache
    AuthenticatedUserDetails.removeUserPrincipal();

    // The {} successfully logged out...
    String username = authentication != null ? authentication.getName() : "HARVEST SYSTEM";
    logger.info("The {} successfully logged out...", username);

    // Empty authentication
    SecurityContextHolder.getContext().setAuthentication(null);

    // Redirect to LOGIN
    response.setStatus(HttpServletResponse.SC_OK);
    response.setContentType(HttpServletContentType.PLAN_TEXT);
    response.sendRedirect(request.getContextPath() + "/login");
    response.flushBuffer();
}

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

public void handle(HttpServletRequest req, HttpServletResponse res)
        throws IOException, ServletException, FileUploadException {
    String nodeId = ServletUtils.getParameter(req, WebConstants.NODE_ID);

    if (StringUtils.isBlank(nodeId)) {
        ServletUtils.sendError(res, HttpServletResponse.SC_BAD_REQUEST, "Node must be specified");
        return;//from w  w w  .  ja v a 2s .  com
    } else if (!ServletFileUpload.isMultipartContent(req)) {
        ServletUtils.sendError(res, HttpServletResponse.SC_BAD_REQUEST, "We only handle multipart requests");
        return;
    } else {
        log.debug("File sync push request received from {}", nodeId);
    }

    ServletFileUpload upload = new ServletFileUpload();

    // Parse the request
    FileItemIterator iter = upload.getItemIterator(req);
    while (iter.hasNext()) {
        FileItemStream item = iter.next();
        String name = item.getFieldName();
        if (!item.isFormField()) {
            log.debug("Processing upload file field " + name + " with file name " + item.getName()
                    + " detected.");
            engine.getFileSyncService().loadFilesFromPush(nodeId, item.openStream(), res.getOutputStream());

        }
    }

    res.flushBuffer();

}

From source file:de.itsvs.cwtrpc.controller.RemoteServiceControllerServlet.java

protected void processUnexpectedFailure(HttpServletRequest request, HttpServletResponse response,
        Throwable exception) throws ServletException, IOException {
    log.error("Unexpected error while processing service request", exception);

    if (CwtRpcUtils.getRpcSessionInvalidationPolicy(request).isInvalidateOnUnexpectedException()) {
        invalidateSession(request);//w  w  w .j  ava2  s  . c  om
    }
    if (!response.isCommitted()) {
        response.reset();
        addNoCacheResponseHeaders(request, response);
        RPCServletUtils.writeResponseForUnexpectedFailure(getServletContext(), response, exception);
        /*
         * Flush all remaining output to the client (client can continue
         * immediately). Also response will be marked as being committed
         * (status may be required later by a filter).
         */
        response.flushBuffer();
    }
}

From source file:org.openmrs.module.CDAGenerator.web.controller.ExportCDAController.java

@RequestMapping(method = RequestMethod.POST)
public void manage(@RequestParam(value = "patientId", required = true) org.openmrs.Patient p,
        @RequestParam(value = "ChildCDAHandler", required = false) String ccth, BaseCdaTypeHandler bcth,
        HttpServletResponse response) {

    ClinicalDocument cda = null;/*from  www . j  av  a  2  s  .c om*/

    String[] arr = ccth.split(",");
    System.out.println("----->" + arr[0]);
    System.out.println("----->" + arr[1]);
    System.out.println("----->" + arr[2]);

    CDAGeneratorService cdaservice = (CDAGeneratorService) Context.getService(CDAGeneratorService.class);

    bcth.setDocumentFullName(arr[0]);
    bcth.setDocumentShortName(arr[1]);
    bcth.setDocumentDescription(arr[2]);
    bcth.setTemplateid(arr[3]);
    bcth.setFormatCode(arr[4]);

    cda = cdaservice.produceCDA(p, bcth);
    response.setHeader("Content-Disposition", "attachment;filename=" + p.getGivenName() + "sampleTest.xml");
    try {

        StringWriter r = new StringWriter();

        CDAUtil.save(cda, r);
        String ccdDoc = r.toString();
        ccdDoc = ccdDoc.replaceAll("&lt;", "<");
        ccdDoc = ccdDoc.replaceAll("&quot;", "\"");
        byte[] res = ccdDoc.getBytes(Charset.forName("UTF-8"));
        response.setContentType("text/xml");
        response.setCharacterEncoding("UTF-8");
        response.getOutputStream().write(res);
        response.flushBuffer();
    } catch (IOException e) {

        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

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);//from w  ww .j  a  v  a2 s  . 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:net.lightbody.bmp.proxy.jetty.jetty.servlet.ServletHandler.java

protected void handleOptions(HttpServletRequest request, HttpServletResponse response) throws IOException {
    // Handle OPTIONS request for entire server
    if ("*".equals(request.getRequestURI())) {
        // 9.2//from w w w.  j  ava  2 s.c om
        response.setIntHeader(HttpFields.__ContentLength, 0);
        response.setHeader(HttpFields.__Allow, __AllowString);
        response.flushBuffer();
    } else
        response.sendError(HttpResponse.__404_Not_Found);
}

From source file:org.nsesa.editor.gwt.an.amendments.server.service.HtmlExportService.java

@Override
public void export(final AmendmentContainerDTO object, final HttpServletResponse response) throws IOException {
    response.setContentType("text/html; charset=UTF-8");
    response.setHeader("Content-Disposition",
            "attachment;filename=" + object.getAmendmentContainerID() + ".html");
    response.setCharacterEncoding("UTF8");

    final String content = object.getBody();
    final InputSource inputSource;
    inputSource = new InputSource(new StringReader(content));

    try {/*from w w  w  . j  a  v  a2  s. co m*/
        final NodeModel model = NodeModel.parse(inputSource);
        final Configuration configuration = new Configuration();
        configuration.setDefaultEncoding("UTF-8");
        configuration.setDirectoryForTemplateLoading(template.getFile().getParentFile());
        final StringWriter sw = new StringWriter();
        Map<String, Object> root = new HashMap<String, Object>();
        root.put("amendment", model);
        root.put("editorUrl", editorUrl);
        configuration.getTemplate(template.getFile().getName()).process(root, sw);
        byte[] bytes = sw.toString().getBytes("utf-8");
        IOUtils.copy(new ByteArrayInputStream(bytes), response.getOutputStream());
        response.setContentLength(bytes.length);
        response.flushBuffer();

    } catch (IOException e) {
        throw new RuntimeException("Could not read file.", e);
    } catch (SAXException e) {
        throw new RuntimeException("Could not parse file.", e);
    } catch (ParserConfigurationException e) {
        throw new RuntimeException("Could not parse file.", e);
    } catch (TemplateException e) {
        throw new RuntimeException("Could not load template.", e);
    }
}

From source file:org.craftercms.cstudio.publishing.servlet.DeployVersionServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter serverOut = response.getWriter();
    try {/* w  w w  . ja  va  2 s  .c  o  m*/
        String target = request.getParameter(FileUploadServlet.PARAM_TARGET);
        String version = request.getParameter(PARAM_NEW_VERSION);
        if (StringUtils.isEmpty(target)) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            serverOut
                    .write("Parameter \"" + FileUploadServlet.PARAM_TARGET + "\" is need and can not be empty");
        } else if (StringUtils.isEmpty(version)) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            serverOut.write("Parameter \"" + PARAM_NEW_VERSION + "\" is need and can not be empty");
        } else {
            versioningService.writeNewVersion(version, target);
            response.setStatus(HttpServletResponse.SC_OK);
            serverOut.write(version);
        }
    } catch (VersionException ex) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        serverOut.write(ex.getMessage());
    }
    setDefaultHeaders(response);
    serverOut.flush();
    response.flushBuffer();
}

From source file:cz.zcu.kiv.eegdatabase.webservices.rest.datafile.DataFileServiceImpl.java

/**
 * Method for downloading file from server.
 *
 * @param id       data file identifier//from   ww  w .  j  av  a  2  s .c  o m
 * @param response HTTP response
 * @throws RestServiceException  error while accessing to file
 * @throws SQLException          error while reading file from db
 * @throws IOException           error while reading file
 * @throws RestNotFoundException no such file on server
 */
@Override
@Transactional(readOnly = true)
public void getFile(int id, HttpServletResponse response)
        throws RestServiceException, SQLException, IOException, RestNotFoundException {
    List<DataFile> dataFiles = experimentDao.getDataFilesWhereId(id);
    DataFile file = null;

    if (dataFiles != null && !dataFiles.isEmpty()) {
        file = dataFiles.get(0);
    }

    if (file == null)
        throw new RestNotFoundException("No file with such id!");

    //if is user member of group, then he has rights to download file
    //basic verification, in future should be extended
    ResearchGroup expGroup = file.getExperiment().getResearchGroup();
    if (!isInGroup(personDao.getLoggedPerson(), expGroup.getResearchGroupId()))
        throw new RestServiceException("User does not have access to this file!");

    // copy it to response's OutputStream
    byte[] data = file.getFileContent().getBytes(1, (int) file.getFileContent().length());
    response.setContentType(file.getMimetype());
    response.setContentLength(data.length);
    response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getFilename() + "\"");
    response.getOutputStream().write(data);
    response.flushBuffer();
}

From source file:de.itsvs.cwtrpc.controller.RemoteServiceControllerServlet.java

protected void writeResponse(HttpServletRequest request, HttpServletResponse response,
        PreparedRemoteServiceConfig serviceConfig, String payload) throws IOException {
    final boolean gzipResponse;

    gzipResponse = serviceConfig.isResponseCompressionEnabled() && RPCServletUtils.acceptsGzipEncoding(request)
            && RPCServletUtils.exceedsUncompressedContentLengthLimit(payload);

    if (log.isDebugEnabled()) {
        log.debug("Writing response (gzip=" + gzipResponse + ")");
    }/* ww  w. ja v a2 s  .c o m*/
    addNoCacheResponseHeaders(request, response);
    RPCServletUtils.writeResponse(getServletContext(), response, payload, gzipResponse);
    /*
     * Flush all remaining output to the client (client can continue
     * immediately). Also response will be marked as being committed (status
     * may be required later by a filter).
     */
    response.flushBuffer();
}