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

The following examples show how to use javax.servlet.ServletOutputStream#close() . 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: 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 2
Source File: LoginController.java    From spring-security with Apache License 2.0 6 votes vote down vote up
@RequestMapping("/getVerifyCode")
public void getVerifyCode(HttpServletRequest request, HttpServletResponse response){
    Map<String, Object> map = VerifyCodeUtil.getVerifyCode();
    HttpSession session = request.getSession();
    session.setAttribute(VerifyCodeUtil.SESSION_KEY, map.get(VerifyCodeUtil.SESSION_KEY));
    // 禁止图像缓存。
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Cache-Control", "no-cache");
    response.setDateHeader("Expires", 0);
    response.setContentType("image/jpeg");
    // 将图像输出到Servlet输出流中。
    try {
        ServletOutputStream sos = response.getOutputStream();
        ImageIO.write((RenderedImage) map.get(VerifyCodeUtil.BUFFIMG_KEY), "jpeg", sos);
        sos.close();
        //设置验证码过期时间
        VerifyCodeUtil.removeAttrbute(session);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 3
Source File: LoginController.java    From spring-security with Apache License 2.0 6 votes vote down vote up
@RequestMapping("/getVerifyCode")
public void getVerifyCode(HttpServletRequest request, HttpServletResponse response){
    Map<String, Object> map = VerifyCodeUtil.getVerifyCode();
    HttpSession session = request.getSession();
    session.setAttribute(VerifyCodeUtil.SESSION_KEY, map.get(VerifyCodeUtil.SESSION_KEY));
    // 禁止图像缓存。
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Cache-Control", "no-cache");
    response.setDateHeader("Expires", 0);
    response.setContentType("image/jpeg");
    // 将图像输出到Servlet输出流中。
    try {
        ServletOutputStream sos = response.getOutputStream();
        ImageIO.write((RenderedImage) map.get(VerifyCodeUtil.BUFFIMG_KEY), "jpeg", sos);
        sos.close();
        //设置验证码过期时间
        VerifyCodeUtil.removeAttrbute(session);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 4
Source File: InfocardOPController.java    From openid4java with Apache License 2.0 6 votes vote down vote up
private ModelAndView directError(HttpServletResponse httpResp,
                                 String response, boolean compat)
{
    if (DEBUG) _log.debug("Sending direct response:\n" + response);

    try
    {
        DirectError err = DirectError.createDirectError(response, compat);

        ServletOutputStream os = httpResp.getOutputStream();
        os.write(err.keyValueFormEncoding().getBytes());
        os.close();
    }
    catch (IOException e)
    {
        _log.error("Error generating direct error response", e);
    }

    return null;
}
 
Example 5
Source File: CaptchaImageCreateController.java    From MultimediaDesktop with Apache License 2.0 6 votes vote down vote up
@RequestMapping("/captchaImage.djpg")
public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws IOException{
	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();  
       // store the text in the session  
       request.getSession().setAttribute(com.google.code.kaptcha.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 6
Source File: ErasmusIndividualCandidacyProcessPublicDA.java    From fenixedu-academic with GNU Lesser General Public License v3.0 6 votes vote down vote up
public ActionForward retrieveApprovedLearningAgreement(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    final ApprovedLearningAgreementDocumentFile file = getDomainObject(request, "agreementId");
    final String hash = request.getParameter("hash");

    final MobilityIndividualApplicationProcess process = file.getProcess();
    final DegreeOfficePublicCandidacyHashCode candidacyHashCode = process.getCandidacyHashCode();
    if (candidacyHashCode.getValue().equals(hash)) {
        final byte[] content = file.getContent();
        response.setContentLength(content.length);
        response.setContentType("application/pdf");
        response.addHeader("Content-Disposition", "attachment; filename=" + file.getFilename());

        final ServletOutputStream writer = response.getOutputStream();
        writer.write(content);
        writer.flush();
        writer.close();

        response.flushBuffer();
    }

    return null;
}
 
Example 7
Source File: KaptchaImageController.java    From Spring-MVC-Blueprints with MIT License 6 votes vote down vote up
@RequestMapping("/captcha/kaptcha-image.do")
public ModelAndView handleRequest(HttpServletRequest request,
		HttpServletResponse response) throws Exception {

   	// Header Preparation for Image creation 
	response.setDateHeader("Expires", 0);
	response.setHeader("Cache-Control",	"no-store, no-cache, must-revalidate");
	response.addHeader("Cache-Control", "post-check=0, pre-check=0");
	response.setHeader("Pragma", "no-cache");
	response.setContentType("image/jpeg");

	// Generation of Captcha Text
	String capText = captchaProducer.createText();
	request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
			
	// Generation of the image
	BufferedImage bi = captchaProducer.createImage(capText);
	ServletOutputStream out = response.getOutputStream();
	ImageIO.write(bi, "jpg", out);
	try {
		out.flush();
	} finally {
		out.close();
	}
	return null;
}
 
Example 8
Source File: SPARQLServletTest.java    From cumulusrdf with Apache License 2.0 5 votes vote down vote up
/**
 * SELECT queries with several supported formats.
 * 
 * @throws Exception never, otherwise test fails.
 */
@Test
public void validSelectQueriesWithAcceptParam() throws Exception {

	for (final String query : _sparql_select) {

		for (final String accept : _accept_select_header) {

			final File tmp = tmpFile();
			final ServletOutputStream servletOutputStream = new StubServletOutputStream(tmp);

			final HttpServletRequest request = mock(HttpServletRequest.class);
			when(request.getParameter(Parameters.QUERY)).thenReturn(query);
			when(request.getParameter(Parameters.ACCEPT)).thenReturn(accept);
			when(request.getMethod()).thenReturn(Methods.POST);

			final HttpServletResponse response = mock(HttpServletResponse.class);
			when(response.getOutputStream()).thenReturn(servletOutputStream);

			_classUnderTest.service(request, response);
			servletOutputStream.close();

			final TupleQueryResult res = QueryResultIO.parse(new FileInputStream(tmp), TupleQueryResultFormat.forMIMEType(accept));
			assertTrue("query: " + query + ", accept: " + accept, _queries2count.get(query) > 0 ? res.hasNext() : !res.hasNext());
		}
	}
}
 
Example 9
Source File: OpenIDHandler.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Send a direct response to the RP.
 *
 * @param httpResp HttpServletResponse
 * @param response Response message
 * @return
 * @throws IOException
 */
private void directResponse(HttpServletResponse httpResp, String response) throws IOException {
    ServletOutputStream stream = null;
    try {
        stream = httpResp.getOutputStream();
        stream.write(response.getBytes());
    } finally {
        if (stream != null) {
            stream.close();
        }
    }
}
 
Example 10
Source File: CompressionFilterTestServlet.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {

    ServletOutputStream out = response.getOutputStream();
    response.setContentType("text/plain");

    Enumeration<String> e = request.getHeaders("Accept-Encoding");
    while (e.hasMoreElements()) {
        String name = e.nextElement();
        out.println(name);
        if (name.indexOf("gzip") != -1) {
            out.println("gzip supported -- able to compress");
        }
        else {
            out.println("gzip not supported");
        }
    }


    out.println("Compression Filter Test Servlet");
    out.println("Minimum content length for compression is 128 bytes");
    out.println("**********  32 bytes  **********");
    out.println("**********  32 bytes  **********");
    out.println("**********  32 bytes  **********");
    out.println("**********  32 bytes  **********");
    out.close();
}
 
Example 11
Source File: QrCodeController.java    From SpringBoot-Home with Apache License 2.0 5 votes vote down vote up
/**
 * 生成 普通二维码
 */
@GetMapping(value = "/getCommonQRCode")
public void getCommonQRCode(HttpServletResponse response, String url) throws Exception {
    ServletOutputStream stream = null;
    try {
        stream = response.getOutputStream();
        //使用工具类生成二维码
        QrCodeUtil.encode(url, stream);
    } finally {
        if (stream != null) {
            stream.flush();
            stream.close();
        }
    }
}
 
Example 12
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 13
Source File: CustomPage.java    From appstatus with Apache License 2.0 5 votes vote down vote up
public void doGet(StatusWebHandler webHandler, HttpServletRequest req, HttpServletResponse resp)
		throws UnsupportedEncodingException, IOException {
	setup(resp, "text/html");

	ServletOutputStream os = resp.getOutputStream();
	Map<String, String> valuesMap = new HashMap<String, String>();
	valuesMap.put("content", "Hello");
	os.write(getPage(webHandler, valuesMap).getBytes("UTF-8"));
	os.close();
}
 
Example 14
Source File: SignupUIBaseBean.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * Send a warning message to user about failed ICS file generation
 * @param fileName
 * @param warningMsg
 */
protected void sendDownloadWarning(String fileName, String warningMsg) {

	FacesContext fc = FacesContext.getCurrentInstance();
	ServletOutputStream out = null;
	
	
	try {
		HttpServletResponse response = (HttpServletResponse) fc.getExternalContext().getResponse();
		
		response.reset();
		response.setHeader("Pragma", "public");
		response.setHeader("Cache-Control","public, must-revalidate, post-check=0, pre-check=0, max-age=0"); 
		response.setContentType("text/plain");
		response.setHeader("Content-disposition", "attachment; filename=" + fileName);
		
		out = response.getOutputStream();
		warningMsg= warningMsg!=null? warningMsg:"Missing Scheduler tool on site";
		out.print(warningMsg);

		out.flush();
	} catch (IOException ex) {
		log.warn("Error generating file for download:" + ex.getMessage());
	} finally {
		try{
			if(out != null) {
				out.close();
			}
		}catch (Exception e){
			//do nothing;
		}
	}
	fc.responseComplete();
	
}
 
Example 15
Source File: ImageUtil.java    From imageServer with Apache License 2.0 5 votes vote down vote up
/**
 * response写出图片
 *
 * 若发生异常则写出默认图片
 *
 * @param fileType .jpg .gif .png
 * @param imagePath
 * @param servletOutputStream
 * @throws IOException
 */
public void writeImage(String fileType, String imagePath, ServletOutputStream servletOutputStream) throws IOException {
    try {
        BufferedImage image = ImageIO.read(new File(imagePath));
        imageWrite(fileType,image,servletOutputStream);
    } catch (Exception e) {
        ImageIO.write(getNoImage(), "JPEP", servletOutputStream);
    } finally {
        servletOutputStream.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: FileDownload.java    From SI with BSD 2-Clause "Simplified" License 4 votes vote down vote up
/**
     * 파일 다운로드를 실행한다
     * @param fileName 풀패스의 파일이름(절대경로)
     * @param downName 다운로드할 설정된 파일이름
     * @throws Exception
     */
	public void download(String fileName, String downName, HttpServletRequest req) throws Exception{
		this.filename = fileName;
		byte[] buffer = new byte[1024];
		int byteData = 0;
		int offset = 0;

        try{
            //파일의 최대길이
//            int maxLength = ConfigMng.getValueInt(IPropertyKey.MAX_FILE_NAME_LENGTH);
//            String tempName = StringUtil.toFileTruncate(downName, maxLength, "");

            //파일이름으로 헤더를 설정한다
//            res.setHeader("Content-Disposition", "attachment; filename=" + LangUtil.encode(tempName));
        	try {
        		//UTF-8로 수정한 이유는 일본어 웹에서 파일을 다운로드할때 파일명이 제대로 나오지 않아서.. (11/11/22 김동준)
//        		downName = new String(downName.getBytes("MS949"), "ISO-8859-1");
            	if(req.getHeader("User-Agent").contains("MSIE")) {
//            		downName = new String(downName.getBytes("MS949"), "ISO-8859-1");
            		downName = URLEncoder.encode(downName, "UTF-8".replace("\\+", "%20"));
            	//}else if(req.getHeader("User-Agent").contains("Mozilla")) {
            	}else{
            		downName = "\"" + new String(downName.getBytes("UTF-8"), "ISO-8859-1") +  "\"";
            	}
        		//한국어 되는것
//        		downName = new String(downName.getBytes("UTF-8"), "UTF-8");
        		//japan -> english
        		//String result = new String(ori.getBytes("ISO-8859-1"), "SHIFT_JIS");
        		//english -> japan
        		//String result = new String(ori.getBytes("SHIFT_JIS"), "ISO-8859-1");
        		//downName = new String(downName.getBytes(ConfigMng.getValue(IPropertyKey.ENCODE)), "UTF-8");
            } catch (UnsupportedEncodingException e) {

            }
        	res.setHeader("Content-Type", "application/octet-stream;");
            res.setHeader("Content-Disposition", "attachment; filename=" + downName + ";");
            res.setHeader("Content-Transfer-Encoding", "binary");
            res.setHeader("Pragma", "no-cache");
            res.setHeader("Expires", "-1");

            //파일객체를 생성한다
            File tempFile = new File(fileName);

            //데이터스트림을 생성한다
            FileInputStream in = new FileInputStream(tempFile);
            //Response객체를 이용하여 출력스트림을 생성
            ServletOutputStream out = res.getOutputStream();

            //모든데이터를 출력한다(버퍼길이만큼나누어서 출력한다)
            while((byteData = in.read(buffer, offset, buffer.length)) != -1){
                out.write(buffer, 0, byteData);
            }
            in.close();
            out.flush();
            out.close();
        }catch(IOException ex){
        	res.setStatus(404);
        	throw new Exception("download", ex);
        }
	}
 
Example 18
Source File: RequestLogFilter.java    From plumdo-work with Apache License 2.0 4 votes vote down vote up
private void finishResponse(ServletOutputStream outputStream, byte[] body) throws IOException {
    if (body.length > 0) {
        outputStream.flush();
        outputStream.close();
    }
}
 
Example 19
Source File: ShowComponent.java    From openemm with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
   * Gets mailing components
   * TYPE_IMAGE: if component not empty, write it into response
   * <br><br>
   * TYPE_HOSTED_IMAGE: if component not empty, write it into response
   * <br><br>
   * TYPE_THUMBNAIL_IMAGE: if component not empty, write it into response
   * <br><br>
   * TYPE_ATTACHMENT: create preview <br>
   *          write component into response
   * <br><br>
   * TYPE_PERSONALIZED_ATTACHMENT: create preview <br>
   *          write component into response
   * <br><br>
   */
  @Override
  public void service(HttpServletRequest req, HttpServletResponse response) throws IOException, ServletException {
      ServletOutputStream out;
      long len;
      int compId;
      
if (!AgnUtils.isUserLoggedIn(req)) {
          return;
      }
	
String compIDParam = req.getParameter("compID");
compId = NumberUtils.toInt(compIDParam, -1);

if (compId < 0) {
	logger.warn("Error converting " + (compIDParam != null ? "'" + compIDParam + "'" : compIDParam) + " to integer");
	return;
}
      
      if(compId==0) {
          return;
      }
	
String customerIDStr = req.getParameter("customerID");
int customerID = NumberUtils.toInt(customerIDStr);
      
      MailingComponent comp = getComponentDao().getMailingComponent(compId, AgnUtils.getCompanyID(req));
      
if (comp != null) {
          try {
		switch (MailingComponentType.getMailingComponentTypeByCode(comp.getType())) {
			case Image:
		    case HostedImage:
			case ThumbnailImage:
				if (comp.getBinaryBlock() != null) {
					response.setContentType(comp.getMimeType());
					out=response.getOutputStream();
					out.write(comp.getBinaryBlock());
					out.flush();
					out.close();
				}
				break;
			case Attachment:
		    case PersonalizedAttachment:
		        HttpUtils.setDownloadFilenameHeader(response, comp.getComponentName());
		        response.setContentType(comp.getMimeType());
		        out=response.getOutputStream();
		       
		        byte[] attachment;
		        int mailingID = comp.getMailingID();
		                            
		        if (MailingComponentType.PersonalizedAttachment.getCode() == comp.getType()) {
		        	Page page;
		            if(customerID == 0){ // no customerID is available, take the 1st available test recipient
		            	Map<Integer,String> recipientList = getRecipientDao().getAdminAndTestRecipientsDescription(comp.getCompanyID(), mailingID);
		            	customerID = recipientList.keySet().iterator().next();
		            }
		            Preview preview = getPreviewFactory().createPreview();
		            page = preview.makePreview(mailingID, customerID, false);
		            attachment = page.getAttachment(comp.getComponentName());
		        } else {
		        	attachment = comp.getBinaryBlock();
		        }
		        
		        len= attachment.length;
		        response.setContentLength((int)len);
		        out.write(attachment);
		        out.flush();
		        out.close();
		        break;
		case PrecAAttachement:
			// do not show component
			break;
		case Template:
			// do not show component
			break;
		default:
			throw new Exception("Invalid component type");
		}
	} catch (Exception e) {
		logger.error("Invalid component found: " + AgnUtils.getCompanyID(req) + "/" + compId, e);
		// do not show component
	}
      }
  }
 
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();
}