javax.servlet.ServletOutputStream Java Examples

The following examples show how to use javax.servlet.ServletOutputStream. 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: AsyncServlet.java    From tutorials with MIT License 6 votes vote down vote up
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    ByteBuffer content = ByteBuffer.wrap(HEAVY_RESOURCE.getBytes(StandardCharsets.UTF_8));

    AsyncContext async = request.startAsync();
    ServletOutputStream out = response.getOutputStream();
    out.setWriteListener(new WriteListener() {
        @Override
        public void onWritePossible() throws IOException {
            while (out.isReady()) {
                if (!content.hasRemaining()) {
                    response.setStatus(200);
                    async.complete();
                    return;
                }
                out.write(content.get());
            }
        }

        @Override
        public void onError(Throwable t) {
            getServletContext().log("Async Error", t);
            async.complete();
        }
    });
}
 
Example #2
Source File: ResponseWrapper.java    From app-engine with Apache License 2.0 6 votes vote down vote up
@Override
public ServletOutputStream getOutputStream() throws IOException {
    return new ServletOutputStream() {
        private TeeOutputStream tee = new TeeOutputStream(ResponseWrapper.super.getOutputStream(), bos);

        @Override
        public boolean isReady() {
            return true;
        }

        @Override
        public void setWriteListener(WriteListener writeListener) {
        }

        @Override
        public void write(int b) throws IOException {
            tee.write(b);
        }
    };
}
 
Example #3
Source File: PhdDocumentRequestManagementDA.java    From fenixedu-academic with GNU Lesser General Public License v3.0 6 votes vote down vote up
public ActionForward printDocument(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request,
        HttpServletResponse response) throws IOException, FenixServiceException {
    final IDocumentRequest documentRequest = getPhdAcademicServiceRequest(request);
    try {
        byte[] data = documentRequest.generateDocument();

        response.setContentLength(data.length);
        response.setContentType("application/pdf");
        response.addHeader("Content-Disposition", "attachment; filename=" + documentRequest.getReportFileName() + ".pdf");

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

        response.flushBuffer();
        return null;
    } catch (DomainException e) {
        throw e;
    }
}
 
Example #4
Source File: MarkSheetSearchDispatchAction.java    From fenixedu-academic with GNU Lesser General Public License v3.0 6 votes vote down vote up
private ActionForward printMarkSheet(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request,
        HttpServletResponse response) throws FenixServiceException {
    DynaActionForm form = (DynaActionForm) actionForm;
    String markSheetString = form.getString("markSheet");
    MarkSheet markSheet = getDomainObject(form, "markSheet");
    ActionMessages actionMessages = new ActionMessages();

    try (ServletOutputStream writer = response.getOutputStream()) {
        MarkSheetDocument document = new MarkSheetDocument(markSheet);
        byte[] data = ReportsUtils.generateReport(document).getData();
        response.setContentLength(data.length);
        response.setContentType("application/pdf");
        response.addHeader("Content-Disposition", String.format("attachment; filename=%s.pdf", document.getReportFileName()));
        writer.write(data);
        markAsPrinted(markSheet);
        return null;
    } catch (Exception e) {
        request.setAttribute("markSheet", markSheetString);
        addMessage(request, actionMessages, e.getMessage());
        return choosePrinterMarkSheetsWeb(mapping, actionForm, request, response);
    }
}
 
Example #5
Source File: CommonController.java    From ProxyPool with Apache License 2.0 6 votes vote down vote up
@RequestMapping(value="/launchjob")
@ResponseBody
public void startJob(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {

    log.info("manual startJob");
    try {
        httpServletResponse.setContentType("text/plain; charset=utf-8");
        ServletOutputStream responseOutputStream = httpServletResponse.getOutputStream();
        if(scheduleJobs.getJobStatus() == ScheduleJobs.JOB_STATUS_RUNNING) {
            responseOutputStream.write("Job正在运行。。。".getBytes("utf-8"));
            responseOutputStream.flush();
            responseOutputStream.close();
        } else {
            log.info("scheduleJobs.cronJob() start by controller...");
            scheduleJobs.cronJob();
        }
    } catch (Exception e) {
        log.info("startJob exception e="+e.getMessage());
    }
}
 
Example #6
Source File: EvaluationManagementBackingBean.java    From fenixedu-academic with GNU Lesser General Public License v3.0 6 votes vote down vote up
private void exportToXls(String filename) throws IOException {
    this.getResponse().setContentType("application/vnd.ms-excel");
    this.getResponse().setHeader("Content-disposition", "attachment; filename=" + filename + ".xls");
    ServletOutputStream outputStream = this.getResponse().getOutputStream();

    String spreadSheetName = BundleUtil.getString(Bundle.APPLICATION, "title.enrolments");
    List<Object> headers = getStudentsEnroledListHeaders();
    Spreadsheet spreadsheet = new Spreadsheet(spreadSheetName, headers);

    reportInfo(spreadsheet);

    spreadsheet.exportToXLSSheet(outputStream);
    outputStream.flush();
    this.getResponse().flushBuffer();
    FacesContext.getCurrentInstance().responseComplete();
}
 
Example #7
Source File: AppDefinitionExportService.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
public void createAppDefinitionBar(HttpServletResponse response, Model appModel, AppDefinitionRepresentation appDefinition) {

        try {
            response.setHeader("Content-Disposition", "attachment; filename=\"" + appDefinition.getName() + ".bar\"; filename*=utf-8''" + UriUtils.encode(appDefinition.getName() + ".bar", "utf-8"));

            byte[] deployZipArtifact = createDeployableZipArtifact(appModel, appDefinition.getDefinition());

            ServletOutputStream servletOutputStream = response.getOutputStream();
            response.setContentType("application/zip");
            servletOutputStream.write(deployZipArtifact);

            // Flush and close stream
            servletOutputStream.flush();
            servletOutputStream.close();

        } catch (Exception e) {
            LOGGER.error("Could not generate app definition bar archive", e);
            throw new InternalServerErrorException("Could not generate app definition bar archive");
        }
    }
 
Example #8
Source File: JeecgTemplateWordView.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 = "临时文件.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 #9
Source File: TestGZIPResponseWrapper.java    From hbase with Apache License 2.0 6 votes vote down vote up
@Test
public void testResetBuffer() throws IOException {
  when(response.isCommitted()).thenReturn(false);
  ServletOutputStream out = mock(ServletOutputStream.class);
  when(response.getOutputStream()).thenReturn(out);

  ServletOutputStream servletOutput = wrapper.getOutputStream();
  assertEquals(GZIPResponseStream.class, servletOutput.getClass());
  wrapper.resetBuffer();
  verify(response).setHeader("Content-Encoding", null);

  when(response.isCommitted()).thenReturn(true);
  servletOutput = wrapper.getOutputStream();
  assertEquals(out.getClass(), servletOutput.getClass());
  assertNotNull(wrapper.getWriter());
}
 
Example #10
Source File: WebAdminInterceptionServletTest.java    From roboconf-platform with Apache License 2.0 6 votes vote down vote up
@Test
public void testInterceptionServlet_noKarafEtc_defaultFound() throws Exception {

	// Mocks
	HttpServletResponse resp = Mockito.mock( HttpServletResponse.class );
	Mockito.when( resp.getOutputStream()).thenReturn( Mockito.mock( ServletOutputStream.class ));

	HttpServletRequest req = Mockito.mock( HttpServletRequest.class );
	Mockito.when( req.getServletPath()).thenReturn( CSS_STYLESHEET );

	ServletConfig sc = Mockito.mock( ServletConfig.class );
	ServletContext ctx = Mockito.mock( ServletContext.class );
	Mockito.when( ctx.getResourceAsStream( Mockito.anyString())).thenReturn( new ByteArrayInputStream( new byte[ 0 ]));
	Mockito.when( sc.getServletContext()).thenReturn( ctx );

	// Initialization
	WebAdminInterceptionServlet servlet = new WebAdminInterceptionServlet();
	servlet.init( sc );

	// Execution
	servlet.doGet( req, resp );

	// Assertions
	Mockito.verify( req, Mockito.atLeast( 1 )).getServletPath();
	Mockito.verify( resp, Mockito.only()).getOutputStream();
}
 
Example #11
Source File: IdmProfileResource.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
@GetMapping(value = "/profile-picture")
public void getProfilePicture(HttpServletResponse response) {
    try {
        Pair<String, InputStream> picture = profileService.getProfilePicture();
        if (picture == null) {
            throw new NotFoundException();
        }
        response.setContentType(picture.getLeft());
        ServletOutputStream servletOutputStream = response.getOutputStream();

        byte[] buffer = new byte[32384];
        while (true) {
            int count = picture.getRight().read(buffer);
            if (count == -1)
                break;
            servletOutputStream.write(buffer, 0, count);
        }

        // Flush and close stream
        servletOutputStream.flush();
        servletOutputStream.close();
    } catch (Exception e) {
        throw new InternalServerErrorException("Could not get profile picture", e);
    }
}
 
Example #12
Source File: CodeController.java    From taoshop with Apache License 2.0 6 votes vote down vote up
@RequestMapping("/generate")
	public void generate(HttpServletRequest request, HttpServletResponse response){
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		String code = drawImg(output);

//		Subject currentUser = SecurityUtils.getSubject();
//		Session session = currentUser.getSession();
		HttpSession session = request.getSession();
		session.setAttribute(SESSION_SECURITY_CODE, code);

		try {
			ServletOutputStream out = response.getOutputStream();
			output.writeTo(out);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
 
Example #13
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 #14
Source File: TwitcastingMediaProxy.java    From Alice-LiveMan with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public void requestHandler(String videoId) throws Exception {
    MediaProxyTask mediaProxyTask = MediaProxyManager.getExecutedProxyTaskMap().get(videoId);
    if (mediaProxyTask instanceof TwitcastingMediaProxyTask) {
        TwitcastingMediaProxyTask twcProxyTask = (TwitcastingMediaProxyTask) mediaProxyTask;
        BlockingQueue<byte[]> bufferedQueue = new ArrayBlockingQueue<>(20);
        twcProxyTask.addBufferedQueue(bufferedQueue);
        try (ServletOutputStream outputStream = response.getOutputStream()) {
            boolean headerWrote = false;
            while (!twcProxyTask.getTerminated()) {
                byte[] bytes = bufferedQueue.poll(1000, TimeUnit.MILLISECONDS);
                if (bytes == null) {
                    continue;
                }
                if (!headerWrote) {
                    outputStream.write(twcProxyTask.getM4sHeader());
                    headerWrote = true;
                }
                outputStream.write(bytes);
            }
        } finally {
            twcProxyTask.removeBufferedQueue(bufferedQueue);
        }
    }
}
 
Example #15
Source File: TestCoyoteOutputStream.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");
    ServletOutputStream sos = resp.getOutputStream();


    AsyncContext asyncCtxt = req.startAsync();
    asyncCtxt.setTimeout(5);
    Runnable task = new AsyncTask(asyncCtxt, sos);
    if (useContainerThreadToSetListener) {
        asyncCtxt.start(task);
    } else {
        Thread t = new Thread(task);
        t.start();
    }
}
 
Example #16
Source File: InputStreamDownloadTest.java    From vraptor4 with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
	MockitoAnnotations.initMocks(this);
	
	bytes = new byte[] { (byte) 0x0 };
	inputStream = new ByteArrayInputStream(bytes);
	outputStream = new ByteArrayOutputStream();

	socketStream = new ServletOutputStream() {
		@Override
		public void write(int b) throws IOException {
			outputStream.write(b);
		}

		@Override
		public boolean isReady() {
			return false;
		}

		@Override
		public void setWriteListener(WriteListener writeListener) {
		}
	};

	when(response.getOutputStream()).thenReturn(socketStream);
}
 
Example #17
Source File: DefaultServlet.java    From olat with Apache License 2.0 6 votes vote down vote up
/**
 * Copy the contents of the specified input stream to the specified output stream, and ensure that both streams are closed before returning (even in the face of an
 * exception).
 * 
 * @param istream
 *            The input stream to read from
 * @param ostream
 *            The output stream to write to
 * @return Exception which occurred during processing
 */
private IOException copyRange(InputStream istream, ServletOutputStream ostream) {

    // Copy the input stream to the output stream
    IOException exception = null;
    byte buffer[] = new byte[input];
    int len = buffer.length;
    while (true) {
        try {
            len = istream.read(buffer);
            if (len == -1)
                break;
            ostream.write(buffer, 0, len);
        } catch (IOException e) {
            exception = e;
            len = -1;
            break;
        }
    }
    return exception;

}
 
Example #18
Source File: CourseLoadOverviewDA.java    From fenixedu-academic with GNU Lesser General Public License v3.0 6 votes vote down vote up
public ActionForward downloadInconsistencies(final ActionMapping mapping, final ActionForm form,
        final HttpServletRequest request, final HttpServletResponse response) {
    final ExecutionSemester executionSemester = getDomainObject(request, "executionSemesterOid");
    final CourseLoadOverviewBean bean = new CourseLoadOverviewBean(executionSemester);
    final StyledExcelSpreadsheet spreadsheet = bean.getInconsistencySpreadsheet();

    response.setContentType("application/vnd.ms-excel");
    response.setHeader("Content-disposition",
            "attachment; filename=" + BundleUtil.getString(Bundle.ACADEMIC, "label.course.load.inconsistency.filename")
                    + ".xls");

    try {
        final ServletOutputStream writer = response.getOutputStream();
        spreadsheet.getWorkbook().write(writer);
        writer.close();
    } catch (final IOException e) {
        throw new Error(e);
    }

    return null;
}
 
Example #19
Source File: LocalResponseTest.java    From logbook with MIT License 6 votes vote down vote up
@BeforeEach
void setUp() throws IOException {
    mock = mock(HttpServletResponse.class);
    when(mock.getOutputStream()).thenReturn(new ServletOutputStream() {
        @Override
        public boolean isReady() {
            return false;
        }

        @Override
        public void setWriteListener(final WriteListener listener) {
            // nothing to do here
        }

        @Override
        public void write(final int b) {
            // serves as a null or no-op output stream
        }
    });
    unit = new LocalResponse(mock, "1");
}
 
Example #20
Source File: TestUpgrade.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Override
public void init(WebConnection connection) {
    ServletInputStream sis;
    ServletOutputStream sos;

    try {
        sis = connection.getInputStream();
        sos = connection.getOutputStream();
    } catch (IOException ioe) {
        throw new IllegalStateException(ioe);
    }

    EchoListener echoListener = new EchoListener(sis, sos);
    sis.setReadListener(echoListener);
    sos.setWriteListener(echoListener);
}
 
Example #21
Source File: FileUtil.java    From eladmin with Apache License 2.0 6 votes vote down vote up
/**
 * 导出excel
 */
public static void downloadExcel(List<Map<String, Object>> list, HttpServletResponse response) throws IOException {
    String tempPath = SYS_TEM_DIR + IdUtil.fastSimpleUUID() + ".xlsx";
    File file = new File(tempPath);
    BigExcelWriter writer = ExcelUtil.getBigWriter(file);
    // 一次性写出内容,使用默认样式,强制输出标题
    writer.write(list, true);
    //response为HttpServletResponse对象
    response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
    //test.xls是弹出下载对话框的文件名,不能为中文,中文请自行编码
    response.setHeader("Content-Disposition", "attachment;filename=file.xlsx");
    ServletOutputStream out = response.getOutputStream();
    // 终止后删除临时文件
    file.deleteOnExit();
    writer.flush(out, true);
    //此处记得关闭输出Servlet流
    IoUtil.close(out);
}
 
Example #22
Source File: DownloadEventBean.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
private void downloadCsvSpreadsheet(List<SignupMeetingWrapper> smWrappers, String fileName) {

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

			csvSpreadsheet(out, smWrappers);

			out.flush();
		} catch (IOException ex) {
			log.warn("Error generating CSV spreadsheet for download event:" + ex.getMessage());
		} finally {
			if (out != null)
				closeStream(out);
		}
		fc.responseComplete();
	}
 
Example #23
Source File: ContentLengthCloseFlushServlet.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@Override
protected synchronized void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
    if (completed) {
        completed = false;
        resp.getWriter().write("OK");
    } else {
        resp.setContentLength(1);
        ServletOutputStream stream = resp.getOutputStream();
        stream.write('a'); //the stream should automatically close here, because it is the content length, but flush should still work
        stream.flush();
        stream.close();
        completed = true;
    }
}
 
Example #24
Source File: VerifyCodeController.java    From maven-archetype with GNU Lesser General Public License v2.1 5 votes vote down vote up
@RequestMapping("/code.do")
  public String getKaptchaImage(HttpServletRequest request,
						  HttpServletResponse response) throws Exception {
// Set to expire far in the past.
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(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();
}
return null; 
  }
 
Example #25
Source File: VoiceXmlSnippet.java    From JVoiceXML with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected void doGet(final HttpServletRequest request,
        final HttpServletResponse response)
                throws ServletException, IOException {
    VoiceXmlDocument document = null;
    final String prompt = request.getParameter("prompt");
    try {
        if (prompt != null) {
            document = createDocumentWithPrompt(prompt);
        } else {
            final String field = request.getParameter("field");
            if (field != null) {
                document = createDocument(field);
            }
        }
    } catch (ParserConfigurationException | SAXException | TransformerException e) {
        throw new IOException(e.getMessage(), e);
    }
    if (document == null) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                "neither parameter 'prompt' nor 'field' found");
        return;
    }
    response.setContentType("text/xml");
    final String xml = document.toXml();
    final ServletOutputStream out = response.getOutputStream();
    out.print(xml);
}
 
Example #26
Source File: FileUtil.java    From JavaWeb with Apache License 2.0 5 votes vote down vote up
public static void writeExcel(HttpServletResponse response,List<String> list) throws Exception {
	response.setContentType("application/vnd.ms-excel");//文件格式,此处设置为excel
	response.setHeader("Content-Disposition","attachment;filename=file.xls");//此处设置了下载文件的默认名称
	ServletOutputStream sos = response.getOutputStream();
    //创建一个新的excel
	XSSFWorkbook wb = new XSSFWorkbook();//XSSFWorkbook
	/**
	 * 采用现成Excel模板
	 * 用这种方式得先保证每个cell有值,不然会报空指针
	 * 有时我们用row.getCell(i)会得到null,那么此时就要用Iterator<Cell> it = row.cellIterator();
	 * XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream(new File("D://a.xlsx")));
	 * XSSFSheet sheet = wb.getSheet("Sheet1");
	 * row[i] = sheet.getRow(i);
	 * headerCell[j] = row[i].getCell(j);
	 */
	//创建sheet页
	XSSFSheet sheet = wb.createSheet("sheet1");//sheet名
	//创建行数
	XSSFRow[] row = new XSSFRow[list.size()];
	//插入数据
	for (int i = 0; i < row.length; i++) {
		row[i] = sheet.createRow(i);
		sheet.setDefaultColumnWidth(30);//设置列的长度
		String info[] = list.get(i).split(",");
		XSSFCell[] headerCell = new XSSFCell[info.length];
		for (int j = 0; j < headerCell.length; j++) {
			headerCell[j] = row[i].createCell(j);
			headerCell[j].setCellValue(new XSSFRichTextString(info[j]));
			/**设置模板样式*/
			//headerCell[j].setCellStyle(setStyle(wb));
		}
	}
	wb.write(sos);
	wb.close();
    sos.flush();
    sos.close();
    response.flushBuffer();
}
 
Example #27
Source File: ServletServerHttpResponse.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Write the DataBuffer to the response body OutputStream.
 * Invoked only when {@link ServletOutputStream#isReady()} returns "true"
 * and the readable bytes in the DataBuffer is greater than 0.
 * @return the number of bytes written
 */
protected int writeToOutputStream(DataBuffer dataBuffer) throws IOException {
	ServletOutputStream outputStream = this.outputStream;
	InputStream input = dataBuffer.asInputStream();
	int bytesWritten = 0;
	byte[] buffer = new byte[this.bufferSize];
	int bytesRead;
	while (outputStream.isReady() && (bytesRead = input.read(buffer)) != -1) {
		outputStream.write(buffer, 0, bytesRead);
		bytesWritten += bytesRead;
	}
	return bytesWritten;
}
 
Example #28
Source File: ExpiresFilter.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
public XServletOutputStream(ServletOutputStream servletOutputStream,
        HttpServletRequest request, XHttpServletResponse response) {
    super();
    this.servletOutputStream = servletOutputStream;
    this.response = response;
    this.request = request;
}
 
Example #29
Source File: JmxWebHandlerTest.java    From simplejmx with ISC License 5 votes vote down vote up
@Test
public void coverage() throws IOException {
	JmxWebHandler handler = new JmxWebHandler();
	Request request = new Request(null, null);
	HttpServletRequest servletRequest = EasyMock.createMock(HttpServletRequest.class);
	HttpServletResponse servletResponse = EasyMock.createMock(HttpServletResponse.class);

	ServletOutputStream outputStream = new ServletOutputStream() {
		@Override
		public void write(int b) {
		}

		@Override
		public boolean isReady() {
			return true;
		}

		@Override
		public void setWriteListener(WriteListener writeListener) {
		}
	};
	expect(servletResponse.getOutputStream()).andReturn(outputStream);
	servletResponse.setContentType("text/html");
	expect(servletRequest.getPathInfo()).andReturn(null);
	expect(servletRequest.getParameter("t")).andReturn(null);

	replay(servletRequest, servletResponse);
	handler.handle(null, request, servletRequest, servletResponse);
	verify(servletRequest, servletResponse);
}
 
Example #30
Source File: TestHttpServletToolbox.java    From cms with Apache License 2.0 5 votes vote down vote up
@Test
public void testWriteBodyResponseAsJson_exception()
{
	try
	{
		HashMap<String, String> errors = new HashMap<String, String>();
		String data = "data";
		HttpServletResponse responseMock = EasyMock.createMock(HttpServletResponse.class);
		ServletOutputStream outputStream = PowerMock.createMock(ServletOutputStream.class);
		EasyMock.expect(responseMock.getOutputStream()).andThrow(new IOException());
		responseMock.setContentType("application/json");
		responseMock.setContentType("application/json");
		responseMock.setCharacterEncoding("UTF-8");
		Capture<byte[]> captureContent = new Capture<byte[]>();
		Capture<Integer> captureInt = new Capture<Integer>();
		EasyMock.expect(responseMock.getOutputStream()).andReturn(outputStream);
		responseMock.setContentLength(EasyMock.captureInt(captureInt));
		outputStream.write(EasyMock.capture(captureContent));
		outputStream.flush();
		
		EasyMock.replay(responseMock, outputStream);

		httpServletToolbox.writeBodyResponseAsJson(responseMock, data, errors);
		EasyMock.verify(responseMock, outputStream);
		org.json.JSONObject json = new org.json.JSONObject(new String (captureContent.getValue()));
		Integer captureContentLen = json.toString().length();
		assertTrue (json.getString("status").compareTo("FAIL") == 0);
		assertTrue (json.getString("payload").compareTo("{}") == 0);
		assertTrue (json.getJSONObject("errors").toString().compareTo("{\"reason\":\"WB_UNKNOWN_ERROR\"}") == 0);
		assertTrue (captureInt.getValue().compareTo(captureContentLen) == 0);
	} catch (Exception e)
	{
		assertTrue(false);
	}
}