List of usage examples for javax.servlet ServletOutputStream flush
public void flush() throws IOException
From source file:net.sf.jsog.spring.JsogViewTest.java
@Test public void testRenderMergedOutputModelBeanCustomBeanJsogFactory() throws Exception { // Setup//from ww w. j a v a 2s . com String encoding = "ISO-8859-1"; // Default encoding JSOG beanJsog = JSOG.object("foo", "foovalue").put("bar", "barvalue"); JSOG expected = JSOG.object("bean", beanJsog); MediaType contentType = MediaType.APPLICATION_JSON; BeanJsogFactory bjf = createMock(BeanJsogFactory.class); instance.setBeanJsogFactory(bjf); expect(bjf.create(isA(TestBean.class))).andReturn(beanJsog); // Setup the model Map<String, Object> model = new HashMap<String, Object>(); model.put("bean", new TestBean()); // Setup the output stream ServletOutputStream sos = createMock(ServletOutputStream.class); expect(response.getOutputStream()).andReturn(sos); Capture<byte[]> out = new Capture<byte[]>(); sos.write(capture(out)); expectLastCall(); sos.flush(); expectLastCall(); sos.close(); expectLastCall(); response.setContentType(contentType.toString()); expectLastCall(); response.setCharacterEncoding(encoding); expectLastCall(); response.setContentLength(expected.toString().getBytes(encoding).length); expectLastCall(); expect(request.getParameter("callback")).andReturn(null); // Execution replay(request, response, sos, bjf); instance.renderMergedOutputModel(model, request, response); // Verification verify(request, response, sos, bjf); assertTrue(out.hasCaptured()); // Parse the resulting value JSOG actual = JSOG.parse(new String(out.getValue(), encoding)); assertEquals(actual, expected); }
From source file:org.jahia.services.content.files.FileServlet.java
@Override protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { long timer = System.currentTimeMillis(); int code = HttpServletResponse.SC_OK; try {//from w ww. ja va 2 s.c o m FileKey fileKey = parseKey(req); if (fileKey != null && fileKey.getWorkspace() != null && StringUtils.isNotEmpty(fileKey.getPath())) { Cache<String, FileLastModifiedCacheEntry> lastModifiedCache = cacheManager.getLastModifiedCache(); FileLastModifiedCacheEntry lastModifiedEntry = lastModifiedCache.get(fileKey.getCacheKey()); if (isNotModified(fileKey, lastModifiedEntry, req, res)) { // resource is not changed code = HttpServletResponse.SC_NOT_MODIFIED; res.setStatus(HttpServletResponse.SC_NOT_MODIFIED); logAccess(fileKey, req, "ok-not-modified"); return; } Cache<String, Map<String, FileCacheEntry>> contentCache = cacheManager.getContentCache(); Map<String, FileCacheEntry> entries = contentCache.get(fileKey.getCacheKey()); FileCacheEntry fileEntry = entries != null ? entries.get(fileKey.getThumbnail()) : null; if (fileEntry == null) { JCRNodeWrapper n = getNode(fileKey); if (n == null || !n.isFile()) { // cannot find it or it is not a file code = HttpServletResponse.SC_NOT_FOUND; res.sendError(HttpServletResponse.SC_NOT_FOUND); return; } Date lastModifiedDate = n.getLastModifiedAsDate(); long lastModified = lastModifiedDate != null ? lastModifiedDate.getTime() : 0; String eTag = generateETag(n.getIdentifier(), lastModified); if (lastModifiedEntry == null) { lastModifiedEntry = new FileLastModifiedCacheEntry(eTag, lastModified); if (canCache(n)) { lastModifiedCache.put(fileKey.getCacheKey(), lastModifiedEntry); } } if (isNotModified(fileKey, lastModifiedEntry, req, res)) { // resource is not changed code = HttpServletResponse.SC_NOT_MODIFIED; res.setStatus(HttpServletResponse.SC_NOT_MODIFIED); logAccess(fileKey, req, "ok-not-modified"); return; } fileEntry = getFileEntry(fileKey, n, lastModifiedEntry); if (fileEntry != null && fileEntry.getData() != null) { entries = contentCache.get(fileKey.getCacheKey()); if (entries == null) { entries = new HashMap<String, FileCacheEntry>(1); } entries.put(fileKey.getThumbnail(), fileEntry); contentCache.put(fileKey.getCacheKey(), entries); logAccess(fileKey, req, "ok"); } } else { if (lastModifiedEntry == null) { lastModifiedEntry = new FileLastModifiedCacheEntry(fileEntry.getETag(), fileEntry.getLastModified()); lastModifiedCache.put(fileKey.getCacheKey(), lastModifiedEntry); } logAccess(fileKey, req, "ok-cached"); if (logger.isDebugEnabled()) { logger.debug("Serving cached file entry {}", fileKey.toString()); } } if (fileEntry != null) { List<RangeUtils.Range> ranges; boolean useRanges = true; if (fileEntry.getBinary() instanceof BinaryRangesSupport) { useRanges = ((BinaryRangesSupport) fileEntry.getBinary()).supportRanges(); } ranges = useRanges ? RangeUtils.parseRange(req, res, fileEntry.getETag(), fileEntry.getLastModified(), fileEntry.getContentLength()) : null; if (fileKey.getPath().indexOf('%', fileKey.getPath().lastIndexOf('/')) != -1) { res.setHeader("Content-Disposition", "inline; filename=\"" + JCRContentUtils.unescapeLocalNodeName( StringUtils.substringAfterLast(fileKey.getPath(), "/")) + "\""); } res.setDateHeader("Last-Modified", fileEntry.getLastModified()); res.setHeader("ETag", fileEntry.getETag()); InputStream is = null; if (fileEntry.getData() != null) { // writing in-memory data is = new ByteArrayInputStream(fileEntry.getData()); } else if (fileEntry.getBinary() != null) { // spool from an input stream is = fileEntry.getBinary().getStream(); } else { code = HttpServletResponse.SC_NOT_FOUND; res.sendError(HttpServletResponse.SC_NOT_FOUND); return; } if (ranges == null || (ranges == RangeUtils.FULL)) { res.setContentType(fileEntry.getMimeType()); if (fileEntry.getContentLength() <= Integer.MAX_VALUE) { res.setContentLength((int) fileEntry.getContentLength()); } else { res.setHeader("Content-Length", Long.toString(fileEntry.getContentLength())); } ServletOutputStream os = res.getOutputStream(); IOUtils.copy(is, os); os.flush(); os.close(); } else { res.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); if (ranges.size() == 1) { res.setContentType(fileEntry.getMimeType()); RangeUtils.Range range = (RangeUtils.Range) ranges.get(0); res.addHeader("Content-Range", "bytes " + range.start + "-" + range.end + "/" + range.length); long length = range.end - range.start + 1; if (length < Integer.MAX_VALUE) { res.setContentLength((int) length); } else { // Set the content-length as String to be able to use a long res.setHeader("Content-Length", "" + length); } ServletOutputStream os = res.getOutputStream(); RangeUtils.copy(is, os, range); IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); } else { res.setContentType("multipart/byteranges; boundary=" + RangeUtils.MIME_SEPARATION); try { res.setBufferSize(RangeUtils.getOutput()); } catch (IllegalStateException e) { // Silent catch } ServletOutputStream os = res.getOutputStream(); RangeUtils.copy(is, os, ranges.iterator(), fileEntry.getMimeType()); IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); } } if ((fileEntry.getData() == null) && (fileEntry.getBinary() != null)) { fileEntry.getBinary().dispose(); fileEntry.setBinary(null); } SpringContextSingleton.getInstance() .publishEvent(new FileDownloadEvent(this, req, fileEntry.getIdentifier(), fileKey.getPath(), fileEntry.getNodeTypes(), fileKey.getWorkspace())); } else { code = HttpServletResponse.SC_NOT_FOUND; res.sendError(HttpServletResponse.SC_NOT_FOUND); return; } } else { code = HttpServletResponse.SC_NOT_FOUND; res.sendError(HttpServletResponse.SC_NOT_FOUND); } } catch (RepositoryException e) { logger.error("Cannot get file", e); code = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } finally { if (logger.isDebugEnabled()) { logger.debug("Served [{}] with status code [{}] in [{}ms]", new Object[] { req.getRequestURI() + (req.getQueryString() != null ? "?" + req.getQueryString() : ""), code, (System.currentTimeMillis() - timer) }); } } }
From source file:org.paxle.tools.charts.impl.gui.ChartServlet.java
@Override protected void doRequest(HttpServletRequest request, HttpServletResponse response) { String chartType = null;// w w w . ja v a2 s . c om try { String display = request.getParameter("display"); chartType = request.getParameter("t"); if ((display == null || display.equals("plain")) && (chartType != null)) { // getting requested graph size String wStrg = request.getParameter("w"); int width = Integer.parseInt(wStrg == null ? "385" : wStrg); String hStrg = request.getParameter("h"); int height = Integer.parseInt(hStrg == null ? "200" : hStrg); // getting the reuested chart JFreeChart chart = this.chartMap.get(chartType); if (chart == null) { response.setStatus(404); return; } // set response type response.setContentType("image/png"); // render image ServletOutputStream out = response.getOutputStream(); ChartUtilities.writeChartAsPNG(out, chart, width, height); out.flush(); } else { // using velocity template super.doRequest(request, response); } } catch (Exception e) { if (e instanceof IIOException && e.getCause() != null && e.getCause().getCause() != null && e.getCause().getCause().getMessage() != null && e.getCause().getCause().getMessage().equalsIgnoreCase("Broken pipe")) { this.logger.debug(String.format("Broken pipe while writing chart '%s'.", chartType)); } else if (e.getClass().getName().equals("org.mortbay.jetty.EofException")) { //c.f. bug #293 this.logger.debug(String.format("Broken connection while writing chart '%s'.", chartType)); } else { this.logger.error(String.format("Unexpected '%s' while writing chart '%s'.", e.getClass().getName(), chartType), e); } } }
From source file:org.inbio.ait.web.ajax.controller.PointsController.java
private ModelAndView writeReponse(HttpServletRequest request, HttpServletResponse response, List<Specimen> specimens) throws Exception { response.setCharacterEncoding("ISO-8859-1"); response.setContentType("text/xml"); ServletOutputStream out = response.getOutputStream(); StringBuilder result = new StringBuilder(); result.append("<?xml version='1.0' encoding='ISO-8859-1'?><response><specimens>"); for (Specimen s : specimens) { result.append("<specimen><scientificname>" + s.getScientificname() + "</scientificname>" + "<longitude>" + s.getDecimallongitude() + "</longitude>" + "<catalog>" + s.getCatalognumber() + "</catalog>" + "<institution>" + s.getInstitutioncode() + "</institution>" + "<latitude>" + s.getDecimallatitude() + "</latitude></specimen>"); }/*from w w w . j a v a 2 s . co m*/ result.append("</specimens></response>"); out.println(result.toString()); out.flush(); out.close(); return null; }
From source file:au.org.ala.layers.web.UserDataService.java
private void setImageBlank(HttpServletResponse response) { if (blankImageBytes == null && blankImageObject != null) { synchronized (blankImageObject) { if (blankImageBytes == null) { try { RandomAccessFile raf = new RandomAccessFile( UserDataService.class.getResource("/blank.png").getFile(), "r"); blankImageBytes = new byte[(int) raf.length()]; raf.read(blankImageBytes); raf.close();//w w w . ja v a 2 s. c o m } catch (IOException e) { logger.error("error reading default blank tile", e); } } } } if (blankImageObject != null) { response.setContentType("image/png"); try { ServletOutputStream outStream = response.getOutputStream(); outStream.write(blankImageBytes); outStream.flush(); outStream.close(); } catch (IOException e) { logger.error("error outputting blank tile", e); } } }
From source file:com.seer.datacruncher.spring.ExtraCheckCustomCodeValidator.java
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String code = request.getParameter("value"); String name = request.getParameter("name"); String addReq = request.getParameter("addReq"); //TODO: take the result message from "locale" String result = null;/*from w ww . j a v a 2s . co m*/ ObjectMapper mapper = new ObjectMapper(); ServletOutputStream out = null; response.setContentType("application/json"); out = response.getOutputStream(); if (StringUtils.isEmpty(code) || StringUtils.isEmpty(name)) { result = I18n.getMessage("error.extracheck.invaliddata"); } else { name = name.trim(); if (addReq.equalsIgnoreCase("true")) { ReadList list = checksTypeDao.findCustomCodeByName(name); if (list != null && CollectionUtils.isNotEmpty(list.getResults())) { result = I18n.getMessage("error.extracheck.name.alreadyexist"); out.write(mapper.writeValueAsBytes(result)); out.flush(); out.close(); return null; } } try { File sourceDir = new File(System.getProperty("java.io.tmpdir"), "DataCruncher/src"); sourceDir.mkdirs(); String classNamePack = name.replace('.', File.separatorChar); String srcFilePath = sourceDir + "" + File.separatorChar + classNamePack + ".java"; File sourceFile = new File(srcFilePath); if (sourceFile.exists()) { sourceFile.delete(); } FileUtils.writeStringToFile(new File(srcFilePath), code); DynamicClassLoader dynacode = DynamicClassLoader.getInstance(); dynacode.addSourceDir(sourceDir); CustomCodeValidator customCodeValidator = (CustomCodeValidator) dynacode .newProxyInstance(CustomCodeValidator.class, name); boolean isValid = false; if (customCodeValidator != null) { Class clazz = dynacode.getLoadedClass(name); if (clazz != null) { Class[] interfaces = clazz.getInterfaces(); if (ArrayUtils.isNotEmpty(interfaces)) { for (Class clz : interfaces) { if ((clz.getName().equalsIgnoreCase( "com.seer.datacruncher.utils.validation.SingleValidation"))) { isValid = true; } } } } } if (isValid) { result = "Success"; } else { result = I18n.getMessage("error.extracheck.wrongimpl"); } } catch (Exception e) { result = "Failed. Reason:" + e.getMessage(); } } out.write(mapper.writeValueAsBytes(result)); out.flush(); out.close(); return null; }
From source file:com.jd.survey.web.survey.PublicSurveyController.java
/** * Returns the survey logo image binary * @param departmentId//from w w w . j av a 2 s .c om * @param uiModel * @param httpServletRequest * @return */ @RequestMapping(value = "/logo/{id}", produces = "text/html") public void getSurveyLogo(@PathVariable("id") Long surveyDefinitionId, Model uiModel, Principal principal, HttpServletRequest httpServletRequest, HttpServletResponse response) { try { uiModel.asMap().clear(); //Check if the user is authorized SurveyDefinition surveyDefinition = surveySettingsService.surveyDefinition_findById(surveyDefinitionId); if (!surveyDefinition.getIsPublic()) {//survey definition not open to the public //attempt to access a private survey definition from a public open url log.warn(SURVEY_NOT_PUBLIC_WARNING_MESSAGE + httpServletRequest.getPathInfo() + FROM_IP_WARNING_MESSAGE + httpServletRequest.getLocalAddr()); throw (new RuntimeException("Unauthorized access to logo")); } else { //response.setContentType("image/png"); ServletOutputStream servletOutputStream = response.getOutputStream(); servletOutputStream.write(surveyDefinition.getLogo()); servletOutputStream.flush(); } } catch (Exception e) { log.error(e.getMessage(), e); throw (new RuntimeException(e)); } }
From source file:net.nan21.dnet.core.web.controller.AbstractDnetController.java
protected void sendFile(File file, ServletOutputStream outputStream, int bufferSize) throws IOException { InputStream in = null;/* w ww . j a v a 2s . co m*/ try { in = new BufferedInputStream(new FileInputStream(file)); byte[] buf = new byte[bufferSize]; int bytesRead; while ((bytesRead = in.read(buf)) != -1) { outputStream.write(buf, 0, bytesRead); } } finally { if (in != null) in.close(); } outputStream.flush(); }
From source file:com.openkm.servlet.frontend.DownloadServlet.java
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { log.debug("service({}, {})", request, response); request.setCharacterEncoding("UTF-8"); String path = request.getParameter("path"); String uuid = request.getParameter("uuid"); String[] uuidList = request.getParameterValues("uuidList"); String[] pathList = request.getParameterValues("pathList"); String checkout = request.getParameter("checkout"); String ver = request.getParameter("ver"); boolean export = request.getParameter("export") != null; boolean inline = request.getParameter("inline") != null; File tmp = File.createTempFile("okm", ".tmp"); InputStream is = null;//w w w .ja v a2 s .c om updateSessionManager(request); try { // Now an document can be located by UUID if (uuid != null && !uuid.equals("")) { uuid = FormatUtil.sanitizeInput(uuid); path = OKMRepository.getInstance().getNodePath(null, uuid); } else if (path != null) { path = FormatUtil.sanitizeInput(path); path = new String(path.getBytes("ISO-8859-1"), "UTF-8"); } if (export) { if (exportZip) { FileOutputStream os = new FileOutputStream(tmp); String fileName = "export.zip"; if (path != null) { exportFolderAsZip(path, os); fileName = PathUtils.getName(path) + ".zip"; } else if (uuidList != null || pathList != null) { // Export into a zip file multiple documents List<String> paths = new ArrayList<String>(); if (uuidList != null) { for (String uuidElto : uuidList) { String foo = new String(uuidElto.getBytes("ISO-8859-1"), "UTF-8"); paths.add(OKMRepository.getInstance().getNodePath(null, foo)); } } else if (pathList != null) { for (String pathElto : pathList) { String foo = new String(pathElto.getBytes("ISO-8859-1"), "UTF-8"); paths.add(foo); } } fileName = PathUtils.getName(PathUtils.getParent(paths.get(0))); exportDocumentsAsZip(paths, os, fileName); fileName += ".zip"; } os.flush(); os.close(); is = new FileInputStream(tmp); // Send document WebUtils.sendFile(request, response, fileName, MimeTypeConfig.MIME_ZIP, inline, is); } else if (exportJar) { // Get document FileOutputStream os = new FileOutputStream(tmp); exportFolderAsJar(path, os); os.flush(); os.close(); is = new FileInputStream(tmp); // Send document String fileName = PathUtils.getName(path) + ".jar"; WebUtils.sendFile(request, response, fileName, "application/x-java-archive", inline, is); } } else { if (OKMDocument.getInstance().isValid(null, path)) { // Get document Document doc = OKMDocument.getInstance().getProperties(null, path); if (ver != null && !ver.equals("")) { is = OKMDocument.getInstance().getContentByVersion(null, path, ver); } else { is = OKMDocument.getInstance().getContent(null, path, checkout != null); } // Send document String fileName = PathUtils.getName(doc.getPath()); WebUtils.sendFile(request, response, fileName, doc.getMimeType(), inline, is); } else if (OKMMail.getInstance().isValid(null, path)) { // Get mail Mail mail = OKMMail.getInstance().getProperties(null, path); // Send mail ServletOutputStream sos = response.getOutputStream(); String fileName = PathUtils.getName(mail.getSubject() + ".eml"); WebUtils.prepareSendFile(request, response, fileName, MimeTypeConfig.MIME_EML, inline); response.setContentLength((int) mail.getSize()); MimeMessage m = MailUtils.create(null, mail); m.writeTo(sos); sos.flush(); sos.close(); } } } catch (PathNotFoundException e) { log.warn(e.getMessage(), e); throw new ServletException(new OKMException( ErrorCode.get(ErrorCode.ORIGIN_OKMDownloadService, ErrorCode.CAUSE_PathNotFound), e.getMessage())); } catch (RepositoryException e) { log.warn(e.getMessage(), e); throw new ServletException( new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMDownloadService, ErrorCode.CAUSE_Repository), e.getMessage())); } catch (IOException e) { log.error(e.getMessage(), e); throw new ServletException(new OKMException( ErrorCode.get(ErrorCode.ORIGIN_OKMDownloadService, ErrorCode.CAUSE_IO), e.getMessage())); } catch (DatabaseException e) { log.error(e.getMessage(), e); throw new ServletException(new OKMException( ErrorCode.get(ErrorCode.ORIGIN_OKMDownloadService, ErrorCode.CAUSE_Database), e.getMessage())); } catch (Exception e) { log.error(e.getMessage(), e); throw new ServletException(new OKMException( ErrorCode.get(ErrorCode.ORIGIN_OKMDownloadService, ErrorCode.CAUSE_General), e.getMessage())); } finally { IOUtils.closeQuietly(is); FileUtils.deleteQuietly(tmp); } log.debug("service: void"); }
From source file:org.eclipse.userstorage.tests.util.USSServer.java
protected void retrieveProperties(HttpServletRequest request, HttpServletResponse response, File applicationFolder) throws IOException { String applicationToken = applicationFolder.getName(); int pageSize = getIntParameter(request, "pageSize", 20); if (pageSize < 1 || pageSize > 100) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid page size"); return;//from ww w . ja va 2 s . c o m } int page = getIntParameter(request, "page", 20); if (page < 1) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid page"); return; } boolean empty = true; StringBuilder builder = new StringBuilder(); builder.append('['); File[] files = applicationFolder.listFiles(); if (files != null) { int first = (page - 1) * pageSize + 1; System.out.println("##### " + first); int i = 0; for (File file : files) { String name = file.getName(); if (name.endsWith(ETAG_EXTENSION)) { if (++i >= first) { String key = name.substring(0, name.length() - ETAG_EXTENSION.length()); System.out.println("##### " + key); String etag = IOUtil.readUTF(file); if (empty) { empty = false; } else { builder.append(","); } builder.append("{\"application_token\":\""); builder.append(applicationToken); builder.append("\",\"key\":\""); builder.append(key); builder.append("\",\"etag\":\""); builder.append(etag); builder.append("\"}"); if (--pageSize == 0) { break; } } } } } builder.append(']'); System.out.println(builder); response.setStatus(HttpServletResponse.SC_OK); response.setContentType("application/json"); InputStream body = IOUtil.streamUTF(builder.toString()); try { ServletOutputStream out = response.getOutputStream(); IOUtil.copy(body, out); out.flush(); } finally { IOUtil.closeSilent(body); } }