Java Code Examples for javax.servlet.ServletOutputStream#flush()

The following examples show how to use javax.servlet.ServletOutputStream#flush() . 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: DownloadEventBean.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
private void downloadExcelSpreadsheet(List<SignupMeetingWrapper> smWrappers,
		String downloadType, String fileName) {

	FacesContext fc = FacesContext.getCurrentInstance();
	ServletOutputStream out = null;
	try {
		HttpServletResponse response = (HttpServletResponse) fc.getExternalContext().getResponse();
		responseSettings(fileName, XLS_MIME_TYPE, response);
		out = response.getOutputStream();

		excelSpreadsheet(out, smWrappers, downloadType);

		out.flush();
	} catch (Exception ex) {
		log.warn("Error generating XLS spreadsheet for download event:" + ex.getMessage());
	} finally {
		if (out != null)
			closeStream(out);
	}
	fc.responseComplete();
}
 
Example 2
Source File: JeecgTemplateWordView.java    From jeasypoi with Apache License 2.0 6 votes vote down vote up
@Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
	String codedFileName = "临时文件.docx";
	if (model.containsKey(TemplateWordConstants.FILE_NAME)) {
		codedFileName = (String) model.get(TemplateWordConstants.FILE_NAME) + ".docx";
	}
	if (isIE(request)) {
		codedFileName = java.net.URLEncoder.encode(codedFileName, "UTF8");
	} else {
		codedFileName = new String(codedFileName.getBytes("UTF-8"), "ISO-8859-1");
	}
	response.setHeader("content-disposition", "attachment;filename=" + codedFileName);
	XWPFDocument document = WordExportUtil.exportWord07((String) model.get(TemplateWordConstants.URL), (Map<String, Object>) model.get(TemplateWordConstants.MAP_DATA));
	ServletOutputStream out = response.getOutputStream();
	document.write(out);
	out.flush();
}
 
Example 3
Source File: DocumentRequestsManagementDispatchAction.java    From fenixedu-academic with GNU Lesser General Public License v3.0 6 votes vote down vote up
public ActionForward downloadDocument(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request,
        HttpServletResponse response) throws IOException {
    final IDocumentRequest documentRequest = getDocumentRequest(request);
    GeneratedDocument doc = documentRequest.getLastGeneratedDocument();
    if (doc != null) {
        final ServletOutputStream writer = response.getOutputStream();
        try {
            response.setContentLength(doc.getSize().intValue());
            response.setContentType("application/pdf");
            response.addHeader("Content-Disposition", "attachment; filename=" + doc.getFilename());
            writer.write(doc.getContent());
            writer.flush();
        } finally {
            writer.close();
        }
    }
    return null;
}
 
Example 4
Source File: StaticsLegacyDispatcher.java    From olat with Apache License 2.0 6 votes vote down vote up
/**
 * Copy the contents of the file to the servlet's outputstream.
 * 
 * @param response
 * @throws IOException
 */
private void copyContent(final HttpServletResponse response, final InputStream istream) throws IOException {

    // Copy resource to output stream
    ServletOutputStream ostream = null;
    try {
        response.setBufferSize(outputBufferSize);
        ostream = response.getOutputStream();

        int len;
        final byte buffer[] = new byte[inputBufferSize];
        while ((len = istream.read(buffer)) != -1) {
            ostream.write(buffer, 0, len);
        }
    } finally {
        istream.close();
    }
    ostream.flush();
}
 
Example 5
Source File: JeecgMapExcelView.java    From easypoi with Apache License 2.0 6 votes vote down vote up
@Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,
                                       HttpServletResponse response) throws Exception {
    String codedFileName = "临时文件";
    Workbook workbook = ExcelExportUtil.exportExcel(
        (ExportParams) model.get(MapExcelConstants.PARAMS),
        (List<ExcelExportEntity>) model.get(MapExcelConstants.ENTITY_LIST),
        (Collection<? extends Map<?, ?>>) model.get(MapExcelConstants.MAP_LIST));
    if (model.containsKey(MapExcelConstants.FILE_NAME)) {
        codedFileName = (String) model.get(MapExcelConstants.FILE_NAME);
    }
    if (workbook instanceof HSSFWorkbook) {
        codedFileName += HSSF;
    } else {
        codedFileName += XSSF;
    }
    if (isIE(request)) {
        codedFileName = java.net.URLEncoder.encode(codedFileName, "UTF8");
    } else {
        codedFileName = new String(codedFileName.getBytes("UTF-8"), "ISO-8859-1");
    }
    response.setHeader("content-disposition", "attachment;filename=" + codedFileName);
    ServletOutputStream out = response.getOutputStream();
    workbook.write(out);
    out.flush();
}
 
Example 6
Source File: DownloadYsoserialPayload.java    From TrackRay with GNU General Public License v3.0 6 votes vote down vote up
@Override
public Object start() {
    try {

        FileInputStream  fis = new FileInputStream(payloadFile);
        byte[] b = new byte[fis.available()];
        fis.read(b);
        ServletOutputStream out =response.getOutputStream();
        out.write(b);
        out.flush();
        out.close();

    } catch (Exception e) {
        SysLog.error(e);
    }

    return null;
}
 
Example 7
Source File: ProarcHTTPServlet.java    From proarc with GNU General Public License v3.0 6 votes vote down vote up
/**
 * The login post method.
 */
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    String username = req.getParameter("j_username");
    String password = req.getParameter("j_password");
    String code = req.getParameter("j_code");
    Map<String, String> loginProperties = new HashMap<String, String>();
    {
        loginProperties.put(Authenticator.LOGINNAME, username);
        loginProperties.put(Authenticator.PASSWORD, password);
        loginProperties.put(DESAAuthenticator.KOD_PUVODCE, code);
    }
    
    ProarcPrincipal proarcPrincipal = new ProarcPrincipal(username);
    ServletOutputStream outputStream = resp.getOutputStream();
    ChainAuthenticator chain = new ChainAuthenticator(Authenticators.getInstance().getAuthenticators());
    if (chain.authenticate(loginProperties, req, resp, proarcPrincipal)) {
        // store principal to session    
        req.getSession(true).setAttribute(ProarcAuthFilter.SESSION_KEY,proarcPrincipal);
        AuthUtils.setLoginSuccesResponse(resp);
    } else {
        AuthUtils.setLoginRequiredResponse(resp);
    }
    outputStream.flush();
}
 
Example 8
Source File: PowerUpDownload.java    From TrackRay with GNU General Public License v3.0 6 votes vote down vote up
@Override
public String start()
{
    try {
        FileInputStream  fis = new FileInputStream(new File(PATH));
        byte[] b = new byte[fis.available()];
        fis.read(b);
        ServletOutputStream out = response.getOutputStream();
        //输出
        out.write(b);
        out.flush();
        out.close();
    } catch (IOException e) {
        SysLog.error(e.getMessage());
    }
    return "";
}
 
Example 9
Source File: UpdateTrustRelationshipAction.java    From oxTrust with MIT License 6 votes vote down vote up
public boolean generateSp() throws IOException {
	FacesContext facesContext = FacesContext.getCurrentInstance();
	try {
		this.trustRelationship.setInum(trustService.generateInumForNewTrustRelationship());
		String cert = getCertForGeneratedSP();
		String spMetadataFileName = this.trustRelationship.getSpMetaDataFN();
		if (StringHelper.isEmpty(spMetadataFileName)) {
			spMetadataFileName = shibboleth3ConfService.getSpNewMetadataFileName(trustRelationship);
			trustRelationship.setSpMetaDataFN(spMetadataFileName);
		}
		String spMetadataFileContent = shibboleth3ConfService.generateSpMetadataFileContent(trustRelationship,
				cert);
		HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();
		response.setContentType("application/xml");
		response.setHeader("Content-Disposition", "attachment;filename=" + spMetadataFileName);
		ServletOutputStream os = response.getOutputStream();
		os.write(spMetadataFileContent.getBytes());
		os.flush();
		os.close();
		facesContext.responseComplete();
	} catch (IOException e) {
		e.printStackTrace();
	}
	facesContext.responseComplete();
	return true;
}
 
Example 10
Source File: StudentsListByCurricularCourseDA.java    From fenixedu-academic with GNU Lesser General Public License v3.0 6 votes vote down vote up
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);
    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;
}
 
Example 11
Source File: ZipUtils.java    From fenixedu-academic with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void createAndFlushArchive(Set<AcademicServiceRequest> requestsToZip, HttpServletResponse response,
        RectorateSubmissionBatch batch) {
    try {
        Set<String> usedNames = new HashSet<String>();
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(bout);
        for (AcademicServiceRequest document : requestsToZip) {
            String filename = document.getLastGeneratedDocument().getFilename();
            if (usedNames.contains(filename)) {
                filename = filename + "_1";
            }
            usedNames.add(filename);
            zip.putNextEntry(new ZipEntry(filename));
            zip.write(document.getLastGeneratedDocument().getContent());
            zip.closeEntry();
        }
        zip.close();
        response.setContentType("application/zip");
        response.addHeader("Content-Disposition", "attachment; filename=documentos-" + batch.getRange() + ".zip");
        ServletOutputStream writer = response.getOutputStream();
        writer.write(bout.toByteArray());
        writer.flush();
        writer.close();
        response.flushBuffer();

    } catch (IOException e) {
        throw new DomainException("error.rectorateSubmission.errorGeneratingMetadata", e);
    }
}
 
Example 12
Source File: TestHttpClient.java    From nifi with Apache License 2.0 5 votes vote down vote up
private static void respondWithText(HttpServletResponse resp, String result, int statusCode) throws IOException {
    resp.setContentType("text/plain");
    resp.setStatus(statusCode);
    final ServletOutputStream out = resp.getOutputStream();
    out.write(result.getBytes());
    out.flush();
}
 
Example 13
Source File: AtlasAPIV2ServerEmulator.java    From nifi with Apache License 2.0 5 votes vote down vote up
private static void respondWithJson(HttpServletResponse resp, Object entity, int statusCode) throws IOException {
    resp.setContentType("application/json");
    resp.setStatus(statusCode);
    final ServletOutputStream out = resp.getOutputStream();
    new ObjectMapper().writer().writeValue(out, entity);
    out.flush();
}
 
Example 14
Source File: LoginController.java    From dpCms with Apache License 2.0 5 votes vote down vote up
/**
 * 获取登录的图片验证码
 */
@RequestMapping(value = "/imgcode", method = RequestMethod.GET)
public void captcha(HttpServletRequest request, HttpServletResponse response )
		throws ServletException, IOException {
	Subject currentUser = SecurityUtils.getSubject();
	Session session = currentUser.getSession();
	Producer captchaProducer = KaptchaProducerAgency.getKaptchaProducerExample();
	response.setDateHeader("Expires", 0);
	// Set standard HTTP/1.1 no-cache headers.
	response.setHeader("Cache-Control",
			"no-store, no-cache, must-revalidate");
	// Set IE extended HTTP/1.1 no-cache headers (use addHeader).
	response.addHeader("Cache-Control", "post-check=0, pre-check=0");
	// Set standard HTTP/1.0 no-cache header.
	response.setHeader("Pragma", "no-cache");
	// return a jpeg
	response.setContentType("image/jpeg");
	// create the text for the image
	String capText = captchaProducer.createText();
	log.debug("******************验证码是: " + capText + "******************");
	// store the text in the session
	session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText	);
	// create the image with the text
	BufferedImage bi = captchaProducer.createImage(capText);
	ServletOutputStream out = response.getOutputStream();
	// write the data out
	ImageIO.write(bi, "jpg", out);
	try {
		out.flush();
	} finally {
		out.close();
	}
}
 
Example 15
Source File: WebUtils.java    From document-management-system with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Send file to client browser.
 *
 * @throws IOException If there is a communication error.
 */
public static void sendFile(HttpServletRequest request, HttpServletResponse response,
                            String fileName, String mimeType, boolean inline, File input) throws IOException {
	log.debug("sendFile({}, {}, {}, {}, {}, {})", new Object[]{request, response, fileName, mimeType, inline, input});
	prepareSendFile(request, response, fileName, mimeType, inline);

	// Set length
	response.setContentLength((int) input.length());
	log.debug("File: {}, Length: {}", fileName, input.length());

	ServletOutputStream sos = response.getOutputStream();
	FileUtils.copy(input, sos);
	sos.flush();
	sos.close();
}
 
Example 16
Source File: CaptchaAction.java    From bbs with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * 生成验证码
 * @param model
 * @param captchaKey 验证码Key
 * @param request
 * @param response
 * @return
 * @throws Exception
 */
@RequestMapping(value="/captcha/{captchaKey}", method=RequestMethod.GET)
public String execute(ModelMap model,@PathVariable String captchaKey,
		HttpServletRequest request, HttpServletResponse response) throws Exception {
	response.setDateHeader("Expires", 0);   
       // Set standard HTTP/1.1 no-cache headers.   
       response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");   
       // Set IE extended HTTP/1.1 no-cache headers (use addHeader).   
       response.addHeader("Cache-Control", "post-check=0, pre-check=0");   
       // Set standard HTTP/1.0 no-cache header.   
       response.setHeader("Pragma", "no-cache");   
       // return a jpeg   
       response.setContentType("image/jpeg"); 
       // create the text for the image  

       //使用指定的字符生成4位长度的随机字符串
       String capText = RandomStringUtils.random(4, character);
   //    String capText = RandomStringUtils.random(4, new char[]{'a','b','c','d','e','f'});


       if(captchaKey != null && !"".equals(captchaKey.trim())){
       	//统计每分钟原来提交次数
		Integer quantity = settingManage.getSubmitQuantity("captcha", captchaKey.trim());
       	if(quantity != null && quantity >60){//如果每分钟提交超过60次,则不再生成验证码
       		capText = "";
       	}
       	
       	
       	//根据key删除验证码
           captchaManage.captcha_delete(captchaKey.trim());
           //根据key生成验证码
           captchaManage.captcha_generate(captchaKey.trim(),capText);
           //创建带有文本的图像
           BufferedImage bi = captchaProducer.createImage(capText);   
           ServletOutputStream out = response.getOutputStream();   
           //输出数据  
           ImageIO.write(bi, "jpg", out);   
           try {   
               out.flush();   
           } finally {   
               out.close();   
           } 
       }
   
       
         
       return null;   

}
 
Example 17
Source File: EvaluationMethodControlDA.java    From fenixedu-academic with GNU Lesser General Public License v3.0 4 votes vote down vote up
public ActionForward export(HttpServletRequest request, HttpServletResponse response, final MethodInvoker methodInvoker)
        throws FenixServiceException {

    final ExecutionCourseWithNoEvaluationMethodSearchBean executionCourseWithNoEvaluationMethodSearchBean =
            getSearchBean(request);

    try {
        String filename = "ControloMetodosAvaliacao:" + new DateTime().toString("yyyyMMddHHmm");
        response.setContentType("text/plain");
        response.setHeader("Content-disposition", "attachment; filename=" + filename + methodInvoker.getExtension());

        ServletOutputStream writer = response.getOutputStream();

        final Spreadsheet spreadsheet = new Spreadsheet("ControloMetodosAvaliacao");
        for (final ExecutionCourse executionCourse : (Set<ExecutionCourse>) executionCourseWithNoEvaluationMethodSearchBean
                .getSearchResult()) {
            final Row row = spreadsheet.addRow();
            row.setCell(executionCourse.getNome());
            final StringBuilder degrees = new StringBuilder();
            for (final Degree degree : executionCourse.getDegreesSortedByDegreeName()) {
                if (degrees.length() > 0) {
                    degrees.append(", ");
                }
                degrees.append(degree.getSigla());
            }
            row.setCell(degrees.toString());
            final StringBuilder responsibleTeachers = new StringBuilder();
            final StringBuilder otherTeachers = new StringBuilder();
            for (final Professorship professorship : executionCourse.getProfessorshipsSet()) {
                final Person person = professorship.getPerson();
                if (professorship.isResponsibleFor()) {
                    if (responsibleTeachers.length() > 0) {
                        responsibleTeachers.append(", ");
                    }
                    responsibleTeachers.append(person.getName());
                    responsibleTeachers.append(" (");
                    responsibleTeachers.append(person.getEmail());
                    responsibleTeachers.append(" )");
                } else {
                    if (otherTeachers.length() > 0) {
                        otherTeachers.append(", ");
                    }
                    otherTeachers.append(person.getName());
                    otherTeachers.append(" (");
                    otherTeachers.append(person.getEmail());
                    otherTeachers.append(" )");
                }
            }
            row.setCell(responsibleTeachers.toString());
            row.setCell(otherTeachers.toString());
            final StringBuilder departments = new StringBuilder();
            for (final Department department : executionCourse.getDepartments()) {
                if (departments.length() > 0) {
                    departments.append(", ");
                }
                departments.append(department.getName());
            }
            row.setCell(departments.toString());
        }
        methodInvoker.export(spreadsheet, writer);

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

    } catch (IOException e) {
        throw new FenixServiceException();
    }
    return null;
}
 
Example 18
Source File: VerificationCodeUtil.java    From roncoo-education with MIT License 4 votes vote down vote up
public static String create(HttpServletRequest request, HttpServletResponse response) throws IOException {
	// 定义输出格式
	response.setContentType("image/jpeg");
	ServletOutputStream out = response.getOutputStream();
	// 准备缓冲图像,不支持表单
	BufferedImage bimg = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
	Random r = new Random();
	// 获取图形上下文环境
	Graphics gc = bimg.getGraphics();
	// 设定背景色并进行填充
	gc.setColor(getRandColor(200, 250));
	gc.fillRect(0, 0, width, height);
	// 设置图形上下文环境字体
	gc.setFont(new Font("Times New Roman", Font.PLAIN, 18));
	// 随机产生200条干扰线条,使图像中的认证码不易被其他分析程序探测到
	gc.setColor(getRandColor(160, 200));
	for (int i = 0; i < 200; i++) {
		int x1 = r.nextInt(width);
		int y1 = r.nextInt(height);
		int x2 = r.nextInt(15);
		int y2 = r.nextInt(15);
		gc.drawLine(x1, y1, x1 + x2, y1 + y2);
	}
	// 随机产生100个干扰点,使图像中的验证码不易被其他分析程序探测到
	gc.setColor(getRandColor(120, 240));
	for (int i = 0; i < 100; i++) {
		int x = r.nextInt(width);
		int y = r.nextInt(height);
		gc.drawOval(x, y, 0, 0);
	}

	// 随机产生4个数字的验证码
	String rs = "";
	String rn = "";
	for (int i = 0; i < 4; i++) {
		rn = String.valueOf(r.nextInt(10));
		rs += rn;
		gc.setColor(new Color(20 + r.nextInt(110), 20 + r.nextInt(110), 20 + r.nextInt(110)));
		gc.drawString(rn, 13 * i + 1, 16);
	}

	// 释放图形上下文环境
	gc.dispose();
	request.getSession().setAttribute("randomCode", rs);
	ImageIO.write(bimg, "jpeg", out);
	out.flush();
	out.close();
	return rs;
}
 
Example 19
Source File: TransportSegment.java    From red5-hls-plugin with Apache License 2.0 4 votes vote down vote up
/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	log.debug("Segment requested");
	// get red5 context and segmenter
	if (service == null) {
		ApplicationContext appCtx = (ApplicationContext) getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
		service = (SegmenterService) appCtx.getBean("segmenter.service");
	}
	//get the requested stream / segment
	String servletPath = request.getServletPath();
	String[] path = servletPath.split("\\.");
	log.trace("Path parts: {}", path.length);
	//fail if they request the same segment
	HttpSession session = ((HttpServletRequest) request).getSession(false);
	if (session != null) {
		String stream = (String) session.getAttribute("stream");
		if (path[0].equals(stream)) {
			log.info("Segment {} was already played by this requester", stream);
			return;
		}
		session.setAttribute("stream", path[0]);
	}		
	// look for underscore char
	int digitIndex = path[0].lastIndexOf('_') + 1;
	String streamName = path[0].substring(1, digitIndex - 1);
	int sequenceNumber = Integer.valueOf(path[0].substring(digitIndex));	
	log.debug("Stream name: {} sequence: {}", streamName, sequenceNumber);
	if (service.isAvailable(streamName)) {
		response.setContentType("video/MP2T");
		Segment segment = service.getSegment(streamName, sequenceNumber);
		if (segment != null) {
   			byte[] buf = new byte[188];
   			ByteBuffer buffer = ByteBuffer.allocate(188);
			ServletOutputStream sos = response.getOutputStream();
   			do {
   				buffer = segment.read(buffer);
   				//log.trace("Limit - position: {}", (buffer.limit() - buffer.position()));
   				if ((buffer.limit() - buffer.position()) == 188) {
   					buffer.get(buf);
   					//write down the output stream
   					sos.write(buf);
   				} else {
   					log.info("Segment result has indicated a problem");
   					// verifies the currently requested stream segment number against the  currently active segment
   					if (service.getSegment(streamName, sequenceNumber) == null) {
   						log.debug("Requested segment is no longer available");
   						break;
   					}
   				}
   				buffer.clear();
   			} while (segment.hasMoreData());
   			log.trace("Segment {} had no more data", segment.getIndex());
   			buffer = null;
   			// flush
   			sos.flush();
   			// segment had no more data
   			segment.cleanupThreadLocal();
		} else {
			log.info("Segment for {} was not found", streamName);
		}
	} else {
		//TODO let requester know that stream segment is not available
		response.sendError(404, "Segment not found");
	}
	
}
 
Example 20
Source File: OAuthHttpServiceImpl.java    From sakai with Educational Community License v2.0 3 votes vote down vote up
/**
 * Sends a response respecting the OAuth format.
 * <p>
 * The content type of the response is "application/x-www-form-urlencoded"
 * </p>
 *
 * @param response   HttpServletResponse used to send the response
 * @param parameters List of parameters in the form of key/value
 * @throws IOException
 */
private static void sendOAuthResponse(HttpServletResponse response, List<OAuth.Parameter> parameters)
        throws IOException {
    response.setContentType(OAuth.FORM_ENCODED);
    ServletOutputStream os = response.getOutputStream();
    OAuth.formEncode(parameters, os);
    os.flush();
    os.close();
}