Java Code Examples for javax.servlet.ServletOutputStream#write()
The following examples show how to use
javax.servlet.ServletOutputStream#write() .
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: LaunchClassicBatchSampleServlet.java From appstatus with Apache License 2.0 | 6 votes |
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // launch the batch ExecutorService executorService = Executors.newCachedThreadPool(); executorService.execute(new BatchSample()); ServletOutputStream os = resp.getOutputStream(); os.write("<html><head".getBytes(ENCODING)); os.write("<body>".getBytes(ENCODING)); os.write("<h1>Batch started</h1><p>The demo batch has been sucessfully started </p>" .getBytes(ENCODING)); os.write("</body></html>".getBytes(ENCODING)); }
Example 2
Source File: CommonController.java From spring-boot-projects with Apache License 2.0 | 6 votes |
@GetMapping("/common/kaptcha") public void defaultKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception { byte[] captchaOutputStream = null; ByteArrayOutputStream imgOutputStream = new ByteArrayOutputStream(); try { //生产验证码字符串并保存到session中 String verifyCode = captchaProducer.createText(); httpServletRequest.getSession().setAttribute("verifyCode", verifyCode); BufferedImage challenge = captchaProducer.createImage(verifyCode); ImageIO.write(challenge, "jpg", imgOutputStream); } catch (IllegalArgumentException e) { httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND); return; } captchaOutputStream = imgOutputStream.toByteArray(); httpServletResponse.setHeader("Cache-Control", "no-store"); httpServletResponse.setHeader("Pragma", "no-cache"); httpServletResponse.setDateHeader("Expires", 0); httpServletResponse.setContentType("image/jpeg"); ServletOutputStream responseOutputStream = httpServletResponse.getOutputStream(); responseOutputStream.write(captchaOutputStream); responseOutputStream.flush(); responseOutputStream.close(); }
Example 3
Source File: Tools.java From torrenttunes-client with GNU General Public License v3.0 | 6 votes |
public static HttpServletResponse writeFileToResponse2(String path, Response res) { byte[] encoded; try { encoded = java.nio.file.Files.readAllBytes(Paths.get(path)); ServletOutputStream os = res.raw().getOutputStream(); os.write(encoded); os.close(); return res.raw(); } catch (IOException e) { throw new NoSuchElementException("Couldn't write response from path: " + path); } }
Example 4
Source File: NetworkExplorer.java From jcifs with GNU Lesser General Public License v2.1 | 6 votes |
protected void doFile ( HttpServletRequest req, HttpServletResponse resp, SmbFile file ) throws IOException { byte[] buf = new byte[8192]; @SuppressWarnings ( "resource" ) ServletOutputStream out = resp.getOutputStream(); String url; int n; try ( SmbFileInputStream in = new SmbFileInputStream(file) ) { url = file.getLocator().getPath(); resp.setContentType("text/plain"); resp.setContentType(URLConnection.guessContentTypeFromName(url)); resp.setHeader("Content-Length", file.length() + ""); resp.setHeader("Accept-Ranges", "Bytes"); while ( ( n = in.read(buf) ) != -1 ) { out.write(buf, 0, n); } } }
Example 5
Source File: ApplicationAdminClient.java From carbon-commons with Apache License 2.0 | 6 votes |
public void downloadCappArchive(String filename, HttpServletResponse response) throws IOException, ApplicationAdminExceptionException { ServletOutputStream out = response.getOutputStream(); DataHandler dataHandler = stub.downloadCappArchive(filename); if (dataHandler != null) { if (!filename.endsWith(".car")) { filename += ".car"; } response.setHeader("Content-Disposition", "fileName=" + filename); response.setContentType(dataHandler.getContentType()); InputStream in = dataHandler.getDataSource().getInputStream(); int nextChar; while ((nextChar = in.read()) != -1) { out.write((char) nextChar); } out.flush(); in.close(); out.close(); } else { out.write("The requested capp archive was not found on the server".getBytes()); } }
Example 6
Source File: ControllerUtils.java From efo with MIT License | 6 votes |
/** * 加载本地资源 * * @param response 返回的Response * @param path 资源路径 * @param download 直接下载 */ public static void loadResource(HttpServletResponse response, String path, boolean download) throws IOException { if (Checker.isNotEmpty(path)) { File file = new File(path); if (download) { setResponseFileName(response, file.getName()); } FileInputStream in = new FileInputStream(file); ServletOutputStream os = response.getOutputStream(); byte[] b; while (in.available() > 0) { b = in.available() > 1024 ? new byte[1024] : new byte[in.available()]; in.read(b, 0, b.length); os.write(b, 0, b.length); } in.close(); os.flush(); os.close(); } else { response.sendRedirect(DefaultValues.NOT_FOUND_PAGE); } }
Example 7
Source File: HttpUrlConnectionTestServlet.java From apm-agent-java with Apache License 2.0 | 6 votes |
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { final URL url = new URL("http", req.getLocalAddr(), req.getLocalPort(),req.getServletContext().getContextPath() + "/hello-world.jsp"); final HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.connect(); final InputStream inputStream = urlConnection.getInputStream(); resp.setStatus(urlConnection.getResponseCode()); resp.setContentType(urlConnection.getHeaderField("Content-Type")); final byte[] buffer = new byte[1024]; final ServletOutputStream outputStream = resp.getOutputStream(); for (int limit = inputStream.read(buffer); limit != -1; limit = inputStream.read(buffer)) { outputStream.write(buffer, 0, limit); } inputStream.close(); urlConnection.disconnect(); outputStream.close(); }
Example 8
Source File: ProtectedResourceProvider.java From entando-components with GNU Lesser General Public License v3.0 | 6 votes |
protected void createResponse(HttpServletResponse resp, ResourceInterface resource, ResourceInstance instance) throws IOException, ServletException { resp.setContentType(instance.getMimeType()); resp.setHeader("Content-Disposition", "inline; filename=" + instance.getFileName()); ServletOutputStream out = resp.getOutputStream(); try { InputStream is = resource.getResourceStream(instance); if (null != is) { byte[] buffer = new byte[2048]; int length = -1; // Transfer the data while ((length = is.read(buffer)) != -1) { out.write(buffer, 0, length); out.flush(); } is.close(); } } catch (Throwable t) { logger.error("Error extracting protected resource", t); throw new ServletException("Error extracting protected resource", t); } finally { out.close(); } }
Example 9
Source File: HttpProxyServlet.java From openfire-ofmeet-plugin with Apache License 2.0 | 5 votes |
private void writeGet(String urlString, ServletOutputStream out) { byte[] buffer = new byte[4096]; try{ URL url = new URL(urlString); URLConnection urlConn = url.openConnection(); InputStream inStream = urlConn.getInputStream(); int n = -1; while ( (n = inStream.read(buffer)) != -1) { out.write(buffer, 0, n); } out.close(); } catch(MalformedURLException e){ Log.info("HttpProxy writeGet MalformedURLException", e); } catch(IOException e1){ Log.info("HttpProxy writeGet IOException", e1); } catch (Exception e2) { Log.info("HttpProxy - writeGet Exception", e2); } }
Example 10
Source File: TestHttpClient.java From localization_nifi with Apache License 2.0 | 5 votes |
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 11
Source File: FileAction.java From albert with MIT License | 5 votes |
@RequestMapping(value = "/downloadFile") public void downloadFile(@RequestParam("id")Integer id,HttpServletResponse response,HttpServletResponse request, ModelMap model){ try { FileDTO f = fileService.getFileDetail(id); //获取网站部署路径(通过ServletContext对象),用于确定下载文件位置,从而实现下载 String path = servletContext.getRealPath("/"); //1.设置文件ContentType类型,这样设置,会自动判断下载文件类型 response.setContentType("multipart/form-data"); //2.设置文件头:最后一个参数是设置下载文件名(假如我们叫a.pdf) response.setHeader("Content-Disposition", "attachment;fileName=download."+f.getFileFormat()); ServletOutputStream out; //通过文件路径获得File对象(假如此路径中有一个download.pdf文件) File file = new File(path +"uploadfile/"+ f.getUrl()); FileInputStream inputStream = new FileInputStream(file); //3.通过response获取ServletOutputStream对象(out) out = response.getOutputStream(); int b = 0; //创建缓冲区 byte buffer[] = new byte[1024]; int len = 0; //循环将输入流中的内容读取到缓冲区当中 while((len=inputStream.read(buffer))>0){ //输出缓冲区的内容到浏览器,实现文件下载 out.write(buffer, 0, len); } inputStream.close(); out.close(); out.flush(); } catch (IOException e) { e.printStackTrace(); } }
Example 12
Source File: FlowableDecisionTableService.java From flowable-engine with Apache License 2.0 | 5 votes |
protected void exportDefinition(HttpServletResponse response, AbstractModel definitionModel, Map<String, String> decisionTablesEditorJson) { try { JsonNode editorJsonNode = objectMapper.readTree(definitionModel.getModelEditorJson()); // URLEncoder.encode will replace spaces with '+', to keep the actual name replacing '+' to '%20' String fileName = URLEncoder.encode(definitionModel.getName(), "UTF-8").replaceAll("\\+", "%20") + ".dmn"; response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + fileName); ServletOutputStream servletOutputStream = response.getOutputStream(); response.setContentType("application/xml"); DmnDefinition dmnDefinition = dmnJsonConverter.convertToDmn(editorJsonNode, definitionModel.getId(), decisionTablesEditorJson); byte[] xmlBytes = dmnXmlConverter.convertToXML(dmnDefinition); BufferedInputStream in = new BufferedInputStream(new ByteArrayInputStream(xmlBytes)); byte[] buffer = new byte[8096]; while (true) { int count = in.read(buffer); if (count == -1) break; servletOutputStream.write(buffer, 0, count); } // Flush and close stream servletOutputStream.flush(); servletOutputStream.close(); } catch (Exception e) { LOGGER.error("Could not export decision table model", e); throw new InternalServerErrorException("Could not export decision table model"); } }
Example 13
Source File: LoggersPage.java From appstatus with Apache License 2.0 | 5 votes |
@Override public void doGet(StatusWebHandler webHandler, HttpServletRequest req, HttpServletResponse resp) throws UnsupportedEncodingException, IOException { LOGGER.debug("doGet"); if (isNotBlank(req.getParameter("name")) && isNotBlank(req.getParameter("level"))) { LoggerConfig logger2Change = new LoggerConfig(req.getParameter("name"), req.getParameter("level")); LOGGER.debug("Change log level : {} - {}", logger2Change.getName(), logger2Change.getLevel()); webHandler.getAppStatus().getLoggersManager().update(logger2Change); } setup(resp, "text/html"); ServletOutputStream os = resp.getOutputStream(); Map<String, String> valuesMap = new HashMap<String, String>(); // build sbLoggersTable StrBuilder sbLoggersTable = new StrBuilder(); List<LoggerConfig> loggers = webHandler.getAppStatus().getLoggersManager().getLoggers(); if (generateBeginTable(sbLoggersTable, loggers.size())) { generateHeaders(sbLoggersTable, "", "Name", "Levels", "", "", "", ""); for (LoggerConfig logger : loggers) { generateRow(sbLoggersTable, Resources.STATUS_PROP, logger.getName(), getButton(LEVEL_TRACE, logger), getButton(ILoggersManager.LEVEL_DEBUG, logger), getButton(LEVEL_INFO, logger), getButton(LEVEL_WARN, logger), getButton(LEVEL_ERROR, logger)); } generateEndTable(sbLoggersTable, loggers.size()); } // generating content valuesMap.put("loggersTable", sbLoggersTable.toString()); valuesMap.put("loggerCount", String.valueOf(loggers.size())); String content = applyLayout(valuesMap, PAGECONTENTLAYOUT); valuesMap.clear(); valuesMap.put("content", content); // generating page os.write(getPage(webHandler, valuesMap).getBytes(ENCODING)); }
Example 14
Source File: WorkFlowController.java From maven-framework-project with MIT License | 5 votes |
/** * 根据流程实例Id和资源类型加载流程资源 * @param processInstanceId 流程实例id * @param resourceType 流程资源类型 * @param request * @param response */ @RequestMapping(value="/loadResourceByProcessInstance",method={RequestMethod.GET,RequestMethod.POST}) public void loadResourceByProcessInstance(@RequestParam("processInstanceId")String processInstanceId,@RequestParam("resourceType")String resourceType,HttpServletRequest request, HttpServletResponse response){ //根据流程实例id查询流程实例 ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult(); //根据流程定义id查询流程定义 ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionId(processInstance.getProcessDefinitionId()).singleResult(); String resourceName=""; if(resourceType.equals("xml")){ //获取流程定义资源名称 resourceName=processDefinition.getResourceName(); }else if(resourceType.equals("image")){ //获取流程图资源名称 resourceName=processDefinition.getDiagramResourceName(); } //打开流程资源流 InputStream resourceAsStream = repositoryService.getResourceAsStream(processDefinition.getDeploymentId(), resourceName); //输出到浏览器 try { byte[] byteArray = IOUtils.toByteArray(resourceAsStream); ServletOutputStream servletOutputStream = response.getOutputStream(); servletOutputStream.write(byteArray, 0, byteArray.length); servletOutputStream.flush(); servletOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } }
Example 15
Source File: ServletWebSocketHttpExchange.java From lams with GNU General Public License v2.0 | 5 votes |
@Override public IoFuture<Void> sendData(final ByteBuffer data) { try { final ServletOutputStream outputStream = response.getOutputStream(); while (data.hasRemaining()) { outputStream.write(data.get()); } return new FinishedIoFuture<>(null); } catch (IOException e) { final FutureResult<Void> ioFuture = new FutureResult<>(); ioFuture.setException(e); return ioFuture.getIoFuture(); } }
Example 16
Source File: CommonController.java From newbee-mall with GNU General Public License v3.0 | 5 votes |
@GetMapping("/common/mall/kaptcha") public void mallKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception { com.google.code.kaptcha.impl.DefaultKaptcha newBeeMallLoginKaptcha = new com.google.code.kaptcha.impl.DefaultKaptcha(); Properties properties = new Properties(); properties.put("kaptcha.border", "no"); properties.put("kaptcha.textproducer.font.color", "27,174,171"); properties.put("kaptcha.noise.color", "20,33,42"); properties.put("kaptcha.textproducer.font.size", "30"); properties.put("kaptcha.image.width", "110"); properties.put("kaptcha.image.height", "40"); properties.put("kaptcha.session.key", Constants.MALL_VERIFY_CODE_KEY); properties.put("kaptcha.textproducer.char.space", "2"); properties.put("kaptcha.textproducer.char.length", "6"); Config config = new Config(properties); newBeeMallLoginKaptcha.setConfig(config); byte[] captchaOutputStream = null; ByteArrayOutputStream imgOutputStream = new ByteArrayOutputStream(); try { //生产验证码字符串并保存到session中 String verifyCode = newBeeMallLoginKaptcha.createText(); httpServletRequest.getSession().setAttribute(Constants.MALL_VERIFY_CODE_KEY, verifyCode); BufferedImage challenge = newBeeMallLoginKaptcha.createImage(verifyCode); ImageIO.write(challenge, "jpg", imgOutputStream); } catch (IllegalArgumentException e) { httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND); return; } captchaOutputStream = imgOutputStream.toByteArray(); httpServletResponse.setHeader("Cache-Control", "no-store"); httpServletResponse.setHeader("Pragma", "no-cache"); httpServletResponse.setDateHeader("Expires", 0); httpServletResponse.setContentType("image/jpeg"); ServletOutputStream responseOutputStream = httpServletResponse.getOutputStream(); responseOutputStream.write(captchaOutputStream); responseOutputStream.flush(); responseOutputStream.close(); }
Example 17
Source File: AbstractBaseController.java From onetwo with Apache License 2.0 | 5 votes |
protected void write(HttpServletResponse response, String contentType, byte[] data){ if(StringUtils.isNotBlank(contentType)){ response.setContentType(contentType); } ServletOutputStream ouput = null; try { ouput = response.getOutputStream(); ouput.write(data); } catch (IOException e) { String msg = "write data error:"; logger.error(msg + e.getMessage(), e); } finally{ IOUtils.closeQuietly(ouput); } }
Example 18
Source File: JcaptchaAction.java From DWSurvey with GNU Affero General Public License v3.0 | 5 votes |
public String execute() throws Exception { HttpServletRequest request = Struts2Utils.getRequest(); HttpServletResponse response = Struts2Utils.getResponse(); ByteArrayOutputStream out = null; byte[] captchaChallengeAsJpeg = null; // the output stream to render the captcha image as jpeg into ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream(); try { // get the session id that will identify the generated captcha. // the same id must be used to validate the response, the session id // is a good candidate! String captchaId = request.getSession().getId(); // call the ImageCaptchaService getChallenge method BufferedImage challenge = imageCaptchaService.getImageChallengeForID(captchaId, request.getLocale()); // a jpeg encoder /*** jdk1.7之后默认不支持了 **/ // JPEGImageEncoder jpegEncoder = JPEGCodec.createJPEGEncoder(jpegOutputStream); // jpegEncoder.encode(challenge); // 换成新版图片api ImageIO.write(challenge, "jpg", jpegOutputStream); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } captchaChallengeAsJpeg = jpegOutputStream.toByteArray(); // flush it in the response response.setHeader("Cache-Control", "no-store"); response.setHeader("Pragma", "no-cache"); response.setDateHeader("Expires", 0); response.setContentType("image/jpeg"); ServletOutputStream responseOutputStream = response.getOutputStream(); responseOutputStream.write(captchaChallengeAsJpeg); responseOutputStream.flush(); responseOutputStream.close(); return null; }
Example 19
Source File: TestCoyoteOutputStream.java From Tomcat8-Source-Read with MIT License | 5 votes |
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/plain"); resp.setCharacterEncoding("UTF-8"); ServletOutputStream sos = resp.getOutputStream(); for (int i = start; i < start + len; i++) { sos.write(("OK - " + i + System.lineSeparator()).getBytes( StandardCharsets.UTF_8)); } }
Example 20
Source File: TestCoyoteOutputStream.java From Tomcat8-Source-Read with MIT License | 5 votes |
private void doAsyncWrite(AsyncContext asyncCtxt, ServletOutputStream sos) throws IOException { while (sos.isReady()) { int next = asyncWriteCount.getAndIncrement(); if (next < asyncWriteTarget) { sos.write( ("OK - " + next + System.lineSeparator()).getBytes( StandardCharsets.UTF_8)); sos.flush(); } else { asyncCtxt.dispatch("/write"); break; } } }