Java Code Examples for javax.servlet.http.HttpServletResponse#flushBuffer()

The following examples show how to use javax.servlet.http.HttpServletResponse#flushBuffer() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CookieUtils.java    From molicode with Apache License 2.0 6 votes vote down vote up
/**
 * 添加一条新的Cookie,可以指定过期时间(单位:秒)
 *
 * @param response
 * @param name
 * @param value
 * @param maxValue
 */
public static void setCookie(HttpServletResponse response, String name,
                             String value, int maxValue) {
    if (StringUtils.isBlank(name)) {
        return;
    }
    if (null == value) {
        value = "";
    }
    Cookie cookie = new Cookie(name, value);
    cookie.setPath("/");
    if (maxValue != 0) {
        cookie.setMaxAge(maxValue);
    } else {
        cookie.setMaxAge(COOKIE_HALF_HOUR);
    }
    response.addCookie(cookie);
    try {
        response.flushBuffer();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 2
Source File: BaseStreamingHTTPEndpoint.java    From flex-blazeds with Apache License 2.0 6 votes vote down vote up
/**
 * Helper method to write a chunk of bytes to the output stream in an HTTP
 * "Transfer-Encoding: chunked" format.
 * If the bytes array is null or empty, a terminal chunk will be written to
 * signal the end of the response.
 * Once the chunk is written to the output stream, the stream will be flushed immediately (no buffering).
 *
 * @param bytes The array of bytes to write as a chunk in the response; or if null, the signal to write the final chunk to complete the response.
 * @param os The output stream the chunk will be written to.
 * @param response The HttpServletResponse, used to flush the chunk to the client.
 *
 * @throws IOException if writing the chunk to the output stream fails.
 */
protected void streamChunk(byte[] bytes, ServletOutputStream os, HttpServletResponse response) throws IOException
{
    if ((bytes != null) && (bytes.length > 0))
    {
        byte[] chunkLength = Integer.toHexString(bytes.length).getBytes("ASCII");
        os.write(chunkLength);
        os.write(CRLF_BYTES);
        os.write(bytes);
        os.write(CRLF_BYTES);
        response.flushBuffer();
    }
    else // Send final 'EOF' chunk for the response.
    {
        os.write(ZERO_BYTE);
        os.write(CRLF_BYTES);
        response.flushBuffer();
    }
}
 
Example 3
Source File: StaticContentController.java    From teiid-spring-boot with Apache License 2.0 6 votes vote down vote up
@RequestMapping(value = {"org.apache.olingo.v1.xml", "org.teiid.v1.xml"})
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String pathInfo = request.getRequestURI();

    try {
        int idx = pathInfo.indexOf("/static");
        pathInfo = pathInfo.substring(idx+7);
        InputStream contents = getClass().getResourceAsStream(pathInfo);
        if (contents != null) {
            writeContent(response, contents);
            response.flushBuffer();
            return;
        }
        throw new TeiidProcessingException(ODataPlugin.Util.gs(ODataPlugin.Event.TEIID16055, pathInfo));
    } catch (TeiidProcessingException e) {
        writeError(request, e.getCode(), e.getMessage(), response, 404);
    }
}
 
Example 4
Source File: TestHttp11Processor.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    resp.setContentType("text/plain");
    resp.setCharacterEncoding("UTF-8");
    if (!useChunks) {
        // Longer than it needs to be because response will fail before
        // it is complete
        resp.setContentLength(100);
    }
    PrintWriter pw = resp.getWriter();
    pw.print("line01");
    pw.flush();
    resp.flushBuffer();
    pw.print("line02");
    pw.flush();
    resp.flushBuffer();
    pw.print("line03");

    // Now throw a RuntimeException to end this request
    throw new ServletException("Deliberate failure");
}
 
Example 5
Source File: ErasmusIndividualCandidacyProcessPublicDA.java    From fenixedu-academic with GNU Lesser General Public License v3.0 6 votes vote down vote up
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);
    writer.flush();
    writer.close();

    response.flushBuffer();
    return mapping.findForward("");
}
 
Example 6
Source File: DegreeChangeCandidacyProcessDA.java    From fenixedu-academic with GNU Lesser General Public License v3.0 5 votes vote down vote up
public ActionForward prepareExecutePrintCandidaciesFromExternalDegrees(ActionMapping mapping, ActionForm actionForm,
        HttpServletRequest request, HttpServletResponse response) throws IOException {

    response.setContentType("application/vnd.ms-excel");
    response.setHeader(
            "Content-disposition",
            "attachment; filename="
                    + BundleUtil.getString(Bundle.APPLICATION, "label.candidacy.degreeChange.external.report.filename")
                    + ".xls");
    writeReportForExternalDegrees(getProcess(request), response.getOutputStream());
    response.getOutputStream().flush();
    response.flushBuffer();
    return null;
}
 
Example 7
Source File: ClientUploadController.java    From qconfig with MIT License 5 votes vote down vote up
private void write(HttpServletResponse response, int code, String message) throws IOException {
    String codeValue = String.valueOf(code);
    if (code != ApiResponseCode.OK_CODE) {
        Monitor.clientUpdateFileCountInc(code);
        logger.info("client upload file failOf, code=[{}], message=[{}]", code, message);
    }

    response.setHeader(Constants.CODE, codeValue);
    response.getWriter().write(message);
    response.flushBuffer();
}
 
Example 8
Source File: SecondCycleCandidacyProcessDA.java    From fenixedu-academic with GNU Lesser General Public License v3.0 5 votes vote down vote up
public ActionForward prepareExecutePrintCandidacies(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request,
        HttpServletResponse response) throws IOException {

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

    final ServletOutputStream writer = response.getOutputStream();
    writeReport(getProcess(request), writer);
    writer.flush();
    response.flushBuffer();
    return null;
}
 
Example 9
Source File: WebMQSubscriber.java    From XRTB with Apache License 2.0 5 votes vote down vote up
public WebMQSubscriber(HttpServletResponse response, String port, String topics) {
	  // Prepare our context and subscriber
	
	
       Context context = ZMQ.context(1);
       Socket subscriber = context.socket(ZMQ.SUB);

       subscriber.connect("tcp://localhost:" + port);
       
       String [] parts = topics.split(",");
       for (String topic : parts) {
       	subscriber.subscribe(topic.getBytes());
       }

       while (!Thread.currentThread ().isInterrupted ()) {
           // Read envelope with address
           String address = subscriber.recvStr ();
           // Read message contents
           String contents = subscriber.recvStr ();
           Map m = new HashMap();
           m.put("topic", address);
           m.put("message", contents);
          
           try {
           	contents = mapper.writeValueAsString(m);
			response.getWriter().println(contents);
			response.flushBuffer();       	
		} catch (IOException e) {
			//e.printStackTrace();
			break;
		}               
       }
       subscriber.close ();
       context.term ();
}
 
Example 10
Source File: AllInOneAction.java    From java2word with MIT License 5 votes vote down vote up
public ActionForward execute(ActionMapping mapping, ActionForm form,
		HttpServletRequest request, HttpServletResponse response)
		throws Exception {
	log.info("@@@ Generating report...");

	buildReport(response);

	response.flushBuffer();

	log.info("@@@ Document has been written to the servlet response...");
	return null; //or maybe: return mapping.findForward("ok");
}
 
Example 11
Source File: TestHttp11Processor.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    resp.setStatus(HttpServletResponse.SC_OK);
    resp.setContentType("text/event-stream");
    resp.addHeader("Connection", "close");
    resp.flushBuffer();
    resp.getWriter().write("OK");
    resp.flushBuffer();
}
 
Example 12
Source File: SpecialSeasonStatusTrackerDA.java    From fenixedu-academic with GNU Lesser General Public License v3.0 5 votes vote down vote up
public ActionForward exportXLS(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws IOException {
    SpecialSeasonStatusTrackerBean bean = getRenderedObject();
    final Spreadsheet spreadsheet = generateSpreadsheet(bean);

    response.setContentType("application/vnd.ms-excel");
    response.setHeader("Content-disposition", "attachment; filename=" + getFilename(bean) + ".xls");
    spreadsheet.exportToXLSSheet(response.getOutputStream());
    response.getOutputStream().flush();
    response.flushBuffer();
    return null;
}
 
Example 13
Source File: TestCookiesDisallowEquals.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
    Cookie cookies[] = req.getCookies();
    for (Cookie cookie : cookies) {
        resp.getWriter().write(cookie.getName() + "=" +
                cookie.getValue() + "\n");
    }
    resp.flushBuffer();
}
 
Example 14
Source File: Http2TestBase.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    // Generate an empty response
    resp.setContentType("application/octet-stream");
    resp.setContentLength(0);
    resp.flushBuffer();
}
 
Example 15
Source File: SiteMapController.java    From putnami-web-toolkit with GNU Lesser General Public License v3.0 5 votes vote down vote up
@RequestMapping(value = "/sitemap.txt", method = RequestMethod.GET)
public void welcomePage(HttpServletResponse response) {
	try {
		InputStream is = new FileInputStream(sitemap);
		response.setContentType("text/plain");
		response.setContentLength((int) sitemap.length());
		IOUtils.copy(is, response.getOutputStream());
		response.flushBuffer();
	} catch (IOException ex) {
		throw new RuntimeException("IOError writing file to output stream", ex);
	}
}
 
Example 16
Source File: AccessDeniedHandlerRestImpl.java    From spring-backend-boilerplate with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(HttpServletRequest request,
				   HttpServletResponse response,
				   AccessDeniedException accessDeniedException) throws IOException, ServletException {
	logger.error("The ajax request access is denied.", accessDeniedException);
	response.setStatus(HttpServletResponse.SC_FORBIDDEN);
	response.getWriter()
			.append(String.format("{\"succeed\":false,\"message\":\"%s\"}", accessDeniedException.getMessage()));
	response.flushBuffer();
}
 
Example 17
Source File: SystemController.java    From jeecg with Apache License 2.0 4 votes vote down vote up
/**
 * 获取图片流/获取文件用于下载
 * @param response
 * @param request
 * @throws Exception
 */
@RequestMapping(value="downloadFile",method = RequestMethod.GET)
public void downloadFile(HttpServletResponse response,HttpServletRequest request) throws Exception{
	String ctxPath = request.getSession().getServletContext().getRealPath("/");
	String dbpath = request.getParameter("filePath");
	String downLoadPath = ctxPath + dbpath;

	if(UrlCheckUtil.checkUrl(downLoadPath)){
		return;
	}

	response.setContentType("application/x-msdownload;charset=utf-8");
	String fileName=dbpath.substring(dbpath.lastIndexOf("/")+1);
	String userAgent = request.getHeader("user-agent").toLowerCase();
	if (userAgent.contains("msie") || userAgent.contains("like gecko") ) {
		fileName = URLEncoder.encode(fileName, "UTF-8");
	}else {  
		fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");  
	} 
	response.setHeader("Content-disposition", "attachment; filename="+ fileName);
	InputStream inputStream = null;
	OutputStream outputStream=null;
	try {
		inputStream = new BufferedInputStream(new FileInputStream(downLoadPath));
		outputStream = response.getOutputStream();
		byte[] buf = new byte[1024];
        int len;
        while ((len = inputStream.read(buf)) > 0) {
            outputStream.write(buf, 0, len);
        }
        response.flushBuffer();
	} catch (Exception e) {
		logger.info("--通过流的方式获取文件异常--"+e.getMessage());
	}finally{
		if(inputStream!=null){
			inputStream.close();
		}
		if(outputStream!=null){
			outputStream.close();
		}
	}
}
 
Example 18
Source File: EntryPointV2Servlet.java    From qconfig with MIT License 4 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String result = getResult(req);
    resp.getWriter().write(result);
    resp.flushBuffer();
}
 
Example 19
Source File: ImageFilter.java    From yes-cart with Apache License 2.0 4 votes vote down vote up
public void handleRequestInternal(final HttpServletRequest httpServletRequest,
                                  final HttpServletResponse httpServletResponse) throws ServletException, IOException {

    final String previousToken = httpServletRequest.getHeader(IF_NONE_MATCH);
    final String currentToken = getETagValue(httpServletRequest);

    httpServletResponse.setHeader(ETAG, currentToken);

    if (currentToken.equals(previousToken) &&
            ZonedDateTime.now(
                    DateUtils.zone()
            ).isBefore(
                    DateUtils.zdtFrom(httpServletRequest.getDateHeader(IF_MODIFIED_SINCE)).plusMinutes(getEtagExpiration())
            )) {
        httpServletResponse.sendError(HttpServletResponse.SC_NOT_MODIFIED);
        // use the same date we sent when we created the ETag the first time through
        httpServletResponse.setHeader(LAST_MODIFIED, httpServletRequest.getHeader(IF_MODIFIED_SINCE));
        if (LOG.isDebugEnabled()) {
            LOG.debug("ETag the same, will return 304");
        }
    } else {

        /*
            RequestURI  -> /yes-shop/imgvault/product/image.png
            ContextPath -> /yes-shop
            ServletPath ->          /imgvault/product/image.png

            RequestURI  -> /imgvault/product/image.png
            ContextPath ->
            ServletPath -> /imgvault/product/image.png
         */

        final String requestPath = HttpUtil.decodeUtf8UriParam(httpServletRequest.getRequestURI());
        final String contextPath = httpServletRequest.getContextPath();
        final String servletPath = requestPath.substring(contextPath.length());

        httpServletResponse.setDateHeader(LAST_MODIFIED, System.currentTimeMillis());

        final String width = httpServletRequest.getParameter(Constants.WIDTH);
        final String height = httpServletRequest.getParameter(Constants.HEIGHT);


        final MediaFileNameStrategy mediaFileNameStrategy = imageService.getImageNameStrategy(servletPath);

        String code = mediaFileNameStrategy.resolveObjectCode(servletPath);  //optional product or sku code
        String locale = mediaFileNameStrategy.resolveLocale(servletPath);  //optional locale
        String originalFileName = mediaFileNameStrategy.resolveFileName(servletPath);  //here file name with prefix

        final String imageRealPathPrefix = getImageRepositoryRoot(mediaFileNameStrategy.getUrlPath());

        String absolutePathToOriginal =
                        imageRealPathPrefix +
                        mediaFileNameStrategy.resolveRelativeInternalFileNamePath(originalFileName, code, locale); //path to not resized image


        final boolean origFileExists = imageService.isImageInRepository(originalFileName, code, mediaFileNameStrategy.getUrlPath(), imageRealPathPrefix);

        if (!origFileExists) {
            code = Constants.NO_IMAGE;
            originalFileName = mediaFileNameStrategy.resolveFileName(code);  //here file name with prefix
            absolutePathToOriginal =
                    imageRealPathPrefix +
                            mediaFileNameStrategy.resolveRelativeInternalFileNamePath(originalFileName, code, locale); //path to not resized image
        }


        String absolutePathToResized = null;
        if (width != null && height != null && imageService.isSizeAllowed(width, height)) {
            absolutePathToResized =
                    imageRealPathPrefix +
                            mediaFileNameStrategy.resolveRelativeInternalFileNamePath(originalFileName, code, locale, width, height);
        }

        final byte[] imageFile = getImageFile(absolutePathToOriginal, absolutePathToResized, width, height);
        if (imageFile != null && imageFile.length > 0) {
            httpServletResponse.getOutputStream().write(imageFile);
            httpServletResponse.flushBuffer();
        } else {
            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    }
}
 
Example 20
Source File: RepositoryCheckerServlet.java    From document-management-system with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
	log.debug("doGet({}, {})", request, response);
	request.setCharacterEncoding("UTF-8");
	String repoPath = WebUtils.getString(request, "repoPath", "/" + Repository.ROOT);
	boolean fast = WebUtils.getBoolean(request, "fast");
	boolean versions = WebUtils.getBoolean(request, "versions");
	boolean checksum = WebUtils.getBoolean(request, "checksum");
	updateSessionManager(request);
	PrintWriter out = response.getWriter();
	response.setContentType(MimeTypeConfig.MIME_HTML);
	header(out, "Repository checker", breadcrumb);
	out.flush();

	try {
		if (!repoPath.equals("")) {
			out.println("<ul>");

			// Calculate number of nodes
			out.println("<li>Calculate number of nodes</li>");
			out.flush();
			response.flushBuffer();
			log.debug("Calculate number of nodes");

			ContentInfo cInfo = OKMFolder.getInstance().getContentInfo(null, repoPath);

			out.println("<li>Documents: " + cInfo.getDocuments() + "</li>");
			out.println("<li>Folders: " + cInfo.getFolders() + "</li>");
			out.println("<li>Checking repository integrity</li>");
			out.flush();
			response.flushBuffer();
			log.debug("Checking repository integrity");

			long begin = System.currentTimeMillis();
			ImpExpStats stats = null;

			if (Config.REPOSITORY_NATIVE) {
				InfoDecorator id = new HTMLInfoDecorator((int) cInfo.getDocuments());
				stats = DbRepositoryChecker.checkDocuments(null, repoPath, fast, versions, checksum, out, id);
			} else {
				// Other implementation
			}

			long end = System.currentTimeMillis();

			// Finalized
			out.println("<li>Repository check completed!</li>");
			out.println("</ul>");
			out.flush();
			log.debug("Repository check completed!");

			out.println("<hr/>");
			out.println("<div class=\"ok\">Path: " + repoPath + "</div>");
			out.println("<div class=\"ok\">Fast: " + fast + "</div>");
			out.println("<div class=\"ok\">Versions: " + versions + "</div>");

			if (Config.REPOSITORY_NATIVE && Config.REPOSITORY_CONTENT_CHECKSUM) {
				out.println("<div class=\"ok\">Checkum: " + checksum + "</div>");
			} else {
				out.println("<div class=\"warn\">Checkum: disabled</div>");
			}

			out.println("<br/>");
			out.println("<b>Documents:</b> " + stats.getDocuments() + "<br/>");
			out.println("<b>Folders:</b> " + stats.getFolders() + "<br/>");
			out.println("<b>Size:</b> " + FormatUtil.formatSize(stats.getSize()) + "<br/>");
			out.println("<b>Time:</b> " + FormatUtil.formatSeconds(end - begin) + "<br/>");

			// Activity log
			UserActivity.log(request.getRemoteUser(), "ADMIN_REPOSITORY_CHECKER", null, null, "Documents: " + stats.getDocuments()
					+ ", Folders: " + stats.getFolders() + ", Size: " + FormatUtil.formatSize(stats.getSize()) + ", Time: "
					+ FormatUtil.formatSeconds(end - begin));
		}
	} catch (Exception e) {
		log.error(e.getMessage(), e);
	} finally {
		footer(out);
		out.flush();
		out.close();
	}
}