List of usage examples for javax.servlet.http HttpServletResponse reset
public void reset();
From source file:org.messic.server.facade.controllers.rest.SongController.java
@ApiMethod(path = "/services/songs/{songSid}/audio", verb = ApiVerb.GET, description = "Get the audio binary from a song resource of an album", produces = { MediaType.APPLICATION_OCTET_STREAM_VALUE }) @ApiErrors(apierrors = { @ApiError(code = UnknownMessicRESTException.VALUE, description = "Unknown error"), @ApiError(code = NotAuthorizedMessicRESTException.VALUE, description = "Forbidden access"), @ApiError(code = IOMessicRESTException.VALUE, description = "IO error trying to get the audio resource") }) @RequestMapping(value = "/{songSid}/audio", method = { RequestMethod.GET, RequestMethod.HEAD }) @ResponseStatus(HttpStatus.OK)/*www . j a v a2 s .co m*/ public void getSongWithRanges( @ApiParam(name = "songSid", description = "SID of the song resource we want to download", paramType = ApiParamType.PATH, required = true) @PathVariable Long songSid, HttpServletRequest request, HttpServletResponse response) throws NotAuthorizedMessicRESTException, IOMessicRESTException, UnknownMessicRESTException { User user = SecurityUtil.getCurrentUser(); try { //http://balusc.blogspot.com.es/2009/02/fileservlet-supporting-resume-and.html // Whether the request body should be written (GET) or not (HEAD). boolean content = request.getMethod().equalsIgnoreCase("GET"); APISong.AudioSongStream ass = songAPI.getAudioSong(user, songSid); // Validate and process Range and If-Range headers. String eTag = songSid + "_" + ass.contentLength + "_" + ass.lastModified; long expires = System.currentTimeMillis() + Range.DEFAULT_EXPIRE_TIME; // Validate request headers for caching --------------------------------------------------- // If-None-Match header should contain "*" or ETag. If so, then return 304. String ifNoneMatch = request.getHeader("If-None-Match"); if (ifNoneMatch != null && Range.matches(ifNoneMatch, eTag)) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); response.setHeader("ETag", eTag); // Required in 304. response.setDateHeader("Expires", expires); // Postpone cache with 1 week. return; } // If-Modified-Since header should be greater than LastModified. If so, then return 304. // This header is ignored if any If-None-Match header is specified. long ifModifiedSince = request.getDateHeader("If-Modified-Since"); if (ifNoneMatch == null && ifModifiedSince != -1 && ifModifiedSince + 1000 > ass.lastModified) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); response.setHeader("ETag", eTag); // Required in 304. response.setDateHeader("Expires", expires); // Postpone cache with 1 week. return; } // Validate request headers for resume ---------------------------------------------------- // If-Match header should contain "*" or ETag. If not, then return 412. String ifMatch = request.getHeader("If-Match"); if (ifMatch != null && !Range.matches(ifMatch, eTag)) { response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); return; } // If-Unmodified-Since header should be greater than LastModified. If not, then return 412. long ifUnmodifiedSince = request.getDateHeader("If-Unmodified-Since"); if (ifUnmodifiedSince != -1 && ifUnmodifiedSince + 1000 <= ass.lastModified) { response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); return; } // Validate and process range ------------------------------------------------------------- // Prepare some variables. The full Range represents the complete file. Range full = new Range(0, ass.contentLength - 1, ass.contentLength); List<Range> ranges = new ArrayList<Range>(); String range = request.getHeader("Range"); if (range != null) { // Range header should match format "bytes=n-n,n-n,n-n...". If not, then return 416. if (!range.matches("^bytes=\\d*-\\d*(,\\d*-\\d*)*$")) { response.setHeader("Content-Range", "bytes */" + ass.contentLength); // Required in 416. response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); return; } // If-Range header should either match ETag or be greater then LastModified. If not, // then return full file. String ifRange = request.getHeader("If-Range"); if (ifRange != null && !ifRange.equals(eTag)) { try { long ifRangeTime = request.getDateHeader("If-Range"); // Throws IAE if invalid. if (ifRangeTime != -1 && ifRangeTime + 1000 < ass.lastModified) { ranges.add(full); } } catch (IllegalArgumentException ignore) { ranges.add(full); } } // If any valid If-Range header, then process each part of byte range. if (ranges.isEmpty()) { for (String part : range.substring(6).split(",")) { // Assuming a file with length of 100, the following examples returns bytes at: // 50-80 (50 to 80), 40- (40 to length=100), -20 (length-20=80 to length=100). long start = Range.sublong(part, 0, part.indexOf("-")); long end = Range.sublong(part, part.indexOf("-") + 1, part.length()); if (start == -1) { start = ass.contentLength - end; end = ass.contentLength - 1; } else if (end == -1 || end > ass.contentLength - 1) { end = ass.contentLength - 1; } // Check if Range is syntactically valid. If not, then return 416. if (start > end) { response.setHeader("Content-Range", "bytes */" + ass.contentLength); // Required in 416. response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); return; } // Add range. ranges.add(new Range(start, end, ass.contentLength)); } } } // Prepare and initialize response -------------------------------------------------------- // Get content type by file name and set default GZIP support and content disposition. String contentType = "audio/mpeg"; boolean acceptsGzip = false; String disposition = "inline"; // // If content type is unknown, then set the default value. // // For all content types, see: http://www.w3schools.com/media/media_mimeref.asp // // To add new content types, add new mime-mapping entry in web.xml. // if ( contentType == null ) // { // contentType = "application/octet-stream"; // } // If content type is text, then determine whether GZIP content encoding is supported by // the browser and expand content type with the one and right character encoding. if (contentType.startsWith("text")) { String acceptEncoding = request.getHeader("Accept-Encoding"); acceptsGzip = acceptEncoding != null && Range.accepts(acceptEncoding, "gzip"); contentType += ";charset=UTF-8"; } // Else, expect for images, determine content disposition. If content type is supported by // the browser, then set to inline, else attachment which will pop a 'save as' dialogue. else if (!contentType.startsWith("image")) { String accept = request.getHeader("Accept"); disposition = accept != null && Range.accepts(accept, contentType) ? "inline" : "attachment"; } // Initialize response. response.reset(); response.setBufferSize(Range.DEFAULT_BUFFER_SIZE); response.setHeader("Content-Disposition", disposition + ";filename=\"" + ass.songFileName + "\""); response.setHeader("Accept-Ranges", "bytes"); response.setHeader("ETag", eTag); response.setDateHeader("Last-Modified", ass.lastModified); response.setDateHeader("Expires", expires); // Send requested file (part(s)) to client ------------------------------------------------ // Prepare streams. OutputStream output = null; try { // Open streams. output = response.getOutputStream(); if (ranges.isEmpty() || ranges.get(0) == full) { // Return full file. Range r = full; response.setContentType(contentType); response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total); if (content) { if (acceptsGzip) { // The browser accepts GZIP, so GZIP the content. response.setHeader("Content-Encoding", "gzip"); output = new GZIPOutputStream(output, Range.DEFAULT_BUFFER_SIZE); } else { // Content length is not directly predictable in case of GZIP. // So only add it if there is no means of GZIP, else browser will hang. response.setHeader("Content-Length", String.valueOf(r.length)); } // Copy full range. Range.copy(ass.raf, output, r.start, r.length); } } else if (ranges.size() == 1) { // Return single part of file. Range r = ranges.get(0); response.setContentType(contentType); response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total); response.setHeader("Content-Length", String.valueOf(r.length)); response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206. if (content) { // Copy single part range. Range.copy(ass.raf, output, r.start, r.length); } } else { // Return multiple parts of file. response.setContentType("multipart/byteranges; boundary=" + Range.MULTIPART_BOUNDARY); response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206. if (content) { // Cast back to ServletOutputStream to get the easy println methods. ServletOutputStream sos = (ServletOutputStream) output; // Copy multi part range. for (Range r : ranges) { // Add multipart boundary and header fields for every range. sos.println(); sos.println("--" + Range.MULTIPART_BOUNDARY); sos.println("Content-Type: " + contentType); sos.println("Content-Range: bytes " + r.start + "-" + r.end + "/" + r.total); // Copy single part range of multi part range. Range.copy(ass.raf, output, r.start, r.length); } // End with multipart boundary. sos.println(); sos.println("--" + Range.MULTIPART_BOUNDARY + "--"); } } } finally { // Gently close streams. Range.close(output); Range.close(ass.is); Range.close(ass.raf); } return; } catch (IOException ioe) { log.error("failed!", ioe); throw new IOMessicRESTException(ioe); } catch (Exception e) { throw new UnknownMessicRESTException(e); } }
From source file:com.founder.fix.fixflow.FlowManager.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { CurrentThread.init();//from w w w . j a v a 2 s .c o m String userId = StringUtil.getString(request.getSession().getAttribute(FlowCenterService.LOGIN_USER_ID)); if (StringUtil.isEmpty(userId)) { String context = request.getContextPath(); response.sendRedirect(context + "/"); return; } ServletOutputStream out = null; String action = StringUtil.getString(request.getParameter("action")); if (StringUtil.isEmpty(action)) { action = StringUtil.getString(request.getAttribute("action")); } 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(); if (item.getFieldName().equals("deploymentId")) { filter.put("deploymentId", 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 ("processDefinitionList".equals(action)) { rd = request.getRequestDispatcher("/fixflow/manager/processDefinitionList.jsp"); Map<String, Object> result = getProcessDefinitionService().getProcessDefitionList(filter); filter.putAll(result); request.setAttribute("result", filter); request.setAttribute("pageInfo", filter.get("pageInfo")); } else if (action.equals("processManageList")) { rd = request.getRequestDispatcher("/fixflow/manager/processInstanceList.jsp"); Map<String, Object> result = getFlowManager().getProcessInstances(filter); filter.putAll(result); request.setAttribute("result", filter); request.setAttribute("pageInfo", filter.get("pageInfo")); } else if (action.equals("suspendProcessInstance")) { rd = request.getRequestDispatcher("/FlowManager?action=processManageList"); getFlowManager().suspendProcessInstance(filter); } else if (action.equals("continueProcessInstance")) { rd = request.getRequestDispatcher("/FlowManager?action=processManageList"); getFlowManager().continueProcessInstance(filter); } else if (action.equals("terminatProcessInstance")) { rd = request.getRequestDispatcher("/FlowManager?action=processManageList"); getFlowManager().terminatProcessInstance(filter); } else if (action.equals("deleteProcessInstance")) { rd = request.getRequestDispatcher("/FlowManager?action=processManageList"); getFlowManager().deleteProcessInstance(filter); } else if (action.equals("toProcessVariable")) { rd = request.getRequestDispatcher("/fixflow/manager/processVariableList.jsp"); Map<String, Object> result = getFlowManager().getProcessVariables(filter); filter.putAll(result); request.setAttribute("result", filter); } else if (action.equals("saveProcessVariables")) { String tmp = (String) filter.get("insertAndUpdate"); if (StringUtil.isNotEmpty(tmp)) { Map<String, Object> tMap = JSONUtil.parseJSON2Map(tmp); filter.put("insertAndUpdate", tMap); } getFlowManager().saveProcessVariables(filter); rd = request.getRequestDispatcher("/FlowManager?action=toProcessVariable"); } else if (action.equals("processTokenList")) { Map<String, Object> result = getFlowManager().getProcessTokens(filter); filter.putAll(result); request.setAttribute("result", filter); rd = request.getRequestDispatcher("/fixflow/manager/processTokenList.jsp"); } else if (action.equals("taskInstanceList")) { rd = request.getRequestDispatcher("/fixflow/manager/taskInstanceList.jsp"); filter.put("path", request.getSession().getServletContext().getRealPath("/")); Map<String, Object> pageResult = getTaskManager().getTaskList(filter); filter.putAll(pageResult); request.setAttribute("result", filter); request.setAttribute("pageInfo", filter.get("pageInfo")); } else if (action.equals("doTaskSuspend")) { rd = request.getRequestDispatcher("/FlowManager?action=taskInstanceList"); getTaskManager().suspendTask(filter); } else if (action.equals("doTaskResume")) { rd = request.getRequestDispatcher("/FlowManager?action=taskInstanceList"); getTaskManager().resumeTask(filter); } else if (action.equals("doTaskTransfer")) { rd = request.getRequestDispatcher("/FlowManager?action=taskInstanceList"); getTaskManager().transferTask(filter); } else if (action.equals("doTaskRollBackNode")) { rd = request.getRequestDispatcher("/FlowManager?action=taskInstanceList"); getTaskManager().rollBackNode(filter); } else if (action.equals("doTaskRollBackTask")) { rd = request.getRequestDispatcher("/FlowManager?action=taskInstanceList"); getTaskManager().rollBackStep(filter); } else if (action.equals("flowLibrary")) { rd = request.getRequestDispatcher("/fixflow-explorer/flowLibrary.jsp"); } //???deploymentId if ("deploy".equals(action)) { rd = request.getRequestDispatcher("/FlowManager?action=processDefinitionList"); response.setContentType("text/html;charset=utf-8"); getProcessDefinitionService().deployByZip(filter); } else if ("deleteDeploy".equals(action)) { rd = request.getRequestDispatcher("/FlowManager?action=processDefinitionList"); getProcessDefinitionService().deleteDeploy(filter); } else if ("download".equals(action)) { String processDefinitionId = StringUtil.getString(filter.get("processDefinitionId")); response.reset(); request.setCharacterEncoding("gbk"); response.setContentType("applcation/octet-stream"); response.setHeader("Content-disposition", "attachment; filename=" + processDefinitionId + ".zip"); response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0,private, max-age=0"); response.setHeader("Content-Type", "application/octet-stream"); response.setHeader("Content-Type", "application/force-download"); response.setHeader("Pragma", "public"); response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0"); ZipOutputStream outZip = new ZipOutputStream(response.getOutputStream()); List<Map<String, Object>> fileList = getProcessDefinitionService().getResources(filter); for (Map<String, Object> file : fileList) { ZipEntry entry = new ZipEntry(file.get("FILENAME").toString()); entry.setSize(((byte[]) file.get("BYTES")).length); outZip.putNextEntry(entry); outZip.write((byte[]) file.get("BYTES")); outZip.closeEntry(); } outZip.close(); outZip.flush(); outZip.close(); } else if ("getUserList".equals(action)) { rd = request.getRequestDispatcher("/fixflow/manager/userList.jsp"); request.setAttribute("nowAction", "UserGroup"); Map<String, Object> result = getUserGroupService().getAllUsers(filter); filter.putAll(result); request.setAttribute("result", filter); List<Map<String, Object>> groupList = getUserGroupService().getAllGroupDefinition(filter); request.setAttribute("groupList", groupList); request.setAttribute("pageInfo", filter.get("pageInfo")); } else if ("getGroupList".equals(action)) { rd = request.getRequestDispatcher("/fixflow/manager/groupList.jsp"); request.setAttribute("nowAction", "UserGroup"); Map<String, Object> result = getUserGroupService().getAllGroup(filter); filter.putAll(result); request.setAttribute("result", filter); List<Map<String, Object>> groupList = getUserGroupService().getAllGroupDefinition(filter); request.setAttribute("groupList", groupList); request.setAttribute("pageInfo", filter.get("pageInfo")); } else if ("getUserInfo".equals(action)) { rd = request.getRequestDispatcher("/fixflow/manager/userInfo.jsp"); Map<String, Object> pageResult = getUserGroupService().getUserInfo(filter); filter.putAll(pageResult); request.setAttribute("result", filter); } else if ("getGroupInfo".equals(action)) { rd = request.getRequestDispatcher("/fixflow/manager/groupInfo.jsp"); Map<String, Object> pageResult = getUserGroupService().getGroupInfo(filter); filter.putAll(pageResult); request.setAttribute("result", filter); } else if ("getJobList".equals(action)) { rd = request.getRequestDispatcher("/fixflow/manager/jobList.jsp"); request.setAttribute("nowAction", "jobManager"); Map<String, Object> result = getJobService().getJobList(filter); filter.putAll(result); request.setAttribute("result", filter); } else if ("viewJobInfo".equals(action)) { rd = request.getRequestDispatcher("/fixflow/manager/jobInfo.jsp"); request.setAttribute("nowAction", "jobManager"); Map<String, Object> result = getJobService().getJobTrigger(filter); filter.putAll(result); request.setAttribute("result", filter); } else if ("suspendJob".equals(action)) { rd = request.getRequestDispatcher("/fixflow/manager/jobList.jsp"); request.setAttribute("nowAction", "jobManager"); getJobService().suspendJob(filter); Map<String, Object> result = getJobService().getJobList(filter); filter.putAll(result); request.setAttribute("result", filter); } else if ("continueJob".equals(action)) { rd = request.getRequestDispatcher("/fixflow/manager/jobList.jsp"); getJobService().continueJob(filter); request.setAttribute("nowAction", "jobManager"); Map<String, Object> result = getJobService().getJobList(filter); filter.putAll(result); request.setAttribute("result", filter); } else if ("suspendTrigger".equals(action)) { rd = request.getRequestDispatcher("/fixflow/manager/jobInfo.jsp"); getJobService().suspendTrigger(filter); request.setAttribute("nowAction", "jobManager"); Map<String, Object> result = getJobService().getJobTrigger(filter); filter.putAll(result); request.setAttribute("result", filter); } else if ("continueTrigger".equals(action)) { rd = request.getRequestDispatcher("/fixflow/manager/jobInfo.jsp"); getJobService().continueTrigger(filter); request.setAttribute("nowAction", "jobManager"); Map<String, Object> result = getJobService().getJobTrigger(filter); filter.putAll(result); request.setAttribute("result", filter); } else if ("setHis".equals(action)) { rd = request.getRequestDispatcher("/FlowManager?action=processManageList"); getFlowManager().setHistory(filter); } else if ("updateCache".equals(action)) { ProcessEngineManagement.getDefaultProcessEngine().cleanCache(true, true); response.getWriter().write("update success!"); } } 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) { e.printStackTrace(); request.setAttribute("errorMsg", e.getMessage()); } } if (rd != null) rd.forward(request, response); }
From source file:org.jahia.services.content.files.StaticFileServlet.java
/** * Process the actual request./* w w w .j ava 2s.c om*/ * * @param request The request to be processed. * @param response The response to be created. * @param content Whether the request body should be written (GET) or not (HEAD). * @throws IOException If something fails at I/O level. */ private void processRequest(HttpServletRequest request, HttpServletResponse response, boolean content) throws IOException { // Validate the requested file ------------------------------------------------------------ // Get requested file by path info. String requestedFile = request.getPathInfo(); // Check if file is actually supplied to the request URL. if (requestedFile == null) { // Do your thing if the file is not supplied to the request URL. // Throw an exception, or send 404, or show default/warning page, or just ignore it. response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // URL-decode the file name (might contain spaces and on) and prepare file object. File file = new File(basePath, URLDecoder.decode(requestedFile, "UTF-8")); // Check if file actually exists in filesystem. if (!file.exists() || !file.isFile()) { // Do your thing if the file appears to be non-existing. // Throw an exception, or send 404, or show default/warning page, or just ignore it. response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // Verify the file requested is a descendant of the base directory. if (!file.getCanonicalPath().startsWith(basePath)) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // Prepare some variables. The ETag is an unique identifier of the file. String fileName = file.getName(); long length = file.length(); long lastModified = file.lastModified(); String eTag = fileName + "_" + length + "_" + lastModified; long expires = System.currentTimeMillis() + DEFAULT_EXPIRE_TIME; // Validate request headers for caching --------------------------------------------------- // If-None-Match header should contain "*" or ETag. If so, then return 304. String ifNoneMatch = request.getHeader("If-None-Match"); if (ifNoneMatch != null && matches(ifNoneMatch, eTag)) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); response.setHeader("ETag", eTag); // Required in 304. response.setDateHeader("Expires", expires); // Postpone cache with 1 week. return; } // If-Modified-Since header should be greater than LastModified. If so, then return 304. // This header is ignored if any If-None-Match header is specified. long ifModifiedSince = request.getDateHeader("If-Modified-Since"); if (ifNoneMatch == null && ifModifiedSince != -1 && ifModifiedSince + 1000 > lastModified) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); response.setHeader("ETag", eTag); // Required in 304. response.setDateHeader("Expires", expires); // Postpone cache with 1 week. return; } // Validate request headers for resume ---------------------------------------------------- // If-Match header should contain "*" or ETag. If not, then return 412. String ifMatch = request.getHeader("If-Match"); if (ifMatch != null && !matches(ifMatch, eTag)) { response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); return; } // If-Unmodified-Since header should be greater than LastModified. If not, then return 412. long ifUnmodifiedSince = request.getDateHeader("If-Unmodified-Since"); if (ifUnmodifiedSince != -1 && ifUnmodifiedSince + 1000 <= lastModified) { response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); return; } // Validate and process range ------------------------------------------------------------- // Prepare some variables. The full Range represents the complete file. Range full = new Range(0, length - 1, length); List<Range> ranges = new ArrayList<Range>(); // Validate and process Range and If-Range headers. String range = request.getHeader("Range"); if (range != null) { // Range header should match format "bytes=n-n,n-n,n-n...". If not, then return 416. if (!PATTERN_RANGE.matcher(range).matches()) { response.setHeader("Content-Range", "bytes */" + length); // Required in 416. response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); return; } // If-Range header should either match ETag or be greater then LastModified. If not, // then return full file. String ifRange = request.getHeader("If-Range"); if (ifRange != null && !ifRange.equals(eTag)) { try { long ifRangeTime = request.getDateHeader("If-Range"); // Throws IAE if invalid. if (ifRangeTime != -1 && ifRangeTime + 1000 < lastModified) { ranges.add(full); } } catch (IllegalArgumentException ignore) { ranges.add(full); } } // If any valid If-Range header, then process each part of byte range. if (ranges.isEmpty()) { for (String part : Patterns.COMMA.split(range.substring(6))) { // Assuming a file with length of 100, the following examples returns bytes at: // 50-80 (50 to 80), 40- (40 to length=100), -20 (length-20=80 to length=100). long start = sublong(part, 0, part.indexOf("-")); long end = sublong(part, part.indexOf("-") + 1, part.length()); if (start == -1) { start = length - end; end = length - 1; } else if (end == -1 || end > length - 1) { end = length - 1; } // Check if Range is syntactically valid. If not, then return 416. if (start > end) { response.setHeader("Content-Range", "bytes */" + length); // Required in 416. response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); return; } // Add range. ranges.add(new Range(start, end, length)); } } } // Prepare and initialize response -------------------------------------------------------- // Get content type by file name and set default GZIP support and content disposition. String contentType = getServletContext().getMimeType(fileName); boolean acceptsGzip = false; String disposition = "inline"; // If content type is unknown, then set the default value. // For all content types, see: http://www.w3schools.com/media/media_mimeref.asp // To add new content types, add new mime-mapping entry in web.xml. if (contentType == null) { contentType = "application/octet-stream"; } // If content type is text, then determine whether GZIP content encoding is supported by // the browser and expand content type with the one and right character encoding. if (contentType.startsWith("text")) { String acceptEncoding = request.getHeader("Accept-Encoding"); acceptsGzip = enableGzip && acceptEncoding != null && accepts(acceptEncoding, "gzip"); contentType += ";charset=UTF-8"; } // Else, expect for images, determine content disposition. If content type is supported by // the browser, then set to inline, else attachment which will pop a 'save as' dialogue. else if (!contentType.startsWith("image")) { String accept = request.getHeader("Accept"); disposition = accept != null && accepts(accept, contentType) ? "inline" : "attachment"; } // Initialize response. response.reset(); response.setBufferSize(DEFAULT_BUFFER_SIZE); response.setHeader("Content-Disposition", disposition + ";filename=\"" + fileName + "\""); response.setHeader("Accept-Ranges", "bytes"); response.setHeader("ETag", eTag); response.setDateHeader("Last-Modified", lastModified); response.setDateHeader("Expires", expires); // Send requested file (part(s)) to client ------------------------------------------------ // Prepare streams. RandomAccessFile input = null; OutputStream output = null; try { // Open streams. input = new RandomAccessFile(file, "r"); output = response.getOutputStream(); if (ranges.isEmpty() || ranges.get(0) == full) { // Return full file. Range r = full; response.setContentType(contentType); response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total); if (content) { if (acceptsGzip) { // The browser accepts GZIP, so GZIP the content. response.setHeader("Content-Encoding", "gzip"); output = new GZIPOutputStream(output, DEFAULT_BUFFER_SIZE); } else { // Content length is not directly predictable in case of GZIP. // So only add it if there is no means of GZIP, else browser will hang. response.setHeader("Content-Length", String.valueOf(r.length)); } // Copy full range. copy(input, output, r.start, r.length); } } else if (ranges.size() == 1) { // Return single part of file. Range r = ranges.get(0); response.setContentType(contentType); response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total); response.setHeader("Content-Length", String.valueOf(r.length)); response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206. if (content) { // Copy single part range. copy(input, output, r.start, r.length); } } else { // Return multiple parts of file. response.setContentType("multipart/byteranges; boundary=" + MULTIPART_BOUNDARY); response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206. if (content) { // Cast back to ServletOutputStream to get the easy println methods. ServletOutputStream sos = (ServletOutputStream) output; // Copy multi part range. for (Range r : ranges) { // Add multipart boundary and header fields for every range. sos.println(); sos.println("--" + MULTIPART_BOUNDARY); sos.println("Content-Type: " + contentType); sos.println("Content-Range: bytes " + r.start + "-" + r.end + "/" + r.total); // Copy single part range of multi part range. copy(input, output, r.start, r.length); } // End with multipart boundary. sos.println(); sos.println("--" + MULTIPART_BOUNDARY + "--"); } } } finally { // Gently close streams. close(output); close(input); } }
From source file:org.apache.openmeetings.servlet.outputhandler.DownloadHandler.java
@Override protected void service(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException { try {/* w w w . j av a 2s . c o m*/ httpServletRequest.setCharacterEncoding("UTF-8"); log.debug("\nquery = " + httpServletRequest.getQueryString()); log.debug("\n\nfileName = " + httpServletRequest.getParameter("fileName")); log.debug("\n\nparentPath = " + httpServletRequest.getParameter("parentPath")); String queryString = httpServletRequest.getQueryString(); if (queryString == null) { queryString = ""; } String sid = httpServletRequest.getParameter("sid"); if (sid == null) { sid = "default"; } log.debug("sid: " + sid); Long users_id = getBean(SessiondataDao.class).checkSession(sid); Long user_level = getBean(UserManager.class).getUserLevelByID(users_id); if (user_level != null && user_level > 0) { String room_id = httpServletRequest.getParameter("room_id"); if (room_id == null) { room_id = "default"; } String moduleName = httpServletRequest.getParameter("moduleName"); if (moduleName == null) { moduleName = "nomodule"; } String parentPath = httpServletRequest.getParameter("parentPath"); if (parentPath == null) { parentPath = "nomodule"; } String requestedFile = httpServletRequest.getParameter("fileName"); if (requestedFile == null) { requestedFile = ""; } String fileExplorerItemIdParam = httpServletRequest.getParameter("fileExplorerItemId"); Long fileExplorerItemId = null; if (fileExplorerItemIdParam != null) { fileExplorerItemId = Long.parseLong(fileExplorerItemIdParam); } // make a complete name out of domain(organisation) + roomname String roomName = room_id; // trim whitespaces cause it is a directory name roomName = StringUtils.deleteWhitespace(roomName); // Get the current User-Directory File working_dir; // Add the Folder for the Room if (moduleName.equals("lzRecorderApp")) { working_dir = OmFileHelper.getStreamsHibernateDir(); } else if (moduleName.equals("videoconf1")) { working_dir = OmFileHelper.getUploadRoomDir(roomName); if (parentPath.length() != 0 && !parentPath.equals("/")) { working_dir = new File(working_dir, parentPath); } } else if (moduleName.equals("userprofile")) { working_dir = OmFileHelper.getUploadProfilesUserDir(users_id); logNonExistentFolder(working_dir); } else if (moduleName.equals("remoteuserprofile")) { String remoteUser_id = httpServletRequest.getParameter("remoteUserid"); working_dir = OmFileHelper .getUploadProfilesUserDir(remoteUser_id == null ? "0" : remoteUser_id); logNonExistentFolder(working_dir); } else if (moduleName.equals("remoteuserprofilebig")) { String remoteUser_id = httpServletRequest.getParameter("remoteUserid"); working_dir = OmFileHelper .getUploadProfilesUserDir(remoteUser_id == null ? "0" : remoteUser_id); logNonExistentFolder(working_dir); requestedFile = getBigProfileUserName(working_dir); } else if (moduleName.equals("chat")) { String remoteUser_id = httpServletRequest.getParameter("remoteUserid"); working_dir = OmFileHelper .getUploadProfilesUserDir(remoteUser_id == null ? "0" : remoteUser_id); logNonExistentFolder(working_dir); requestedFile = getChatUserName(working_dir); } else { working_dir = OmFileHelper.getUploadRoomDir(roomName); } if (!moduleName.equals("nomodule")) { log.debug("requestedFile: " + requestedFile + " current_dir: " + working_dir); File full_path = new File(working_dir, requestedFile); // If the File does not exist or is not readable show/load a // place-holder picture if (!full_path.exists() || !full_path.canRead()) { if (!full_path.canRead()) { log.debug("LOG DownloadHandler: The request file is not readable "); } else { log.debug( "LOG DownloadHandler: The request file does not exist / has already been deleted"); } log.debug("LOG ERROR requestedFile: " + requestedFile); // replace the path with the default picture/document if (requestedFile.endsWith(".jpg")) { log.debug("LOG endsWith d.jpg"); log.debug("LOG moduleName: " + moduleName); requestedFile = DownloadHandler.defaultImageName; if (moduleName.equals("remoteuserprofile")) { requestedFile = DownloadHandler.defaultProfileImageName; } else if (moduleName.equals("remoteuserprofilebig")) { requestedFile = DownloadHandler.defaultProfileImageNameBig; } else if (moduleName.equals("userprofile")) { requestedFile = DownloadHandler.defaultProfileImageName; } else if (moduleName.equals("chat")) { requestedFile = DownloadHandler.defaultChatImageName; } } else if (requestedFile.endsWith(".swf")) { requestedFile = DownloadHandler.defaultSWFName; } else { requestedFile = DownloadHandler.defaultImageName; } full_path = new File(OmFileHelper.getDefaultDir(), requestedFile); } log.debug("full_path: " + full_path); if (!full_path.exists() || !full_path.canRead()) { if (!full_path.canRead()) { log.debug( "DownloadHandler: The request DEFAULT-file does not exist / has already been deleted"); } else { log.debug( "DownloadHandler: The request DEFAULT-file does not exist / has already been deleted"); } // no file to handle abort processing return; } // Requested file is outside OM webapp folder File curDirFile = OmFileHelper.getOmHome(); if (!full_path.getCanonicalPath().startsWith(curDirFile.getCanonicalPath())) { throw new Exception("Invalid file requested: f2.cp == " + full_path.getCanonicalPath() + "; curDir.cp == " + curDirFile.getCanonicalPath()); } // Default type - Explorer, Chrome and others int browserType = 0; // Firefox and Opera browsers if (httpServletRequest.getHeader("User-Agent") != null) { if ((httpServletRequest.getHeader("User-Agent").contains("Firefox")) || (httpServletRequest.getHeader("User-Agent").contains("Opera"))) { browserType = 1; } } log.debug("Detected browser type:" + browserType); httpServletResponse.reset(); httpServletResponse.resetBuffer(); OutputStream out = httpServletResponse.getOutputStream(); if (requestedFile.endsWith(".swf")) { // trigger download to SWF => THIS is a workaround for // Flash Player 10, FP 10 does not seem // to accept SWF-Downloads with the Content-Disposition // in the Header httpServletResponse.setContentType("application/x-shockwave-flash"); httpServletResponse.setHeader("Content-Length", "" + full_path.length()); } else { httpServletResponse.setContentType("APPLICATION/OCTET-STREAM"); String fileNameResult = requestedFile; if (fileExplorerItemId != null && fileExplorerItemId > 0) { FileExplorerItem fileExplorerItem = getBean(FileExplorerItemDao.class) .getFileExplorerItemsById(fileExplorerItemId); if (fileExplorerItem != null) { fileNameResult = fileExplorerItem.getFileName().substring(0, fileExplorerItem.getFileName().length() - 4) + fileNameResult.substring(fileNameResult.length() - 4, fileNameResult.length()); } } if (browserType == 0) { httpServletResponse.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(fileNameResult, "UTF-8")); } else { httpServletResponse.setHeader("Content-Disposition", "attachment; filename*=UTF-8'en'" + java.net.URLEncoder.encode(fileNameResult, "UTF-8")); } httpServletResponse.setHeader("Content-Length", "" + full_path.length()); } OmFileHelper.copyFile(full_path, out); out.flush(); out.close(); } } else { log.error("ERROR DownloadHandler: not authorized FileDownload "); } } catch (ServerNotInitializedException e) { return; } catch (Exception er) { log.error("Error downloading: ", er); } }
From source file:edu.ucsd.library.dams.api.FileStoreServlet.java
/** * Process the actual request./* www . j a v a 2s .co m*/ * @param request The request to be processed. * @param response The response to be created. * @param content Whether the request body should be written (GET) or not * (HEAD). * @throws IOException If something fails at I/O level. */ private void processRequest(HttpServletRequest request, HttpServletResponse response, boolean content) throws IOException { // Validate the requested file ------------------------------------- // Get requested file by path info. /* start ucsd changes */ // get object and file ids from path String objid = null; String cmpid = null; String fileid = null; try { // /bb1234567x/1.tif // /bb1234567x/1/2.tif String[] path = request.getPathInfo().split("/"); if (path.length == 3) { objid = path[1]; fileid = path[2]; } else if (path.length == 4) { objid = path[1]; cmpid = path[2]; fileid = path[3]; } } catch (Exception e) { String errorMessage = "Error parsing request pathInfo: " + request.getPathInfo(); log.error(errorMessage, e); response.setContentType("text/plain"); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, errorMessage); return; } // make sure required parameters are populated if (objid == null || objid.trim().length() == 0 || fileid == null || fileid.trim().length() == 0) { response.setContentType("text/plain"); response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Subject and file must be specified in the request URI"); return; } String fullFilename = objid + (StringUtils.isNotBlank(cmpid) ? "-" + cmpid : "") + "-" + fileid; // first load the FileStore (no point if this doesn't work) FileStore fs = null; long fsTime = 0; try { long start = System.currentTimeMillis(); fs = FileStoreUtil.getFileStore(props, fsDefault); fsTime = System.currentTimeMillis() - start; } catch (Exception ex) { response.setContentType("text/plain"); response.sendError(response.SC_INTERNAL_SERVER_ERROR, "Error initializing FileStore"); ex.printStackTrace(); return; } // check authorization attribute String restricted = null; String authorized = (String) request.getAttribute("edu.ucsd.library.dams.api.DAMSAPIServlet.authorized"); if (authorized == null || !authorized.equals("true")) { log.warn("Illegal Access from IP " + request.getRemoteAddr() + " for file " + fullFilename); response.setContentType("text/plain"); response.sendError(HttpServletResponse.SC_FORBIDDEN, "Access without authorization."); return; } else { log.info("DAMS Access authorized for IP " + request.getRemoteAddr() + " for file " + fullFilename); restricted = (String) request.getAttribute("pas.restricted"); //Disable browser caching for restricted objects. if (restricted != null && restricted.equals("1")) { String browser = request.getHeader("User-Agent"); if (browser != null && browser.indexOf("MSIE") != -1) { response.addHeader("Cache-Control", "post-check=0, pre-check=0"); } else { response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate"); } response.setHeader("Pragma", "no-cache"); response.setHeader("Expires", "0"); } } /* end ucsd changes */ // load file metadata Map<String, String> meta = null; long metaTime = 0; try { long start = System.currentTimeMillis(); meta = fs.meta(objid, cmpid, fileid); metaTime = System.currentTimeMillis() - start; } catch (Exception ex) { log.error("File " + fullFilename + " doesn't exist.", ex); response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // Prepare some variables. The ETag is an unique identifier of the file String length = meta.get("Content-Length"); String lastModStr = meta.get("Last-Modified"); long lastModified = 0L; try { lastModified = df.parse(lastModStr).getTime(); } catch (Exception ex) { // error parsing lastmod date... set to now lastModified = System.currentTimeMillis(); } String eTag = meta.get("ETag"); if (eTag == null) { eTag = fullFilename + "_" + length + "_" + lastModified; } // Validate request headers for caching ----------------------------- // If-None-Match header should contain "*" or ETag. If so, return 304. String ifNoneMatch = request.getHeader("If-None-Match"); if (ifNoneMatch != null && matches(ifNoneMatch, eTag)) { response.setHeader("ETag", eTag); // Required in 304. response.sendError(HttpServletResponse.SC_NOT_MODIFIED); return; } // If-Modified-Since header should be greater than LastModified. If so, // then return 304. // This header is ignored if any If-None-Match header is specified. long ifModifiedSince = request.getDateHeader("If-Modified-Since"); if (ifNoneMatch == null && ifModifiedSince != -1 && ifModifiedSince + 1000 > lastModified) { response.setHeader("ETag", eTag); // Required in 304. response.sendError(HttpServletResponse.SC_NOT_MODIFIED); return; } // Validate request headers for resume ------------------------------ // If-Match header should contain "*" or ETag. If not, then return 412. String ifMatch = request.getHeader("If-Match"); if (ifMatch != null && !matches(ifMatch, eTag)) { response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); return; } // If-Unmodified-Since header should be greater than LastModified. // If not, then return 412. long ifUnmodifiedSince = request.getDateHeader("If-Unmodified-Since"); if (ifUnmodifiedSince != -1 && ifUnmodifiedSince + 1000 <= lastModified) { response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); return; } // Prepare and initialize response ---------------------------------- // Get content type by file name and set default GZIP support and // content disposition. String contentType = getServletContext().getMimeType(fullFilename); boolean acceptsGzip = false; String disposition = "inline"; // If content type is unknown, then set the default value. For all // content types, see: http://www.w3schools.com/media/media_mimeref.asp // To add new content types, add new mime-mapping entry in web.xml. if (contentType == null) { contentType = "application/octet-stream"; } //If UCSD download boolean download = request.getParameter("download") != null; if (download) { disposition = "attachment"; contentType = "application/x-download"; } // Else if content type is text, then determine whether GZIP content // encoding is supported by the browser and expand content type with // the one and right character encoding. else if (contentType.startsWith("text")) { //String acceptEncoding = request.getHeader("Accept-Encoding"); //acceptsGzip = acceptEncoding != null && accepts(acceptEncoding, "gzip"); contentType += ";charset=UTF-8"; } // Else, expect for images, determine content disposition. If content // type is supported by the browser, then set to inline, else // attachment which will pop a 'save as' dialogue. else if (!contentType.startsWith("image")) { String accept = request.getHeader("Accept"); disposition = accept != null && accepts(accept, contentType) ? "inline" : "attachment"; } String sFileName = request.getParameter("name"); if (sFileName == null || (sFileName = sFileName.trim()).length() == 0) sFileName = fullFilename; // Initialize response. response.reset(); response.setBufferSize(DEFAULT_BUFFER_SIZE); response.setHeader("Content-Disposition", disposition + ";filename=\"" + sFileName + "\""); response.setHeader("ETag", eTag); response.setDateHeader("Last-Modified", lastModified); /* begin ucsd changes */ if (restricted == null || !restricted.equals("1")) { response.setDateHeader("Expires", System.currentTimeMillis() + DEFAULT_EXPIRE_TIME); } /* end ucsd changes */ // Send requested file to client ------------------------------------ // Prepare streams. InputStream input = null; OutputStream output = null; long fileTime = 0; if (content) { try { long start = System.currentTimeMillis(); // Open streams. input = fs.getInputStream(objid, cmpid, fileid); output = response.getOutputStream(); response.setContentType(contentType); if (acceptsGzip) { // The browser accepts GZIP, so GZIP the content. response.setHeader("Content-Encoding", "gzip"); output = new GZIPOutputStream(output, DEFAULT_BUFFER_SIZE); } else { // Content length is not directly predictable in case of // GZIP. So only add it if there is no means of GZIP, else // browser will hang. response.setHeader("Content-Length", length); } // Copy full range. /* begin ucsd changes */ FileStoreUtil.copy(input, output); fileTime = System.currentTimeMillis() - start; /* begin ucsd changes */ } catch (Exception ex) { log.error("Error reading " + fullFilename, ex); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } finally { /* begin ucsd changes */ log.info("Time in miliseconds to retrival file " + fullFilename + "(" + length + " bytes)" + ": Total " + (fsTime + metaTime + fileTime) + "[FileStore initiation: " + fsTime + "; Metadata query: " + metaTime + "; File download: " + fileTime + "]"); /* begin ucsd changes */ // Gently close streams. close(output); close(input); } } }
From source file:org.openmrs.module.patientnarratives.web.servlet.FileServlet.java
/** * Process the actual request./*from ww w .j a v a2s .c om*/ * @param request The request to be processed. * @param response The response to be created. * @param content Whether the request body should be written (GET) or not (HEAD). * @throws IOException If something fails at I/O level. */ private void processRequest(HttpServletRequest request, HttpServletResponse response, boolean content) throws IOException { // Validate the requested file ------------------------------------------------------------ Integer videoObsId = Integer.parseInt(request.getParameter("obsId")); Obs complexObs = Context.getObsService().getComplexObs(videoObsId, OpenmrsConstants.RAW_VIEW); ComplexData complexData = complexObs.getComplexData(); byte[] videoObjectData = ((byte[]) complexData.getData()); String fileExt_file = complexData.getTitle(); String arrFileExt[] = fileExt_file.split(" "); tempMergedVideoFile = createFile(arrFileExt[0]); String requestedFile = tempMergedVideoFile.getCanonicalPath(); FileUtils.writeByteArrayToFile(new File(requestedFile), videoObjectData); // Check if file is actually supplied to the request URL. if (requestedFile == null) { // Do your thing if the file is not supplied to the request URL. // Throw an exception, or send 404, or show default/warning page, or just ignore it. response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // URL-decode the file name (might contain spaces and on) and prepare file object. File file = new File(requestedFile); // Check if file actually exists in filesystem. if (!file.exists()) { // Do your thing if the file appears to be non-existing. // Throw an exception, or send 404, or show default/warning page, or just ignore it. response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // Prepare some variables. The ETag is an unique identifier of the file. String fileName = file.getName(); long length = file.length(); long lastModified = file.lastModified(); String eTag = fileName + "_" + length + "_" + lastModified; long expires = System.currentTimeMillis() + DEFAULT_EXPIRE_TIME; // Validate request headers for caching --------------------------------------------------- // If-None-Match header should contain "*" or ETag. If so, then return 304. String ifNoneMatch = request.getHeader("If-None-Match"); if (ifNoneMatch != null && matches(ifNoneMatch, eTag)) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); response.setHeader("ETag", eTag); // Required in 304. response.setDateHeader("Expires", expires); // Postpone cache with 1 week. return; } // If-Modified-Since header should be greater than LastModified. If so, then return 304. // This header is ignored if any If-None-Match header is specified. long ifModifiedSince = request.getDateHeader("If-Modified-Since"); if (ifNoneMatch == null && ifModifiedSince != -1 && ifModifiedSince + 1000 > lastModified) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); response.setHeader("ETag", eTag); // Required in 304. response.setDateHeader("Expires", expires); // Postpone cache with 1 week. return; } // Validate request headers for resume ---------------------------------------------------- // If-Match header should contain "*" or ETag. If not, then return 412. String ifMatch = request.getHeader("If-Match"); if (ifMatch != null && !matches(ifMatch, eTag)) { response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); return; } // If-Unmodified-Since header should be greater than LastModified. If not, then return 412. long ifUnmodifiedSince = request.getDateHeader("If-Unmodified-Since"); if (ifUnmodifiedSince != -1 && ifUnmodifiedSince + 1000 <= lastModified) { response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); return; } // Validate and process range ------------------------------------------------------------- // Prepare some variables. The full Range represents the complete file. Range full = new Range(0, length - 1, length); List<Range> ranges = new ArrayList<Range>(); // Validate and process Range and If-Range headers. String range = request.getHeader("Range"); if (range != null) { // Range header should match format "bytes=n-n,n-n,n-n...". If not, then return 416. if (!range.matches("^bytes=\\d*-\\d*(,\\d*-\\d*)*$")) { response.setHeader("Content-Range", "bytes */" + length); // Required in 416. response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); return; } // If-Range header should either match ETag or be greater then LastModified. If not, // then return full file. String ifRange = request.getHeader("If-Range"); if (ifRange != null && !ifRange.equals(eTag)) { try { long ifRangeTime = request.getDateHeader("If-Range"); // Throws IAE if invalid. if (ifRangeTime != -1 && ifRangeTime + 1000 < lastModified) { ranges.add(full); } } catch (IllegalArgumentException ignore) { ranges.add(full); } } // If any valid If-Range header, then process each part of byte range. if (ranges.isEmpty()) { for (String part : range.substring(6).split(",")) { // Assuming a file with length of 100, the following examples returns bytes at: // 50-80 (50 to 80), 40- (40 to length=100), -20 (length-20=80 to length=100). long start = sublong(part, 0, part.indexOf("-")); long end = sublong(part, part.indexOf("-") + 1, part.length()); if (start == -1) { start = length - end; end = length - 1; } else if (end == -1 || end > length - 1) { end = length - 1; } // Check if Range is syntactically valid. If not, then return 416. if (start > end) { response.setHeader("Content-Range", "bytes */" + length); // Required in 416. response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); return; } // Add range. ranges.add(new Range(start, end, length)); } } } // Prepare and initialize response -------------------------------------------------------- // Get content type by file name and set default GZIP support and content disposition. String contentType = getServletContext().getMimeType(fileName); boolean acceptsGzip = false; String disposition = "inline"; // If content type is unknown, then set the default value. // For all content types, see: http://www.w3schools.com/media/media_mimeref.asp // To add new content types, add new mime-mapping entry in web.xml. if (contentType == null) { contentType = "application/octet-stream"; } // If content type is text, then determine whether GZIP content encoding is supported by // the browser and expand content type with the one and right character encoding. if (contentType.startsWith("text")) { String acceptEncoding = request.getHeader("Accept-Encoding"); acceptsGzip = acceptEncoding != null && accepts(acceptEncoding, "gzip"); contentType += ";charset=UTF-8"; } // Else, expect for images, determine content disposition. If content type is supported by // the browser, then set to inline, else attachment which will pop a 'save as' dialogue. else if (!contentType.startsWith("image")) { String accept = request.getHeader("Accept"); disposition = accept != null && accepts(accept, contentType) ? "inline" : "attachment"; } // Initialize response. response.reset(); response.setBufferSize(DEFAULT_BUFFER_SIZE); response.setHeader("Content-Disposition", disposition + ";filename=\"" + fileName + "\""); response.setHeader("Accept-Ranges", "bytes"); response.setHeader("ETag", eTag); response.setDateHeader("Last-Modified", lastModified); response.setDateHeader("Expires", expires); // Send requested file (part(s)) to client ------------------------------------------------ // Prepare streams. RandomAccessFile input = null; OutputStream output = null; try { // Open streams. input = new RandomAccessFile(file, "r"); output = response.getOutputStream(); if (ranges.isEmpty() || ranges.get(0) == full) { // Return full file. Range r = full; response.setContentType(contentType); response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total); if (content) { if (acceptsGzip) { // The browser accepts GZIP, so GZIP the content. response.setHeader("Content-Encoding", "gzip"); output = new GZIPOutputStream(output, DEFAULT_BUFFER_SIZE); } else { // Content length is not directly predictable in case of GZIP. // So only add it if there is no means of GZIP, else browser will hang. response.setHeader("Content-Length", String.valueOf(r.length)); } // Copy full range. copy(input, output, r.start, r.length); } } else if (ranges.size() == 1) { // Return single part of file. Range r = ranges.get(0); response.setContentType(contentType); response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total); response.setHeader("Content-Length", String.valueOf(r.length)); response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206. if (content) { // Copy single part range. copy(input, output, r.start, r.length); } } else { // Return multiple parts of file. response.setContentType("multipart/byteranges; boundary=" + MULTIPART_BOUNDARY); response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206. if (content) { // Cast back to ServletOutputStream to get the easy println methods. ServletOutputStream sos = (ServletOutputStream) output; // Copy multi part range. for (Range r : ranges) { // Add multipart boundary and header fields for every range. sos.println(); sos.println("--" + MULTIPART_BOUNDARY); sos.println("Content-Type: " + contentType); sos.println("Content-Range: bytes " + r.start + "-" + r.end + "/" + r.total); // Copy single part range of multi part range. copy(input, output, r.start, r.length); } // End with multipart boundary. sos.println(); sos.println("--" + MULTIPART_BOUNDARY + "--"); } } } finally { // Gently close streams. close(output); close(input); tempMergedVideoFile.delete(); } }
From source file:org.openmeetings.servlet.outputhandler.CalendarServlet.java
@Override protected void service(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException { try {//from w ww . j a v a2s . co m if (getUserManagement() == null || getOmTimeZoneDaoImpl() == null || getCfgManagement() == null || getSessionManagement() == null || getAppointmentLogic() == null || getTimezoneUtil() == null) { return; } String sid = httpServletRequest.getParameter("sid"); if (sid == null) { sid = "default"; } log.debug("sid: " + sid); Long users_id = getSessionManagement().checkSession(sid); Long user_level = getUserManagement().getUserLevelByID(users_id); if (user_level != null && user_level > 0) { String timeZoneIdAsStr = httpServletRequest.getParameter("timeZoneId"); if (timeZoneIdAsStr == null) { log.error("No timeZoneIdAsStr given, using default"); timeZoneIdAsStr = ""; } TimeZone timezone = getTimezoneUtil() .getTimezoneByOmTimeZoneId(Long.valueOf(timeZoneIdAsStr).longValue()); String yearStr = httpServletRequest.getParameter("year"); String monthStr = httpServletRequest.getParameter("month"); String userStr = httpServletRequest.getParameter("user"); String contactUser = httpServletRequest.getParameter("contactUser"); Calendar starttime = GregorianCalendar.getInstance(timezone); starttime.set(Calendar.DATE, 1); starttime.set(Calendar.MONTH, Integer.parseInt(monthStr) - 1); starttime.set(Calendar.MINUTE, 0); starttime.set(Calendar.SECOND, 0); starttime.set(Calendar.YEAR, Integer.parseInt(yearStr)); Calendar endtime = GregorianCalendar.getInstance(timezone); endtime.set(Calendar.DATE, 1); endtime.set(Calendar.MONTH, Integer.parseInt(monthStr)); endtime.set(Calendar.MINUTE, 0); endtime.set(Calendar.SECOND, 0); endtime.set(Calendar.YEAR, Integer.parseInt(yearStr)); Long userToShowId = Long.parseLong(contactUser); if (userToShowId == 0) { userToShowId = Long.parseLong(userStr); } List<Appointment> appointements = getAppointmentLogic().getAppointmentByRange(userToShowId, new Date(starttime.getTimeInMillis()), new Date(endtime.getTimeInMillis())); Document document = DocumentHelper.createDocument(); document.setXMLEncoding("UTF-8"); document.addComment("###############################################\n" + getServletContext().getServletContextName() + " Calendar \n" + "###############################################"); Element vcalendar = document.addElement("vcalendar"); Element year = vcalendar.addElement("year" + yearStr); Element month = year.addElement("month" + monthStr); int previousDay = 0; Element day = null; for (Appointment appointment : appointements) { Calendar appStart = Calendar.getInstance(timezone); appStart.setTime(appointment.getAppointmentStarttime()); int dayAsInt = appStart.get(Calendar.DATE); if (previousDay != dayAsInt) { day = month.addElement("day" + dayAsInt); previousDay = dayAsInt; } if (appStart.get(Calendar.MONTH) + 1 == Integer.parseInt(monthStr)) { Element event = day.addElement("event"); Element appointementId = event.addElement("appointementId"); appointementId.addAttribute("value", "" + appointment.getAppointmentId()); Element isConnectedEvent = event.addElement("isConnectedEvent"); isConnectedEvent.addAttribute("value", "" + appointment.getIsConnectedEvent()); Element rooms_id = event.addElement("rooms_id"); Element roomtype = event.addElement("roomtype"); if (appointment.getRoom() != null) { rooms_id.addAttribute("value", "" + appointment.getRoom().getRooms_id()); roomtype.addAttribute("value", "" + appointment.getRoom().getRoomtype().getRoomtypes_id()); } else { rooms_id.addAttribute("value", "0"); roomtype.addAttribute("value", "1"); } Element remindType = event.addElement("remindtype"); remindType.addAttribute("value", appointment.getRemind() != null ? "" + appointment.getRemind().getTypId() : "0"); Element summary = event.addElement("summary"); summary.addAttribute("value", appointment.getAppointmentName()); Element comment = event.addElement("comment"); comment.addAttribute("value", appointment.getAppointmentDescription()); Element start = event.addElement("start"); start.addAttribute("year", "" + appStart.get(Calendar.YEAR)); start.addAttribute("month", "" + (appStart.get(Calendar.MONTH) + 1)); start.addAttribute("day", "" + appStart.get(Calendar.DATE)); start.addAttribute("hour", "" + appStart.get(Calendar.HOUR_OF_DAY)); start.addAttribute("minute", "" + appStart.get(Calendar.MINUTE)); Calendar appEnd = Calendar.getInstance(timezone); appEnd.setTime(appointment.getAppointmentEndtime()); Element end = event.addElement("end"); end.addAttribute("year", "" + appEnd.get(Calendar.YEAR)); end.addAttribute("month", "" + (appEnd.get(Calendar.MONTH) + 1)); end.addAttribute("day", "" + appEnd.get(Calendar.DATE)); end.addAttribute("hour", "" + appEnd.get(Calendar.HOUR_OF_DAY)); end.addAttribute("minute", "" + appEnd.get(Calendar.MINUTE)); Element category = event.addElement("category"); category.addAttribute("value", "" + appointment.getAppointmentCategory().getCategoryId()); Element uid = event.addElement("uid"); uid.addAttribute("value", "" + appointment.getAppointmentId()); Element attendees = event.addElement("attendees"); for (MeetingMember meetingMember : appointment.getMeetingMember()) { Element attendee = attendees.addElement("attendee"); Element email = attendee.addElement("email"); email.addAttribute("value", meetingMember.getEmail()); Element userId = attendee.addElement("userId"); if (meetingMember.getUserid() != null) { userId.addAttribute("value", "" + meetingMember.getUserid().getUser_id()); } else { userId.addAttribute("value", ""); } Element memberId = attendee.addElement("memberId"); memberId.addAttribute("value", "" + meetingMember.getMeetingMemberId()); Element firstname = attendee.addElement("firstname"); memberId.addAttribute("value", "" + meetingMember.getMeetingMemberId()); firstname.addAttribute("value", meetingMember.getFirstname()); Element lastname = attendee.addElement("lastname"); lastname.addAttribute("value", meetingMember.getLastname()); Element jNameTimeZoneMember = attendee.addElement("jNameTimeZone"); if (meetingMember.getOmTimeZone() != null) { jNameTimeZoneMember.addAttribute("value", meetingMember.getOmTimeZone().getJname()); } else { jNameTimeZoneMember.addAttribute("value", ""); } } } } httpServletResponse.reset(); httpServletResponse.resetBuffer(); OutputStream out = httpServletResponse.getOutputStream(); httpServletResponse.setContentType("text/xml"); // httpServletResponse.setHeader("Content-Length", ""+ // rf.length()); OutputFormat outformat = OutputFormat.createPrettyPrint(); outformat.setEncoding("UTF-8"); XMLWriter writer = new XMLWriter(out, outformat); writer.write(document); writer.flush(); out.flush(); out.close(); } } catch (Exception er) { log.error("[Calendar :: service]", er); } }
From source file:org.openhab.ui.cometvisu.servlet.CometVisuServlet.java
/** * Process the actual request./*from ww w . j ava 2s. c o m*/ * * @param request * The request to be processed. * @param response * The response to be created. * @param content * Whether the request body should be written (GET) or not * (HEAD). * @throws IOException * If something fails at I/O level. * * @author BalusC * @link * http://balusc.blogspot.com/2009/02/fileservlet-supporting-resume-and * .html */ private void processStaticRequest(File file, HttpServletRequest request, HttpServletResponse response, boolean content) throws IOException { // Validate the requested file // ------------------------------------------------------------ if (file == null) { // Get requested file by path info. String requestedFile = request.getPathInfo(); // Check if file is actually supplied to the request URL. if (requestedFile == null) { // Do your thing if the file is not supplied to the request URL. // Throw an exception, or send 404, or show default/warning // page, or // just ignore it. response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // URL-decode the file name (might contain spaces and on) and // prepare // file object. file = new File(rootFolder, URLDecoder.decode(requestedFile, "UTF-8")); } // Check if file actually exists in filesystem. if (!file.exists()) { // Do your thing if the file appears to be non-existing. // Throw an exception, or send 404, or show default/warning page, or // just ignore it. response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // Prepare some variables. The ETag is an unique identifier of the file. String fileName = file.getName(); long length = file.length(); long lastModified = file.lastModified(); String eTag = fileName + "_" + length + "_" + lastModified; long expires = System.currentTimeMillis() + DEFAULT_EXPIRE_TIME; // Validate request headers for caching // --------------------------------------------------- // If-None-Match header should contain "*" or ETag. If so, then return // 304. String ifNoneMatch = request.getHeader("If-None-Match"); if (ifNoneMatch != null && matches(ifNoneMatch, eTag)) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); response.setHeader("ETag", eTag); // Required in 304. response.setDateHeader("Expires", expires); // Postpone cache with 1 // week. return; } // If-Modified-Since header should be greater than LastModified. If so, // then return 304. // This header is ignored if any If-None-Match header is specified. long ifModifiedSince = request.getDateHeader("If-Modified-Since"); if (ifNoneMatch == null && ifModifiedSince != -1 && ifModifiedSince + 1000 > lastModified) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); response.setHeader("ETag", eTag); // Required in 304. response.setDateHeader("Expires", expires); // Postpone cache with 1 // week. return; } // Validate request headers for resume // ---------------------------------------------------- // If-Match header should contain "*" or ETag. If not, then return 412. String ifMatch = request.getHeader("If-Match"); if (ifMatch != null && !matches(ifMatch, eTag)) { response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); return; } // If-Unmodified-Since header should be greater than LastModified. If // not, then return 412. long ifUnmodifiedSince = request.getDateHeader("If-Unmodified-Since"); if (ifUnmodifiedSince != -1 && ifUnmodifiedSince + 1000 <= lastModified) { response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); return; } // Validate and process range // ------------------------------------------------------------- // Prepare some variables. The full Range represents the complete file. Range full = new Range(0, length - 1, length); List<Range> ranges = new ArrayList<Range>(); // Validate and process Range and If-Range headers. String range = request.getHeader("Range"); if (range != null) { // Range header should match format "bytes=n-n,n-n,n-n...". If not, // then return 416. if (!range.matches("^bytes=\\d*-\\d*(,\\d*-\\d*)*$")) { response.setHeader("Content-Range", "bytes */" + length); // Required // in // 416. response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); return; } // If-Range header should either match ETag or be greater then // LastModified. If not, // then return full file. String ifRange = request.getHeader("If-Range"); if (ifRange != null && !ifRange.equals(eTag)) { try { long ifRangeTime = request.getDateHeader("If-Range"); // Throws // IAE // if // invalid. if (ifRangeTime != -1 && ifRangeTime + 1000 < lastModified) { ranges.add(full); } } catch (IllegalArgumentException ignore) { ranges.add(full); } } // If any valid If-Range header, then process each part of byte // range. if (ranges.isEmpty()) { for (String part : range.substring(6).split(",")) { // Assuming a file with length of 100, the following // examples returns bytes at: // 50-80 (50 to 80), 40- (40 to length=100), -20 // (length-20=80 to length=100). long start = sublong(part, 0, part.indexOf("-")); long end = sublong(part, part.indexOf("-") + 1, part.length()); if (start == -1) { start = length - end; end = length - 1; } else if (end == -1 || end > length - 1) { end = length - 1; } // Check if Range is syntactically valid. If not, then // return 416. if (start > end) { response.setHeader("Content-Range", "bytes */" + length); // Required // in // 416. response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); return; } // Add range. ranges.add(new Range(start, end, length)); } } } // Prepare and initialize response // -------------------------------------------------------- // Get content type by file name and set default GZIP support and // content disposition. String contentType = getServletContext().getMimeType(fileName); boolean acceptsGzip = false; String disposition = "inline"; // If content type is unknown, then set the default value. // For all content types, see: // http://www.w3schools.com/media/media_mimeref.asp // To add new content types, add new mime-mapping entry in web.xml. if (contentType == null) { contentType = "application/octet-stream"; } // If content type is text, then determine whether GZIP content encoding // is supported by // the browser and expand content type with the one and right character // encoding. if (contentType.startsWith("text")) { String acceptEncoding = request.getHeader("Accept-Encoding"); acceptsGzip = acceptEncoding != null && accepts(acceptEncoding, "gzip"); contentType += ";charset=UTF-8"; } // Else, expect for images, determine content disposition. If content // type is supported by // the browser, then set to inline, else attachment which will pop a // 'save as' dialogue. else if (!contentType.startsWith("image")) { String accept = request.getHeader("Accept"); disposition = accept != null && accepts(accept, contentType) ? "inline" : "attachment"; } // Initialize response. response.reset(); response.setBufferSize(DEFAULT_BUFFER_SIZE); response.setHeader("Content-Disposition", disposition + ";filename=\"" + fileName + "\""); response.setHeader("Accept-Ranges", "bytes"); response.setHeader("ETag", eTag); response.setDateHeader("Last-Modified", lastModified); response.setDateHeader("Expires", expires); // Send requested file (part(s)) to client // ------------------------------------------------ // Prepare streams. RandomAccessFile input = null; OutputStream output = null; try { // Open streams. input = new RandomAccessFile(file, "r"); output = response.getOutputStream(); if (ranges.isEmpty() || ranges.get(0) == full) { // Return full file. Range r = full; response.setContentType(contentType); response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total); if (content) { if (acceptsGzip) { // The browser accepts GZIP, so GZIP the content. response.setHeader("Content-Encoding", "gzip"); output = new GZIPOutputStream(output, DEFAULT_BUFFER_SIZE); } else { // Content length is not directly predictable in case of // GZIP. // So only add it if there is no means of GZIP, else // browser will hang. response.setHeader("Content-Length", String.valueOf(r.length)); } // Copy full range. copy(input, output, r.start, r.length); } } else if (ranges.size() == 1) { // Return single part of file. Range r = ranges.get(0); response.setContentType(contentType); response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total); response.setHeader("Content-Length", String.valueOf(r.length)); response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206. if (content) { // Copy single part range. copy(input, output, r.start, r.length); } } else { // Return multiple parts of file. response.setContentType("multipart/byteranges; boundary=" + MULTIPART_BOUNDARY); response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206. if (content) { // Cast back to ServletOutputStream to get the easy println // methods. ServletOutputStream sos = (ServletOutputStream) output; // Copy multi part range. for (Range r : ranges) { // Add multipart boundary and header fields for every // range. sos.println(); sos.println("--" + MULTIPART_BOUNDARY); sos.println("Content-Type: " + contentType); sos.println("Content-Range: bytes " + r.start + "-" + r.end + "/" + r.total); // Copy single part range of multi part range. copy(input, output, r.start, r.length); } // End with multipart boundary. sos.println(); sos.println("--" + MULTIPART_BOUNDARY + "--"); } } } finally { // Gently close streams. close(output); close(input); } }
From source file:org.openmeetings.servlet.outputhandler.DownloadHandler.java
@Override protected void service(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException { try {//from w w w .j a v a2 s . c o m if (getUserManagement() == null || getSessionManagement() == null) { return; } httpServletRequest.setCharacterEncoding("UTF-8"); log.debug("\nquery = " + httpServletRequest.getQueryString()); log.debug("\n\nfileName = " + httpServletRequest.getParameter("fileName")); log.debug("\n\nparentPath = " + httpServletRequest.getParameter("parentPath")); String queryString = httpServletRequest.getQueryString(); if (queryString == null) { queryString = ""; } String sid = httpServletRequest.getParameter("sid"); if (sid == null) { sid = "default"; } log.debug("sid: " + sid); Long users_id = getSessionManagement().checkSession(sid); Long user_level = getUserManagement().getUserLevelByID(users_id); if (user_level != null && user_level > 0) { String room_id = httpServletRequest.getParameter("room_id"); if (room_id == null) { room_id = "default"; } String moduleName = httpServletRequest.getParameter("moduleName"); if (moduleName == null) { moduleName = "nomodule"; } String parentPath = httpServletRequest.getParameter("parentPath"); if (parentPath == null) { parentPath = "nomodule"; } String requestedFile = httpServletRequest.getParameter("fileName"); if (requestedFile == null) { requestedFile = ""; } String fileExplorerItemIdParam = httpServletRequest.getParameter("fileExplorerItemId"); Long fileExplorerItemId = null; if (fileExplorerItemIdParam != null) { fileExplorerItemId = Long.parseLong(fileExplorerItemIdParam); } // make a complete name out of domain(organisation) + roomname String roomName = room_id; // trim whitespaces cause it is a directory name roomName = StringUtils.deleteWhitespace(roomName); // Get the current User-Directory String current_dir = getServletContext().getRealPath("/"); String working_dir = ""; working_dir = current_dir + OpenmeetingsVariables.UPLOAD_DIR + File.separatorChar; // Add the Folder for the Room if (moduleName.equals("lzRecorderApp")) { working_dir = current_dir + OpenmeetingsVariables.STREAMS_DIR + File.separatorChar + "hibernate" + File.separatorChar; } else if (moduleName.equals("videoconf1")) { if (parentPath.length() != 0) { if (parentPath.equals("/")) { working_dir = working_dir + roomName + File.separatorChar; } else { working_dir = working_dir + roomName + File.separatorChar + parentPath + File.separatorChar; } } else { working_dir = current_dir + roomName + File.separatorChar; } } else if (moduleName.equals("userprofile")) { working_dir += "profiles" + File.separatorChar; logNonExistentFolder(working_dir); working_dir += ScopeApplicationAdapter.profilesPrefix + users_id + File.separatorChar; logNonExistentFolder(working_dir); } else if (moduleName.equals("remoteuserprofile")) { working_dir += "profiles" + File.separatorChar; logNonExistentFolder(working_dir); String remoteUser_id = httpServletRequest.getParameter("remoteUserid"); if (remoteUser_id == null) { remoteUser_id = "0"; } working_dir += ScopeApplicationAdapter.profilesPrefix + remoteUser_id + File.separatorChar; logNonExistentFolder(working_dir); } else if (moduleName.equals("remoteuserprofilebig")) { working_dir += "profiles" + File.separatorChar; logNonExistentFolder(working_dir); String remoteUser_id = httpServletRequest.getParameter("remoteUserid"); if (remoteUser_id == null) { remoteUser_id = "0"; } working_dir += ScopeApplicationAdapter.profilesPrefix + remoteUser_id + File.separatorChar; logNonExistentFolder(working_dir); requestedFile = this.getBigProfileUserName(working_dir); } else if (moduleName.equals("chat")) { working_dir += "profiles" + File.separatorChar; logNonExistentFolder(working_dir); String remoteUser_id = httpServletRequest.getParameter("remoteUserid"); if (remoteUser_id == null) { remoteUser_id = "0"; } working_dir += ScopeApplicationAdapter.profilesPrefix + remoteUser_id + File.separatorChar; logNonExistentFolder(working_dir); requestedFile = this.getChatUserName(working_dir); } else { working_dir = working_dir + roomName + File.separatorChar; } if (!moduleName.equals("nomodule")) { log.debug("requestedFile: " + requestedFile + " current_dir: " + working_dir); String full_path = working_dir + requestedFile; File f = new File(full_path); // If the File does not exist or is not readable show/load a // place-holder picture if (!f.exists() || !f.canRead()) { if (!f.canRead()) { log.debug("LOG DownloadHandler: The request file is not readable"); } else { log.debug( "LOG DownloadHandler: The request file does not exist / has already been deleted"); } log.debug("LOG ERROR requestedFile: " + requestedFile); // replace the path with the default picture/document if (requestedFile.endsWith(".jpg")) { log.debug("LOG endsWith d.jpg"); log.debug("LOG moduleName: " + moduleName); requestedFile = DownloadHandler.defaultImageName; if (moduleName.equals("remoteuserprofile")) { requestedFile = DownloadHandler.defaultProfileImageName; } else if (moduleName.equals("remoteuserprofilebig")) { requestedFile = DownloadHandler.defaultProfileImageNameBig; } else if (moduleName.equals("userprofile")) { requestedFile = DownloadHandler.defaultProfileImageName; } else if (moduleName.equals("chat")) { requestedFile = DownloadHandler.defaultChatImageName; } // request for an image full_path = current_dir + "default" + File.separatorChar + requestedFile; } else if (requestedFile.endsWith(".swf")) { requestedFile = DownloadHandler.defaultSWFName; // request for a SWFPresentation full_path = current_dir + "default" + File.separatorChar + DownloadHandler.defaultSWFName; } else { // Any document, must be a download request // OR a Moodle Loggedin User requestedFile = DownloadHandler.defaultImageName; full_path = current_dir + "default" + File.separatorChar + DownloadHandler.defaultImageName; } } log.debug("full_path: " + full_path); File f2 = new File(full_path); if (!f2.exists() || !f2.canRead()) { if (!f2.canRead()) { log.debug( "DownloadHandler: The request DEFAULT-file does not exist / has already been deleted"); } else { log.debug( "DownloadHandler: The request DEFAULT-file does not exist / has already been deleted"); } // no file to handle abort processing return; } // Requested file is outside OM webapp folder File curDirFile = new File(current_dir); if (!f2.getCanonicalPath().startsWith(curDirFile.getCanonicalPath())) { throw new Exception("Invalid file requested: f2.cp == " + f2.getCanonicalPath() + "; curDir.cp == " + curDirFile.getCanonicalPath()); } // Get file and handle download RandomAccessFile rf = new RandomAccessFile(full_path, "r"); // Default type - Explorer, Chrome and others int browserType = 0; // Firefox and Opera browsers if (httpServletRequest.getHeader("User-Agent") != null) { if ((httpServletRequest.getHeader("User-Agent").contains("Firefox")) || (httpServletRequest.getHeader("User-Agent").contains("Opera"))) { browserType = 1; } } log.debug("Detected browser type:" + browserType); httpServletResponse.reset(); httpServletResponse.resetBuffer(); OutputStream out = httpServletResponse.getOutputStream(); if (requestedFile.endsWith(".swf")) { // trigger download to SWF => THIS is a workaround for // Flash Player 10, FP 10 does not seem // to accept SWF-Downloads with the Content-Disposition // in the Header httpServletResponse.setContentType("application/x-shockwave-flash"); httpServletResponse.setHeader("Content-Length", "" + rf.length()); } else { httpServletResponse.setContentType("APPLICATION/OCTET-STREAM"); String fileNameResult = requestedFile; if (fileExplorerItemId != null && fileExplorerItemId > 0) { FileExplorerItem fileExplorerItem = getFileExplorerItemDaoImpl() .getFileExplorerItemsById(fileExplorerItemId); if (fileExplorerItem != null) { fileNameResult = fileExplorerItem.getFileName().substring(0, fileExplorerItem.getFileName().length() - 4) + fileNameResult.substring(fileNameResult.length() - 4, fileNameResult.length()); } } if (browserType == 0) { httpServletResponse.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(fileNameResult, "UTF-8")); } else { httpServletResponse.setHeader("Content-Disposition", "attachment; filename*=UTF-8'en'" + java.net.URLEncoder.encode(fileNameResult, "UTF-8")); } httpServletResponse.setHeader("Content-Length", "" + rf.length()); } byte[] buffer = new byte[1024]; int readed = -1; while ((readed = rf.read(buffer, 0, buffer.length)) > -1) { out.write(buffer, 0, readed); } rf.close(); out.flush(); out.close(); } } else { System.out.println("ERROR DownloadHandler: not authorized FileDownload " + (new Date())); } } catch (Exception er) { log.error("Error downloading: ", er); // er.printStackTrace(); } }
From source file:de.innovationgate.wgpublisher.WGPDispatcher.java
private void dispatchTmlRequest(WGPRequestPath path, javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, Date startDate) throws java.lang.Exception { WGContent content = path.getContent(); WGDatabase database = path.getDatabase(); if (database == null) { throw new HttpErrorException(404, "No database of key " + path.getDatabaseKey(), null); }//from w ww . j av a 2 s . c o m WGARequestInformation info = (WGARequestInformation) request .getAttribute(WGARequestInformation.REQUEST_ATTRIBUTENAME); if (info != null) { info.setDatabase(database); info.setContent(content); if (content != null) { info.setType(WGARequestInformation.TYPE_CONTENT); } else { info.setType(WGARequestInformation.TYPE_TML); } } boolean ajax = false; HttpSession session = request.getSession(); // Determine requested mime type and type key String mediaKey = path.getMediaKey(); if (mediaKey == null) { mediaKey = database.getAttribute(WGACore.DBATTRIB_DEFAULT_MEDIAKEY).toString(); } // Ensure existing SO registry for this session/database SessionScopeResolver.getRegistry(request.getSession(), database.getDbReference(), true); // Look if a session cookie has to be set _core.setSessionCookie(request, response, database); // Context request, if content key filled or we have a title path if (content != null) { if (!content.mayBePublished( isBrowserInterface(session) || isAuthoringMode(database.getDbReference(), session), WGContent.DISPLAYTYPE_NONE)) { sendNoContentNotification(path, request, response, database); return; } if (content.isVirtual()) { if (isBrowserInterface(session)) { if (!content.getStatus().equals(WGContent.STATUS_DRAFT) && request.getParameter("forceVLink") == null) { String url = getVirtualContentURL(request, database, path, content); sendRedirect(request, response, url); return; } } else { String vLink = buildVirtualLink(WGA.get(request, response, getCore()), content, path.getMediaKey(), path.getLayoutKey()); if (vLink != null) { sendRedirect(request, response, vLink); return; } else { throw new HttpErrorException(HttpServletResponse.SC_NOT_FOUND, "Unresolveable virtual link on content " + content.getContentKey().toString(), path.getDatabaseKey()); } } } } // Contextless request. We use a dummy content else { content = database.getDummyContent(path.getRequestLanguage()); } // Test browsability of content if (!content.isDummy() && getBrowsingSecurity(database) <= BrowsingSecurity.NO_BROWSING) { throw new HttpErrorException(java.net.HttpURLConnection.HTTP_FORBIDDEN, "Browsing not allowed in database '" + path.getDatabaseKey() + "'", path.getDatabaseKey()); } // Drop cache if requested by url param if (request.getQueryString() != null && request.getQueryString().toLowerCase().indexOf("dropcache") != -1 && isAdminLoggedIn(request)) { content.dropCache(); } // Preparse TMLForm data into multipart form data TMLForm.MultipartFormData formData = null; String ajaxFormdataSessionKey = request.getParameter("$ajaxformkey"); if (ajaxFormdataSessionKey != null && !ajaxFormdataSessionKey.trim().equals("")) { formData = (TMLForm.MultipartFormData) request.getSession().getAttribute(ajaxFormdataSessionKey); if (formData != null && !formData.isValid()) { formData = null; } request.getSession().removeAttribute(ajaxFormdataSessionKey); } else if (ServletFileUpload.isMultipartContent(request) && request.getContentLength() != -1) { try { formData = new TMLForm.MultipartFormData(request, getCore()); } catch (IOException e) { getCore().getLog().warn( "Could not parse multipart form data because of IO exception: " + WGUtils.getRootCause(e)); } catch (Exception e) { getCore().getLog().error("Exception parsing multipart form data", e); } } // Read ajax information, to be able to determine AJAX requests String encAjaxInfo = request.getParameter("$ajaxInfo"); boolean isAjax = (encAjaxInfo != null); TMLUserProfile tmlUserProfile = null; try { tmlUserProfile = getCore().getPersManager().prepareUserProfileForRequest(request, response, content, database, formData, isAjax); if (info != null && tmlUserProfile != null) { info.setProfile(tmlUserProfile); } } catch (Exception e) { _log.error("Unable to personalize WebTML request " + path.getCompleteURL(), e); } // Set some basic attributes for WebTML processing request.setAttribute(WGACore.ATTRIB_WGPPATH, path.getPublisherURL()); request.setAttribute(WGACore.ATTRIB_TAGIDS, new ConcurrentHashMap<String, BaseTagStatus>()); request.setAttribute(WGACore.ATTRIB_REQUESTURL, path.getCompleteURL()); request.setAttribute(WGACore.ATTRIB_REQUESTTYPE, REQUESTTYPE_TML); request.setAttribute(WGACore.ATTRIB_URI_HASH, WGUtils.createMD5HEX(request.getRequestURI().getBytes("UTF-8"))); request.setAttribute(WGACore.ATTRIB_FORMDATA, formData); request.setAttribute(WGACore.ATTRIB_COOKIES, fetchHttpCookies(request)); // Determine tml design for this request WGA wga = WGA.get(request, response, getCore()); Design outerLayout = null; if (path.getLayoutKey() != null) { outerLayout = wga.design(database).resolve(path.getLayoutKey()); WGTMLModule tmlLib = outerLayout.getTMLModule(mediaKey); if (tmlLib != null && tmlLib.isDirectAccessAllowed() == false) { throw new HttpErrorException(java.net.HttpURLConnection.HTTP_FORBIDDEN, "This design is not allowed for direct access: " + tmlLib.getName() + " (" + tmlLib.getMediaKey() + ")", path.getDatabaseKey()); } } else { WGStructEntry entry = content.getStructEntry(); if (entry == null) { throw new HttpErrorException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Content " + content.getContentKey().toString() + " has no struct entry", path.getDatabaseKey()); } outerLayout = wga.design(database).resolve(entry.getContentType().getOuterLayoutName()); } request.setAttribute(WGACore.ATTRIB_OUTER_DESIGN, outerLayout.getBaseReference().getResourceName()); // If AJAX read the AJAX data and use WebTML module from there AjaxInfo ajaxInfo = null; if (encAjaxInfo != null) { ajaxInfo = readAjaxInformation(request, database, encAjaxInfo); ajax = true; WGTMLModule tmlLib = getAjaxTMLModule(request, database, ajaxInfo); outerLayout = wga.design(tmlLib.getDatabase()).resolve(tmlLib.getName()); mediaKey = tmlLib.getMediaKey(); } // Set these here for once, so the following scripts can fetch them. Might be changed by the renderer. MediaKey mediaKeyObj = _core.getMediaKey(mediaKey); request.setAttribute(WGACore.ATTRIB_MIMETYPE, mediaKeyObj.getMimeType()); request.setAttribute(WGACore.ATTRIB_MEDIAKEY, mediaKeyObj.getKey()); // Update usage statistics getCore().getUsageStatistics().addRequestStatistic(request, session, database, tmlUserProfile); // Prepare WebTML environment TMLContext mainContext = new WebTMLEnvironmentBuilder(getCore(), content, request, response, tmlUserProfile, ajaxInfo).prepareWebTmlEnvironment(); // Dispatch try { rootDispatch(wga, outerLayout, mainContext, mediaKey); // Eventually do redirect if (request.getAttribute(WGACore.ATTRIB_REDIRECT) != null) { if (!ajax) { // On AJAX requests the redirect is performed by Root.tmlEndTag() if (!response.isCommitted()) { if (!session.isNew()) { // on new sessions we must not reset the response (#00000147) response.reset(); } response.sendRedirect(String.valueOf(request.getAttribute(WGACore.ATTRIB_REDIRECT))); } else { // Out of luck for redirect. We only can log that we could not redirect getCore().getLog() .warn("Unable to perform redirect to '" + String.valueOf(request.getAttribute(WGACore.ATTRIB_REDIRECT)) + "' because response was already committed"); } } } } catch (Exception t) { throw t; } finally { if (info != null) { info.setMimeType((String) request.getAttribute(WGACore.ATTRIB_MIMETYPE)); info.setPath(path); info.setDesign(outerLayout.getTMLModule((String) request.getAttribute(WGACore.ATTRIB_MEDIAKEY))); info.setAjax(ajax); } TMLContext.clearThreadMainContext(); } }