List of usage examples for javax.servlet ServletOutputStream close
public void close() throws IOException
From source file:SendWord.java
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //get the 'file' parameter String fileName = (String) request.getParameter("file"); if (fileName == null || fileName.equals("")) throw new ServletException("Invalid or non-existent file parameter in SendWord servlet."); // add the .doc suffix if it doesn't already exist if (fileName.indexOf(".doc") == -1) fileName = fileName + ".doc"; String wordDir = getServletContext().getInitParameter("word-dir"); if (wordDir == null || wordDir.equals("")) throw new ServletException("Invalid or non-existent wordDir context-param."); ServletOutputStream stream = null; BufferedInputStream buf = null; try {/*from w w w . j a va2s .com*/ stream = response.getOutputStream(); File doc = new File(wordDir + "/" + fileName); response.setContentType("application/msword"); response.addHeader("Content-Disposition", "attachment; filename=" + fileName); response.setContentLength((int) doc.length()); FileInputStream input = new FileInputStream(doc); buf = new BufferedInputStream(input); int readBytes = 0; while ((readBytes = buf.read()) != -1) stream.write(readBytes); } catch (IOException ioe) { throw new ServletException(ioe.getMessage()); } finally { if (stream != null) stream.close(); if (buf != null) buf.close(); } }
From source file:SendXml.java
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //get the 'file' parameter String fileName = (String) request.getParameter("file"); if (fileName == null || fileName.equals("")) throw new ServletException("Invalid or non-existent file parameter in SendXml servlet."); // add the .doc suffix if it doesn't already exist if (fileName.indexOf(".xml") == -1) fileName = fileName + ".xml"; String xmlDir = getServletContext().getInitParameter("xml-dir"); if (xmlDir == null || xmlDir.equals("")) throw new ServletException("Invalid or non-existent xmlDir context-param."); ServletOutputStream stream = null; BufferedInputStream buf = null; try {/*from w ww . ja v a2s . co m*/ stream = response.getOutputStream(); File xml = new File(xmlDir + "/" + fileName); response.setContentType("text/xml"); response.addHeader("Content-Disposition", "attachment; filename=" + fileName); response.setContentLength((int) xml.length()); FileInputStream input = new FileInputStream(xml); buf = new BufferedInputStream(input); int readBytes = 0; while ((readBytes = buf.read()) != -1) stream.write(readBytes); } catch (IOException ioe) { throw new ServletException(ioe.getMessage()); } finally { if (stream != null) stream.close(); if (buf != null) buf.close(); } }
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 www. j a v a 2 s. c om result.append("</specimens></response>"); out.println(result.toString()); out.flush(); out.close(); return null; }
From source file:OpenProdocServ.Oper.java
private void SendFile(HttpServletRequest Req, HttpServletResponse response) throws Exception { String Param = Req.getParameter(DriverRemote.PARAM); if (PDLog.isDebug()) PDLog.Debug("SendFile Param:" + Param); DocumentBuilder DB = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document XMLObjects = DB.parse(new ByteArrayInputStream(Param.getBytes("UTF-8"))); NodeList OPDObjectList = XMLObjects.getElementsByTagName("Id"); Node OPDObject = OPDObjectList.item(0); String Id = OPDObject.getTextContent(); OPDObjectList = XMLObjects.getElementsByTagName("Ver"); OPDObject = OPDObjectList.item(0);/*from ww w . ja va 2 s. c o m*/ String Ver = OPDObject.getTextContent(); DB.reset(); PDDocs doc = new PDDocs(getSessOPD(Req)); doc.setPDId(Id); if (Ver != null && Ver.length() != 0) doc.LoadVersion(Id, Ver); else doc.LoadCurrent(Id); ServletOutputStream out = response.getOutputStream(); PDMimeType mt = new PDMimeType(getSessOPD(Req)); mt.Load(doc.getMimeType()); response.setContentType(mt.getMimeCode()); response.setHeader("Content-disposition", "inline; filename=" + doc.getName()); try { if (Ver != null && Ver.length() != 0) doc.getStreamVer(out); else doc.getStream(out); } catch (Exception e) { out.close(); throw e; } out.close(); }
From source file:org.exist.webstart.JnlpWriter.java
/** * Send JAR or JAR.PACK.GZ file to end user. * * @param filename Name of JAR file//from ww w. j a v a2 s . co m * @param response Object for writing to end user. * @throws java.io.IOException */ void sendJar(JnlpJarFiles jnlpFiles, String filename, HttpServletRequest request, HttpServletResponse response) throws IOException { logger.debug("Send jar file " + filename); final File localFile = jnlpFiles.getJarFile(filename); if (localFile == null || !localFile.exists()) { response.sendError(HttpServletResponse.SC_NOT_FOUND, "Jar file '" + filename + "' not found."); return; } logger.debug("Actual file " + localFile.getAbsolutePath()); if (localFile.getName().endsWith(".jar")) { //response.setHeader(CONTENT_ENCODING, JAR_MIME_TYPE); response.setContentType(JAR_MIME_TYPE); } else if (localFile.getName().endsWith(".jar.pack.gz")) { response.setHeader(CONTENT_ENCODING, PACK200_GZIP_ENCODING); response.setContentType(PACK_MIME_TYPE); } // It is very improbable that a 64 bit jar is needed, but // it is better to be ready // response.setContentLength(Integer.parseInt(Long.toString(localFile.length()))); response.setHeader("Content-Length", Long.toString(localFile.length())); response.setDateHeader("Last-Modified", localFile.lastModified()); final FileInputStream fis = new FileInputStream(localFile); final ServletOutputStream os = response.getOutputStream(); try { // Transfer bytes from in to out final byte[] buf = new byte[4096]; int len; while ((len = fis.read(buf)) > 0) { os.write(buf, 0, len); } } catch (final IllegalStateException ex) { logger.debug(ex.getMessage()); } catch (final IOException ex) { logger.debug("Ignore IOException for '" + filename + "'"); } os.flush(); os.close(); fis.close(); }
From source file:net.sf.jsog.spring.JsogViewTest.java
@Test public void testRenderMergedOutputModelBean() throws Exception { // Setup// w w w .j a v a 2 s. c o m String encoding = "ISO-8859-1"; // Default encoding JSOG expected = JSOG.object("bean", JSOG.object().put("foo", "foovalue").put("bar", "barvalue")); MediaType contentType = MediaType.APPLICATION_JSON; // 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); instance.renderMergedOutputModel(model, request, response); // Verification verify(request, response, sos); 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 {//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:net.sf.jsog.spring.JsogViewTest.java
@Test public void testRenderMergedOutputModelCustomContentType() throws Exception { // Setup//from w ww . j a v a 2s .c om String encoding = "ISO-8859-1"; // Default encoding JSOG expected = new JSOG("foobar"); MediaType contentType = MediaType.TEXT_PLAIN; instance.setOutputContentType(contentType); // Setup the model Map<String, Object> model = new HashMap<String, Object>(); model.put("JSOG", expected); // 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); instance.renderMergedOutputModel(model, request, response); // Verification verify(request, response, sos); assertTrue(out.hasCaptured()); // Parse the resulting value JSOG actual = JSOG.parse(new String(out.getValue(), encoding)); assertEquals(actual, expected); }
From source file:org.codelabor.system.file.web.spring.controller.FileController.java
@RequestMapping("/view") public void view(@RequestParam("fileId") String fileId, HttpServletResponse response) throws Exception { StringBuilder stringBuilder = null; FileDTO fileDTO;/*from ww w .j av a 2 s . co m*/ fileDTO = fileManager.selectFileByFileId(fileId); logger.debug("fileDTO: {}", fileDTO); String repositoryPath = fileDTO.getRepositoryPath(); String uniqueFilename = fileDTO.getUniqueFilename(); String realFilename = fileDTO.getRealFilename(); InputStream inputStream = null; if (StringUtils.isNotEmpty(repositoryPath)) { // FILE_SYSTEM stringBuilder = new StringBuilder(); stringBuilder.append(repositoryPath); if (!repositoryPath.endsWith(File.separator)) { stringBuilder.append(File.separator); } stringBuilder.append(uniqueFilename); File file = new File(stringBuilder.toString()); inputStream = new FileInputStream(file); } else { // DATABASE byte[] bytes = new byte[] {}; if (fileDTO.getFileSize() > 0) { bytes = fileDTO.getBytes(); } inputStream = new ByteArrayInputStream(bytes); } response.setContentType(fileDTO.getContentType()); // set response contenttype, header String encodedRealFilename = URLEncoder.encode(realFilename, "UTF-8"); logger.debug("realFilename: {}", realFilename); logger.debug("encodedRealFilename: {}", encodedRealFilename); logger.debug("character encoding: {}", response.getCharacterEncoding()); logger.debug("content type: {}", response.getContentType()); logger.debug("bufferSize: {}", response.getBufferSize()); logger.debug("locale: {}", response.getLocale()); BufferedInputStream bufferdInputStream = new BufferedInputStream(inputStream); ServletOutputStream servletOutputStream = response.getOutputStream(); BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(servletOutputStream); int bytesRead; byte buffer[] = new byte[2048]; while ((bytesRead = bufferdInputStream.read(buffer)) != -1) { bufferedOutputStream.write(buffer, 0, bytesRead); } // flush stream bufferedOutputStream.flush(); // close stream inputStream.close(); bufferdInputStream.close(); servletOutputStream.close(); bufferedOutputStream.close(); }
From source file:net.sf.jsog.spring.JsogViewTest.java
@Test public void testRenderMergedOutputModel() throws Exception { // TODO: Make this test more robust // Setup//from w w w . j av a2 s . com String encoding = "ISO-8859-1"; // Default encoding JSOG expected = new JSOG("foobar"); MediaType contentType = MediaType.APPLICATION_JSON; // Setup the model Map<String, Object> model = new HashMap<String, Object>(); model.put("JSOG", expected); // 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); instance.renderMergedOutputModel(model, request, response); // Verification verify(request, response, sos); assertTrue(out.hasCaptured()); // Parse the resulting value JSOG actual = JSOG.parse(new String(out.getValue(), encoding)); assertEquals(actual, expected); }