List of usage examples for javax.servlet ServletOutputStream write
public void write(byte b[], int off, int len) throws IOException
len
bytes from the specified byte array starting at offset off
to this output stream. From source file:org.opencms.webdav.CmsWebdavServlet.java
/** * 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).<p> * * @param item the RepositoryItem// w w w .j av a 2 s . co m * @param is the input stream to copy from * @param ostream the output stream to write to * * @throws IOException if an input/output error occurs */ protected void copy(I_CmsRepositoryItem item, InputStream is, ServletOutputStream ostream) throws IOException { IOException exception = null; InputStream resourceInputStream = null; // Optimization: If the binary content has already been loaded, send // it directly if (!item.isCollection()) { byte[] buffer = item.getContent(); if (buffer != null) { ostream.write(buffer, 0, buffer.length); return; } resourceInputStream = new ByteArrayInputStream(item.getContent()); } else { resourceInputStream = is; } InputStream istream = new BufferedInputStream(resourceInputStream, m_input); // Copy the input stream to the output stream exception = copyRange(istream, ostream); // Clean up the input stream try { istream.close(); } catch (Exception e) { if (LOG.isErrorEnabled()) { LOG.error(Messages.get().getBundle().key(Messages.ERR_CLOSE_INPUT_STREAM_0), e); } } // Rethrow any exception that has occurred if (exception != null) { throw exception; } }
From source file:org.gss_project.gss.server.rest.Webdav.java
/** * 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).//w w w.j av a 2s.c o m * * @param istream The input stream to read from * @param ostream The output stream to write to * @param start Start of the range which will be copied * @param end End of the range which will be copied * @return Exception which occurred during processing */ private IOException copyRange(InputStream istream, ServletOutputStream ostream, long start, long end) { if (logger.isDebugEnabled()) logger.debug("Serving bytes:" + start + "-" + end); try { istream.skip(start); } catch (IOException e) { return e; } IOException exception = null; long bytesToRead = end - start + 1; byte buffer[] = new byte[input]; int len = buffer.length; while (bytesToRead > 0 && len >= buffer.length) { try { len = istream.read(buffer); if (bytesToRead >= len) { ostream.write(buffer, 0, len); bytesToRead -= len; } else { ostream.write(buffer, 0, (int) bytesToRead); bytesToRead = 0; } } catch (IOException e) { exception = e; len = -1; } if (len < buffer.length) break; } return exception; }
From source file:org.opencms.webdav.CmsWebdavServlet.java
/** * 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).<p> * * @param istream the input stream to read from * @param ostream the output stream to write to * @param start the start of the range which will be copied * @param end the end of the range which will be copied * /* w w w . j av a 2s. co m*/ * @return the exception which occurred during processing */ protected IOException copyRange(InputStream istream, ServletOutputStream ostream, long start, long end) { if (LOG.isDebugEnabled()) { LOG.debug(Messages.get().getBundle().key(Messages.LOG_SERVE_BYTES_2, new Long(start), new Long(end))); } try { istream.skip(start); } catch (IOException e) { return e; } IOException exception = null; long bytesToRead = (end - start) + 1; byte[] buffer = new byte[m_input]; int len = buffer.length; while ((bytesToRead > 0) && (len >= buffer.length)) { try { len = istream.read(buffer); if (bytesToRead >= len) { ostream.write(buffer, 0, len); bytesToRead -= len; } else { ostream.write(buffer, 0, (int) bytesToRead); bytesToRead = 0; } } catch (IOException e) { exception = e; len = -1; } if (len < buffer.length) { break; } } return exception; }
From source file:org.apache.ranger.biz.ServiceDBStore.java
public void getPoliciesInCSV(List<RangerPolicy> policies, HttpServletResponse response) throws Exception { if (LOG.isDebugEnabled()) { LOG.debug("==> ServiceDBStore.getPoliciesInCSV()"); }/*from w w w .jav a 2 s . c o m*/ InputStream in = null; ServletOutputStream out = null; String CSVFileName = null; try { String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); CSVFileName = "Ranger_Policies_" + timeStamp + ".csv"; out = response.getOutputStream(); StringBuffer sb = writeCSV(policies, CSVFileName, response); in = new ByteArrayInputStream(sb.toString().getBytes()); byte[] outputByte = new byte[sb.length()]; while (in.read(outputByte, 0, sb.length()) != -1) { out.write(outputByte, 0, sb.length()); } } catch (Exception e) { LOG.error("Error while generating report file " + CSVFileName, e); e.printStackTrace(); } finally { try { if (in != null) { in.close(); in = null; } } catch (Exception ex) { } try { if (out != null) { out.flush(); out.close(); } } catch (Exception ex) { } } }
From source file:ro.cs.ts.web.servlet.ReportServlet.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { logger.debug("doPost START"); ServletOutputStream sos = response.getOutputStream(); try {//retrieve the params from the context // *********************************************************************** //Servlet's OutputStream //get the report type String reportType = request.getParameter(IConstant.REPORT_TYPE); logger.debug("Report type: " + reportType); String uid = (String) request.getParameter(IConstant.REPORT_UID); logger.debug("Retrieved UID in report servlet: " + uid); Map<String, ReportParams> reportParamsMap = (Map<String, ReportParams>) TSContext .getFromContext(IConstant.REPORT_PARAM_MAP); ReportParams reportParams = reportParamsMap.get(uid); String format = (String) reportParams.getProperties() .get(IConstant.TS_PROJECT_REPORT_SEARCH_CRITERIA_FORMAT); // we set the is embeddable attribute if (format.toLowerCase().equals("html") && ServletRequestUtils.getBooleanParameters(request, ATTACHMENT) == null) { logger.debug("The report is HTML embeddable"); reportParams.setProperty(IConstant.TS_PROJECT_REPORT_IS_EMBEDDABLE, true); } else {/*from w ww . j a v a 2 s .c om*/ reportParams.setProperty(IConstant.TS_PROJECT_REPORT_IS_EMBEDDABLE, false); } logger.debug(ReportsMessageTools.viewReportParams(reportParams)); DataHandler reportFileReceived = null; String reportTitle = null; if (reportType.equals(IConstant.REPORT_TYPE_PROJECT)) { logger.debug("Retrieving project report: "); reportFileReceived = ReportsWebServiceClient.getInstance().getProjectReport(reportParams); reportTitle = (String) reportParams.getProperties() .get(IConstant.TS_PROJECT_REPORT_REPORT_TITLE_PARAM); } else if (reportType.equals(IConstant.REPORT_TYPE_TIME_SHEET)) { logger.debug("Retrieving time sheet report: "); reportFileReceived = ReportsWebServiceClient.getInstance().getTimeSheetReport(reportParams); reportTitle = (String) reportParams.getProperties() .get(IConstant.TS_TIME_SHEET_REPORT_REPORT_TITLE_PARAM); } else { logger.error("We do not have a report type on the request!!!!"); throw new BusinessException(ICodeException.REPORT_CREATE, null); } //set the response content type if (format.toLowerCase().equals("html")) { response.setContentType("text/html"); if (ServletRequestUtils.getBooleanParameters(request, ATTACHMENT) != null) { response.setHeader("Content-Disposition", "attachment; filename=\"".concat(reportTitle).concat(".html\"")); } else { response.setHeader("Content-Disposition", "inline; filename=\"".concat(reportTitle).concat(".html\"")); } } else if (format.toLowerCase().equals("pdf")) { response.setContentType("application/pdf"); response.setHeader("Content-Disposition", "inline; filename=\"".concat(reportTitle).concat(".pdf\"")); } else if (format.toLowerCase().equals("doc")) { response.setContentType("application/msword"); response.setHeader("Content-Disposition", "attachment; filename=\"".concat(reportTitle).concat(".doc\"")); } else if (format.toLowerCase().equals("xls")) { response.setContentType("application/vnd.ms-excel"); response.setHeader("Content-Disposition", "attachment; filename=\"".concat(reportTitle).concat(".xls\"")); } //write the received report bytes stream to response output stream byte buffer[] = new byte[4096]; BufferedInputStream bis = new BufferedInputStream(reportFileReceived.getInputStream()); int size = 0; int i; while ((i = bis.read(buffer, 0, 4096)) != -1) { sos.write(buffer, 0, i); size += i; } if (size == 0) { response.setContentType("text/plain"); sos.write("No content !".getBytes()); } bis.close(); response.setContentLength(size); logger.debug("**** report transfer completed !"); } catch (Exception ex) { logger.error("", ex); response.setContentType("text/html"); String exceptionCode = ICodeException.REPORT_CREATE; sos.write(("<html xmlns=\"http://www.w3.org/1999/xhtml\">" + "<head> <script type=\"text/javascript\" src=\"js/cs/cs_common.js\"></script>" + "<link rel=\"stylesheet\" type=\"text/css\" href=\"themes/standard/css/style.css\"/> " + "<link rel=\"stylesheet\" type=\"text/css\" href=\"themes/standard/css/yui/fonts-min.css\" /> " + "<link rel=\"stylesheet\" type=\"text/css\" href=\"themes/standard/css/yui/container.css\" /> </head> " + "<link rel=\"stylesheet\" type=\"text/css\" href=\"themes/standard/css/yui/button.css\" />" + "<body> <div id=\"errorsContainer\" class=\"errorMessagesDiv\"> " + "<table class=\"errorMessagesTable\">" + "<tr>" + "<td>" + "</td>" + "<td>" + "<div class=\"hd\">" + "<div id=\"closeErrors\" class=\"messagesCloseButon\"></div>" + "</div>" + "</td>" + "</tr>" + "<tr>" + "<td>" + "<div class=\"bd\">" + "<div style=\"width:470px\"> " + messageSource.getMessage(CREATE_ERROR, new Object[] { exceptionCode, ControllerUtils.getInstance().getFormattedCurrentTime() }, (Locale) request.getSession() .getAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME)) + "<br/> " + "</div>" + "</div>" + "</td>" + "<td>" + "</td>" + "</tr>" + "</table>" + "<div class=\"ft\"> </div>" + "</div>" + "<script> " + "if(typeof(YAHOO.widget.Module) != \"undefined\") { " + "YAHOO.ts.errorsContainer = new YAHOO.widget.Module(\"errorsContainer\", {visible:true} ); " + "YAHOO.ts.errorsContainer.render() ;" + "YAHOO.ts.errorsContainer.show();" + "YAHOO.util.Event.addListener(\"closeErrors\", \"click\", function () { " + "YAHOO.ts.errorsContainer.hide();" + "YAHOO.ts.errorsContainer.destroy(); " + "}, YAHOO.ts.errorsContainer, true);" + "}" + "</script> </body></html>").getBytes()); } finally { if (sos != null) { //Flushing and Closing OutputStream sos.flush(); sos.close(); logger.debug("**** servlet output stream closed."); } } logger.debug("doPost END"); }
From source file:gov.nih.nci.evs.browser.servlet.AjaxServlet.java
public void exportVSDToXMLAction(HttpServletRequest request, HttpServletResponse response) { String selectedvalueset = null; String multiplematches = HTTPUtils.cleanXSS((String) request.getParameter("multiplematches")); if (multiplematches != null) { selectedvalueset = HTTPUtils.cleanXSS((String) request.getParameter("valueset")); } else {// w w w. j a v a 2 s .c o m selectedvalueset = HTTPUtils.cleanXSS((String) request.getParameter("vsd_uri")); if (selectedvalueset != null && selectedvalueset.indexOf("|") != -1) { Vector u = DataUtils.parseData(selectedvalueset); selectedvalueset = (String) u.elementAt(1); } } String uri = selectedvalueset; request.getSession().setAttribute("selectedvalueset", uri); String xml_str = valueSetDefinition2XMLString(uri); try { response.setContentType("text/xml"); String vsd_name = DataUtils.valueSetDefiniionURI2Name(uri); vsd_name = vsd_name.replaceAll(" ", "_"); vsd_name = vsd_name + ".xml"; response.setHeader("Content-Disposition", "attachment; filename=" + vsd_name); response.setContentLength(xml_str.length()); ServletOutputStream ouputStream = response.getOutputStream(); ouputStream.write(xml_str.getBytes("UTF8"), 0, xml_str.length()); ouputStream.flush(); ouputStream.close(); } catch (IOException e) { e.printStackTrace(); } FacesContext.getCurrentInstance().responseComplete(); }
From source file:gov.nih.nci.evs.browser.servlet.AjaxServlet.java
public void export_mapping(HttpServletRequest request, HttpServletResponse response) { String mapping_schema = HTTPUtils.cleanXSS((String) request.getParameter("dictionary")); String mapping_version = HTTPUtils.cleanXSS((String) request.getParameter("version")); ResolvedConceptReferencesIterator iterator = DataUtils.getMappingDataIterator(mapping_schema, mapping_version);/*from w w w . j av a 2s . c om*/ int numRemaining = 0; if (iterator != null) { try { numRemaining = iterator.numberRemaining(); //System.out.println("number of records: " + numRemaining); } catch (Exception ex) { ex.printStackTrace(); } } StringBuffer sb = new StringBuffer(); try { sb.append("Source Code,"); sb.append("Source Name,"); sb.append("Source Coding Scheme,"); sb.append("Source Coding Scheme Version,"); sb.append("Source Coding Scheme Namespace,"); sb.append("Association Name,"); sb.append("REL,"); sb.append("Map Rank,"); sb.append("Target Code,"); sb.append("Target Name,"); sb.append("Target Coding Scheme,"); sb.append("Target Coding Scheme Version,"); sb.append("Target Coding Scheme Namespace"); sb.append("\r\n"); MappingIteratorBean bean = new MappingIteratorBean(iterator); List list = bean.getData(0, numRemaining - 1); for (int k = 0; k < list.size(); k++) { MappingData mappingData = (MappingData) list.get(k); sb.append("\"" + mappingData.getSourceCode() + "\","); sb.append("\"" + mappingData.getSourceName() + "\","); sb.append("\"" + mappingData.getSourceCodingScheme() + "\","); sb.append("\"" + mappingData.getSourceCodingSchemeVersion() + "\","); sb.append("\"" + mappingData.getSourceCodeNamespace() + "\","); sb.append("\"" + mappingData.getAssociationName() + "\","); sb.append("\"" + mappingData.getRel() + "\","); sb.append("\"" + mappingData.getScore() + "\","); sb.append("\"" + mappingData.getTargetCode() + "\","); sb.append("\"" + mappingData.getTargetName() + "\","); sb.append("\"" + mappingData.getTargetCodingScheme() + "\","); sb.append("\"" + mappingData.getTargetCodingSchemeVersion() + "\","); sb.append("\"" + mappingData.getTargetCodeNamespace() + "\""); sb.append("\r\n"); } } catch (Exception ex) { sb.append("WARNING: Export to CVS action failed."); ex.printStackTrace(); } String filename = mapping_schema + "_" + mapping_version; filename = filename.replaceAll(" ", "_"); filename = filename + ".csv"; response.setContentType("text/csv"); response.setHeader("Content-Disposition", "attachment; filename=" + filename); response.setContentLength(sb.length()); try { ServletOutputStream ouputStream = response.getOutputStream(); ouputStream.write(sb.toString().getBytes("UTF-8"), 0, sb.length()); ouputStream.flush(); ouputStream.close(); } catch (Exception ex) { ex.printStackTrace(); sb.append("WARNING: Export to CVS action failed."); } FacesContext.getCurrentInstance().responseComplete(); return; }
From source file:org.etudes.jforum.view.admin.ImportExportAction.java
/** * writes the zip file to browser//from ww w . ja va2 s . c o m * * @param file * - zip file to download * @throws Exception */ private void download(File file) throws Exception { FileInputStream fis = null; ServletOutputStream out = null; try { String disposition = "attachment; filename=\"" + file.getName() + "\""; fis = new FileInputStream(file); response.setContentType("application/zip"); // application/zip response.addHeader("Content-Disposition", disposition); out = response.getOutputStream(); int len; byte buf[] = new byte[102400]; while ((len = fis.read(buf)) > 0) { out.write(buf, 0, len); } out.flush(); } catch (IOException e) { throw e; } finally { try { if (out != null) out.close(); } catch (IOException e1) { } try { if (fis != null) fis.close(); } catch (IOException e2) { } } }
From source file:com.founder.fix.fixflow.FlowCenter.java
/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response)/*from w w w . jav a2s. co m*/ */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String userId = StringUtil.getString(request.getSession().getAttribute(FlowCenterService.LOGIN_USER_ID)); if (StringUtil.isEmpty(userId)) { String context = request.getContextPath(); response.sendRedirect(context + "/"); return; } CurrentThread.init(); ServletOutputStream out = null; String action = StringUtil.getString(request.getParameter("action")); if (StringUtil.isEmpty(action)) { action = StringUtil.getString(request.getAttribute("action")); } if (StringUtil.isEmpty(action)) { action = "getMyTask"; } RequestDispatcher rd = null; try { Map<String, Object> filter = new HashMap<String, Object>(); if (ServletFileUpload.isMultipartContent(request)) { ServletFileUpload Uploader = new ServletFileUpload(new DiskFileItemFactory()); // Uploader.setSizeMax("); // Uploader.setHeaderEncoding("utf-8"); List<FileItem> fileItems = Uploader.parseRequest(request); for (FileItem item : fileItems) { filter.put(item.getFieldName(), item); if (item.getFieldName().equals("action")) action = item.getString(); } } else { Enumeration enu = request.getParameterNames(); while (enu.hasMoreElements()) { Object tmp = enu.nextElement(); Object obj = request.getParameter(StringUtil.getString(tmp)); // if (request.getAttribute("ISGET") != null) obj = new String(obj.toString().getBytes("ISO8859-1"), "utf-8"); filter.put(StringUtil.getString(tmp), obj); } } Enumeration attenums = request.getAttributeNames(); while (attenums.hasMoreElements()) { String paramName = (String) attenums.nextElement(); Object paramValue = request.getAttribute(paramName); // ?map filter.put(paramName, paramValue); } filter.put("userId", userId); request.setAttribute("nowAction", action); if (action.equals("getMyProcess")) { rd = request.getRequestDispatcher("/fixflow/center/startTask.jsp"); List<Map<String, String>> result = getFlowCenter().queryStartProcess(userId); Map<String, List<Map<String, String>>> newResult = new HashMap<String, List<Map<String, String>>>(); for (Map<String, String> tmp : result) { String category = tmp.get("category"); if (StringUtil.isEmpty(category)) category = ""; List<Map<String, String>> tlist = newResult.get(category); if (tlist == null) { tlist = new ArrayList<Map<String, String>>(); } tlist.add(tmp); newResult.put(category, tlist); } request.setAttribute("result", newResult); //??sqlserverbug???? request.setAttribute("userId", userId); // userId add Rex try { List<Map<String, String>> lastestProcess = getFlowCenter().queryLastestProcess(userId); request.setAttribute("lastest", lastestProcess); } catch (Exception ex) { ex.printStackTrace(); } } else if (action.equals("getMyTask")) { rd = request.getRequestDispatcher("/fixflow/center/todoTask.jsp"); filter.put("path", request.getSession().getServletContext().getRealPath("/")); Map<String, Object> pageResult = getFlowCenter().queryMyTaskNotEnd(filter); filter.putAll(pageResult); request.setAttribute("result", filter); request.setAttribute("pageInfo", filter.get("pageInfo")); } else if (action.equals("getProcessImage")) { response.getOutputStream(); } else if (action.equals("getAllProcess")) { rd = request.getRequestDispatcher("/fixflow/center/queryprocess.jsp"); Map<String, Object> pageResult = getFlowCenter().queryTaskInitiator(filter); filter.putAll(pageResult); request.setAttribute("result", filter); request.setAttribute("pageInfo", filter.get("pageInfo")); } else if (action.equals("getPlaceOnFile")) { rd = request.getRequestDispatcher("/fixflow/center/placeOnFile.jsp"); Map<String, Object> pageResult = getFlowCenter().queryPlaceOnFile(filter); filter.putAll(pageResult); request.setAttribute("result", filter); request.setAttribute("pageInfo", filter.get("pageInfo")); } else if (action.equals("getTaskDetailInfo")) { rd = request.getRequestDispatcher("/fixflow/center/flowGraphic.jsp"); Map<String, Object> pageResult = getFlowCenter().getTaskDetailInfo(filter); filter.putAll(pageResult); request.setAttribute("result", filter); } else if (action.equals("getTaskDetailInfoSVG")) { rd = request.getRequestDispatcher("/fixflow/center/flowGraphic.jsp"); Map<String, Object> pageResult = getFlowCenter().getTaskDetailInfoSVG(filter); filter.putAll(pageResult); request.setAttribute("result", filter); } else if (action.equals("getFlowGraph")) { InputStream is = getFlowCenter().getFlowGraph(filter); out = response.getOutputStream(); response.setContentType("application/octet-stream;charset=UTF-8"); byte[] buff = new byte[2048]; int size = 0; while (is != null && (size = is.read(buff)) != -1) { out.write(buff, 0, size); } } else if (action.equals("getUserInfo")) { rd = request.getRequestDispatcher("/fixflow/common/userInfo.jsp"); filter.put("path", request.getSession().getServletContext().getRealPath("/")); Map<String, Object> pageResult = getFlowCenter().getUserInfo(filter); filter.putAll(pageResult); request.setAttribute("result", filter); } else if (action.equals("getUserIcon")) { rd = request.getRequestDispatcher("/fixflow/common/userOperation.jsp"); filter.put("path", request.getSession().getServletContext().getRealPath("/")); Map<String, Object> pageResult = getFlowCenter().getUserInfo(filter); filter.putAll(pageResult); request.setAttribute("result", filter); } else if (action.equals("updateUserIcon")) { rd = request.getRequestDispatcher("/FlowCenter?action=getUserInfo"); filter.put("path", request.getSession().getServletContext().getRealPath("/")); getFlowCenter().saveUserIcon(filter); } else if (action.equals("selectUserList")) { // String isMulti = request.getParameter("isMulti"); rd = request.getRequestDispatcher("/fixflow/common/selectUserList.jsp?isMulti=" + isMulti); Map<String, Object> pageResult = getFlowCenter().getAllUsers(filter); filter.putAll(pageResult); request.setAttribute("result", filter); request.setAttribute("isMulti", isMulti); request.setAttribute("pageInfo", filter.get("pageInfo")); } else if (action.equals("selectNodeList")) { // rd = request.getRequestDispatcher("/fixflow/common/selectNodeList.jsp"); Map<String, Object> pageResult = getFlowCenter().getRollbackNode(filter); filter.putAll(pageResult); request.setAttribute("result", filter); } else if (action.equals("selectStepList")) { // rd = request.getRequestDispatcher("/fixflow/common/selectStepList.jsp"); Map<String, Object> pageResult = getFlowCenter().getRollbackTask(filter); filter.putAll(pageResult); request.setAttribute("result", filter); } else if (action.equals("viewDelegation")) { // rd = request.getRequestDispatcher("/fixflow/common/setDelegation.jsp"); Map<String, Object> pageResult = new HashMap<String, Object>(); pageResult = this.getFlowIdentityService().getUserDelegationInfo(userId); filter.putAll(pageResult); request.setAttribute("result", filter); } else if (action.equals("saveDelegation")) { // String agentInfoJson = StringUtil.getString(request.getParameter("insertAndUpdate")); if (StringUtil.isNotEmpty(agentInfoJson)) { Map<String, Object> delegationInfo = JSONUtil.parseJSON2Map(agentInfoJson); this.getFlowIdentityService().saveUserDelegationInfo(delegationInfo); } response.setContentType("text/html;charset=UTF-8"); response.getWriter().write("<script>alert('??');window.close();</script>"); } } catch (Exception e) { e.printStackTrace(); request.setAttribute("errorMsg", e.getMessage()); try { CurrentThread.rollBack(); } catch (SQLException e1) { e1.printStackTrace(); request.setAttribute("errorMsg", e.getMessage()); } } finally { if (out != null) { out.flush(); out.close(); } try { CurrentThread.clear(); } catch (SQLException e) { request.setAttribute("errorMsg", e.getMessage()); e.printStackTrace(); } } if (rd != null) { rd.forward(request, response); } }
From source file:org.joget.apps.app.controller.ConsoleWebController.java
@RequestMapping("/console/monitor/log/(*:fileName)") public void consoleMonitorLogs(HttpServletResponse response, @RequestParam("fileName") String fileName) throws IOException { if (HostManager.isVirtualHostEnabled()) { response.sendError(HttpServletResponse.SC_FORBIDDEN); return;/*from ww w . jav a 2s . c o m*/ } ServletOutputStream stream = response.getOutputStream(); String decodedFileName = fileName; try { decodedFileName = URLDecoder.decode(fileName, "UTF8"); } catch (UnsupportedEncodingException e) { // ignore } File file = LogUtil.getTomcatLogFile(decodedFileName); if (file == null || file.isDirectory() || !file.exists()) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } DataInputStream in = new DataInputStream(new FileInputStream(file)); byte[] bbuf = new byte[65536]; try { // set attachment filename response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + URLEncoder.encode(decodedFileName, "UTF8")); // send output int length = 0; while ((in != null) && ((length = in.read(bbuf)) != -1)) { stream.write(bbuf, 0, length); } } finally { in.close(); stream.flush(); stream.close(); } }