List of usage examples for javax.servlet.http HttpServletResponse reset
public void reset();
From source file:de.innovationgate.wgpublisher.WGPDispatcher.java
private void dispatchStaticTmlRequest(WGPRequestPath path, javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws java.lang.Exception { // do not static requests WGARequestInformation info = (WGARequestInformation) request .getAttribute(WGARequestInformation.REQUEST_ATTRIBUTENAME); if (info != null) { info.setType(WGARequestInformation.TYPE_STATIC); }// w ww.j ava 2s. c o m // Fetch the database WGDatabase database = path.getDatabase(); String contentKey = path.getContentKey(); String jspName = path.getResourcePath(); WGContent content = null; if (database != null) { LanguageBehaviour langBehaviour = LanguageBehaviourTools.retrieve(database); // Determine the content for this request if (contentKey != null) { content = getContentByAnyKey(contentKey, database, request); if (content == null) { if (request.getQueryString() != null && request.getQueryString().toLowerCase().indexOf("login") != -1) { sendRedirect(request, response, getLoginURL(request, database, path.getCompleteURL())); } else { throw new HttpErrorException(404, "No content of name/id " + contentKey, path.getDatabaseKey()); } return; } if (!content.isVisible() && !isBrowserInterface(request.getSession())) { throw new HttpErrorException(404, "No content of name/id " + contentKey, path.getDatabaseKey()); } } else { WGLanguage lang = langBehaviour.requestSelectDatabaseLanguage(database, request); content = database.getDummyContent(lang.getName()); } // 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()); } request.setAttribute(WGACore.ATTRIB_MEDIAKEY, database.getAttribute(WGACore.DBATTRIB_DEFAULT_MEDIAKEY)); } // Set context attributes for jsps request.setAttribute(WGACore.ATTRIB_WGPPATH, getPublisherURL(request)); request.setAttribute(WGACore.ATTRIB_TAGIDS, new ConcurrentHashMap<String, BaseTagStatus>()); request.setAttribute(WGACore.ATTRIB_REQUESTURL, path.getCompleteURL()); request.setAttribute(WGACore.ATTRIB_REQUESTTYPE, REQUESTTYPE_STATICTML); // Prepare WebTML environment TMLContext mainContext = new WebTMLEnvironmentBuilder(getCore(), content, request, response, null, null) .prepareWebTmlEnvironment(); String mimeType = null; if (contentKey != null) { mimeType = this.getServletContext().getMimeType(jspName); } else { mimeType = this.getServletContext().getMimeType(request.getRequestURI()); } if (mimeType == null) { mimeType = "text/html"; } request.setAttribute(WGACore.ATTRIB_MIMETYPE, mimeType); response.setContentType(mimeType); String targetJSP = jspName + ".jsp"; if (!"HEAD".equalsIgnoreCase(request.getMethod())) { this.getServletContext().getRequestDispatcher(targetJSP).include(request, response); } // Eventually do redirect if (request.getAttribute(WGACore.ATTRIB_REDIRECT) != null) { response.reset(); response.sendRedirect(String.valueOf(request.getAttribute(WGACore.ATTRIB_REDIRECT))); } }
From source file:com.swingtech.apps.filemgmt.controller.StreamingViewRenderer.java
@Override protected void renderMergedOutputModel(Map objectMap, HttpServletRequest request, HttpServletResponse response) throws Exception { InputStream dataStream = (InputStream) objectMap.get(DownloadConstants.INPUT_STREAM); if (dataStream == null) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return;//from ww w . j a v a 2s .c om } long length = (Long) objectMap.get(DownloadConstants.CONTENT_LENGTH); String fileName = (String) objectMap.get(DownloadConstants.FILENAME); Date lastModifiedObj = (Date) objectMap.get(DownloadConstants.LAST_MODIFIED); if (StringUtils.isEmpty(fileName) || lastModifiedObj == null) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } long lastModified = lastModifiedObj.getTime(); String contentType = (String) objectMap.get(DownloadConstants.CONTENT_TYPE); // 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 && HttpUtils.matches(ifNoneMatch, fileName)) { response.setHeader("ETag", fileName); // 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", fileName); // 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 && !HttpUtils.matches(ifMatch, fileName)) { 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; } String ifRange = request.getHeader("If-Range"); if (ifRange != null && !ifRange.equals(fileName)) { try { long ifRangeTime = request.getDateHeader("If-Range"); // Throws // IAE // if // invalid. if (ifRangeTime != -1) { 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 = StringUtils.sublong(part, 0, part.indexOf("-")); long end = StringUtils.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 content disposition. 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"; } else if (!contentType.startsWith("image")) { // 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. String accept = request.getHeader("Accept"); disposition = accept != null && HttpUtils.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", fileName); response.setDateHeader("Last-Modified", lastModified); response.setDateHeader("Expires", System.currentTimeMillis() + DEFAULT_EXPIRE_TIME); // Send requested file (part(s)) to client // ------------------------------------------------ // Prepare streams. InputStream input = null; OutputStream output = null; try { // Open streams. input = new BufferedInputStream(dataStream); 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); response.setHeader("Content-Length", String.valueOf(r.length)); copy(input, output, length, 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. // Copy single part range. copy(input, output, length, r.start, r.length); } else { // Return multiple parts of file. response.setContentType("multipart/byteranges; boundary=" + MULTIPART_BOUNDARY); response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206. // 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, length, r.start, r.length); } // End with multipart boundary. sos.println(); sos.println("--" + MULTIPART_BOUNDARY + "--"); } } finally { // Gently close streams. close(output); close(input); close(dataStream); } }
From source file:com.harrywu.springweb.common.StreamingViewRenderer.java
@Override public void renderMergedOutputModel(Map<String, Object> objectMap, HttpServletRequest request, HttpServletResponse response) throws Exception { InputStream dataStream = (InputStream) objectMap.get(INPUT_STREAM); if (dataStream == null) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return;/*ww w . j ava 2 s . co m*/ } long length = (Long) objectMap.get(CONTENT_LENGTH); String fileName = (String) objectMap.get(FILENAME); Date lastModifiedObj = (Date) objectMap.get(LAST_MODIFIED); if (StringUtils.isEmpty(fileName) || lastModifiedObj == null) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } long lastModified = lastModifiedObj.getTime(); String contentType = (String) objectMap.get(CONTENT_TYPE); // 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, fileName)) { response.setHeader("ETag", fileName); // 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", fileName); // 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, fileName)) { 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; } String ifRange = request.getHeader("If-Range"); if (ifRange != null && !ifRange.equals(fileName)) { try { long ifRangeTime = request.getDateHeader("If-Range"); // Throws // IAE // if // invalid. if (ifRangeTime != -1) { 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 content disposition. 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"; } else if (!contentType.startsWith("image")) { // 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. 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", fileName); response.setDateHeader("Last-Modified", lastModified); response.setDateHeader("Expires", System.currentTimeMillis() + DEFAULT_EXPIRE_TIME); // Send requested file (part(s)) to client // ------------------------------------------------ // Prepare streams. InputStream input = null; OutputStream output = null; try { // Open streams. input = new BufferedInputStream(dataStream); 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); response.setHeader("Content-Length", String.valueOf(r.length)); copy(input, output, length, 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. // Copy single part range. copy(input, output, length, r.start, r.length); } else { // Return multiple parts of file. response.setContentType("multipart/byteranges; boundary=" + MULTIPART_BOUNDARY); response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206. // 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, length, r.start, r.length); } // End with multipart boundary. sos.println(); sos.println("--" + MULTIPART_BOUNDARY + "--"); } } finally { // Gently close streams. close(output); close(input); close(dataStream); } }
From source file:fll.web.api.SubjectiveScoresServlet.java
@SuppressFBWarnings(value = { "SQL_PREPARED_STATEMENT_GENERATED_FROM_NONCONSTANT_STRING" }, justification = "columns and category are dynamic") @Override//from w w w.ja v a 2 s. c o m protected final void doPost(final HttpServletRequest request, final HttpServletResponse response) throws IOException, ServletException { int numModified = 0; final ObjectMapper jsonMapper = new ObjectMapper(); final ServletContext application = getServletContext(); final ChallengeDescription challengeDescription = ApplicationAttributes .getChallengeDescription(application); Connection connection = null; PreparedStatement deletePrep = null; PreparedStatement noShowPrep = null; PreparedStatement insertPrep = null; try { final DataSource datasource = ApplicationAttributes.getDataSource(application); connection = datasource.getConnection(); final int currentTournament = Queries.getCurrentTournament(connection); final StringWriter debugWriter = new StringWriter(); IOUtils.copy(request.getReader(), debugWriter); if (LOGGER.isTraceEnabled()) { LOGGER.trace("Read data: " + debugWriter.toString()); } final Reader reader = new StringReader(debugWriter.toString()); final Map<String, Map<String, Map<Integer, SubjectiveScore>>> allScores = jsonMapper.readValue(reader, ScoresTypeInfo.INSTANCE); for (final Map.Entry<String, Map<String, Map<Integer, SubjectiveScore>>> catEntry : allScores .entrySet()) { final String category = catEntry.getKey(); final ScoreCategory categoryDescription = challengeDescription .getSubjectiveCategoryByName(category); deletePrep = connection.prepareStatement("DELETE FROM " + category // + " WHERE TeamNumber = ?" // + " AND Tournament = ?" // + " AND Judge = ?" // ); deletePrep.setInt(2, currentTournament); noShowPrep = connection.prepareStatement("INSERT INTO " + category // + "(TeamNumber, Tournament, Judge, NoShow) VALUES(?, ?, ?, ?)"); noShowPrep.setInt(2, currentTournament); noShowPrep.setBoolean(4, true); final int NUM_COLUMNS_BEFORE_GOALS = 6; insertPrep = createInsertStatement(connection, categoryDescription); insertPrep.setInt(2, currentTournament); insertPrep.setBoolean(4, false); for (final Map.Entry<String, Map<Integer, SubjectiveScore>> judgeEntry : catEntry.getValue() .entrySet()) { final String judgeId = judgeEntry.getKey(); deletePrep.setString(3, judgeId); noShowPrep.setString(3, judgeId); insertPrep.setString(3, judgeId); for (final Map.Entry<Integer, SubjectiveScore> teamEntry : judgeEntry.getValue().entrySet()) { final int teamNumber = teamEntry.getKey(); final SubjectiveScore score = teamEntry.getValue(); if (score.getModified()) { deletePrep.setInt(1, teamNumber); noShowPrep.setInt(1, teamNumber); insertPrep.setInt(1, teamNumber); insertPrep.setString(5, score.getNote()); ++numModified; if (score.getDeleted()) { if (LOGGER.isTraceEnabled()) { LOGGER.trace("Deleting team: " + teamNumber + " judge: " + judgeId + " category: " + category); } deletePrep.executeUpdate(); } else if (score.getNoShow()) { if (LOGGER.isTraceEnabled()) { LOGGER.trace("NoShow team: " + teamNumber + " judge: " + judgeId + " category: " + category); } deletePrep.executeUpdate(); noShowPrep.executeUpdate(); } else { if (LOGGER.isTraceEnabled()) { LOGGER.trace("scores for team: " + teamNumber + " judge: " + judgeId + " category: " + category); } int goalIndex = 0; for (final AbstractGoal goalDescription : categoryDescription.getGoals()) { if (!goalDescription.isComputed()) { final String goalName = goalDescription.getName(); if (goalDescription.isEnumerated()) { final String value = score.getEnumSubScores().get(goalName); if (null == value) { insertPrep.setNull(goalIndex + NUM_COLUMNS_BEFORE_GOALS, Types.VARCHAR); } else { insertPrep.setString(goalIndex + NUM_COLUMNS_BEFORE_GOALS, value.trim()); } } else { final Double value = score.getStandardSubScores().get(goalName); if (null == value) { insertPrep.setNull(goalIndex + NUM_COLUMNS_BEFORE_GOALS, Types.DOUBLE); } else { insertPrep.setDouble(goalIndex + NUM_COLUMNS_BEFORE_GOALS, value); } } ++goalIndex; } // not computed } // end for deletePrep.executeUpdate(); insertPrep.executeUpdate(); } } // is modified } // foreach team score } // foreach judge SQLFunctions.close(deletePrep); deletePrep = null; SQLFunctions.close(noShowPrep); noShowPrep = null; SQLFunctions.close(insertPrep); insertPrep = null; } // foreach category UploadSubjectiveData.removeNullSubjectiveRows(connection, currentTournament, challengeDescription); final Tournament tournament = Tournament.findTournamentByID(connection, currentTournament); tournament.recordSubjectiveModified(connection); final UploadResult result = new UploadResult(true, "Successfully uploaded scores", numModified); response.reset(); response.setContentType("application/json"); final PrintWriter writer = response.getWriter(); jsonMapper.writeValue(writer, result); } catch (final SQLException sqle) { LOGGER.error("Error uploading scores", sqle); final UploadResult result = new UploadResult(false, sqle.getMessage(), numModified); response.reset(); response.setContentType("application/json"); final PrintWriter writer = response.getWriter(); jsonMapper.writeValue(writer, result); } finally { SQLFunctions.close(deletePrep); SQLFunctions.close(noShowPrep); SQLFunctions.close(insertPrep); SQLFunctions.close(connection); } }
From source file:eionet.gdem.web.FileDownloadServlet.java
/** * Process the actual request./*from w ww. ja v a2 s . 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. * @throws ServletException If an error occurs. */ private void processRequest(HttpServletRequest request, HttpServletResponse response, boolean content) throws IOException, ServletException { String urlPath = URLDecoder .decode(StringUtils.substringAfter(request.getRequestURI(), request.getContextPath()), "UTF-8"); String filePath = Properties.appRootFolder + urlPath; String securityMessage = checkPermissions(request, urlPath); if (securityMessage != null) { handleNotAuthorised(securityMessage, request, response); return; } // Get the file object from the file store File file = new File(filePath); // If file was not found, send 404. if (file == null || !file.exists() || !file.isFile()) { handleFileNotFound("Could not find file by the following URI: " + request.getRequestURI(), request, response); 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; // 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.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; } // 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 = "text/plain"; } // 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, 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. if (contentType.startsWith("text")) { String acceptEncoding = request.getHeader("Accept-Encoding"); acceptsGzip = acceptEncoding != null && accepts(acceptEncoding, "gzip"); contentType += ";charset=UTF-8"; } 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", System.currentTimeMillis() + DEFAULT_EXPIRE_TIME); // 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:eionet.eunis.servlets.DownloadServlet.java
/** * Process the actual request.//from w w w . jav a 2 s . 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. * @throws ServletException */ private void processRequest(HttpServletRequest request, HttpServletResponse response, boolean content) throws IOException, ServletException { String requestURI = request.getRequestURI(); String contextPath = request.getContextPath(); String pathInfo = request.getPathInfo(); String servletPath = request.getServletPath(); // Create the abstract file reference to the requested file. File file = null; String fileRelativePath = StringUtils.substringAfter(request.getRequestURI(), request.getContextPath()); fileRelativePath = StringUtils.replace(fileRelativePath, "%20", " "); if (StringUtils.isNotEmpty(fileRelativePath) && StringUtils.isNotEmpty(appHome)) { file = new File(appHome, fileRelativePath); } // If file was not found, send 404. if (file == null || !file.exists() || file.isDirectory()) { 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; // 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.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; } // 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. // 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. if (contentType.startsWith("text")) { String acceptEncoding = request.getHeader("Accept-Encoding"); acceptsGzip = acceptEncoding != null && accepts(acceptEncoding, "gzip"); contentType += ";charset=UTF-8"; } 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", System.currentTimeMillis() + DEFAULT_EXPIRE_TIME); // 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:de.innovationgate.wgpublisher.WGPDispatcher.java
public boolean dispatchErrorTmlRequest(WGAError error, javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) { try {/*from w w w . jav a2 s .co m*/ if (error.getCausingDatabase() == null) { return false; } HttpSession session = request.getSession(); // Parse request WGPRequestPath path = (WGPRequestPath) request.getAttribute(WGACore.ATTRIB_REQUESTPATH); if (path == null) { path = WGPRequestPath.parseRequest(this, request, response); if (path == null) return false; request.setAttribute(WGACore.ATTRIB_REQUESTPATH, path); } // Again fetch the wrapped request and response created by the filter, as we are outside it here and we have again the raw request/response object HttpServletRequest wrappedRequest = (HttpServletRequest) request .getAttribute(WGAFilter.REQATTRIB_REQUEST_WRAPPER); if (wrappedRequest != null) { request = wrappedRequest; } HttpServletResponse wrappedResponse = (HttpServletResponse) request .getAttribute(WGAFilter.REQATTRIB_RESPONSE_WRAPPER); if (wrappedResponse != null) { response = wrappedResponse; } // Determine tml design for this request WGA wga = WGA.get(request, response, getCore()); WGDatabase errorDatabase = getCore().getContentdbs().get(error.getCausingDatabase()); if (!errorDatabase.isSessionOpen() && !wga.openDatabase(errorDatabase)) { return false; } WGTMLModule tmlLib = determineErrorModule(errorDatabase, wga, error); if (tmlLib == null) { return false; } WGContent content = errorDatabase.getDummyContent(path == null ? null : path.getRequestLanguage()); // Personalize TMLUserProfile tmlUserProfile = null; WGTransientPortletRegistry portletRegistry = null; TMLPortletStateStorage portletStateStorage = null; try { tmlUserProfile = getCore().getPersManager().prepareUserProfileForRequest(request, response, content, errorDatabase, null, false); } catch (Exception e) { _log.error("Unable to personalize WebTML request " + path.getCompleteURL(), e); } // Set context attributes for tml 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_MIMETYPE, "text/html"); request.setAttribute(WGACore.ATTRIB_MEDIAKEY, "html"); 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, null); request.setAttribute(WGACore.ATTRIB_OUTER_DESIGN, tmlLib.getName()); request.setAttribute(WGACore.ATTRIB_OUTER_DESIGN_DB, tmlLib.getDatabase().getDbReference()); request.setAttribute(WGACore.ATTRIB_COOKIES, fetchHttpCookies(request)); // TML Cache control response.setHeader("Pragma", "No-Cache"); response.setHeader("Cache-Control", "No-Cache"); // Prepare WebTML environment TMLContext mainContext = new WebTMLEnvironmentBuilder(getCore(), content, request, response, tmlUserProfile, null).prepareWebTmlEnvironment(); // Change path type to TML, so the WebTML rendering works normally path.setPathType(WGPRequestPath.TYPE_TML); path.setMediaKey(_core.getMediaKey("html")); // Dispatch to jsp rootDispatch(wga, wga.design(tmlLib.getDatabase()).resolve(tmlLib.getName()), mainContext, "html"); // Eventually do redirect if (request.getAttribute(WGACore.ATTRIB_REDIRECT) != null) { 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))); } } return true; } catch (Exception t) { getCore().getLog().error("Exception handling error request", t); if (!response.isCommitted()) { response.reset(); } return false; } finally { WGFactory.getInstance().closeSessions(); TMLContext.clearThreadMainContext(); } }
From source file:org.apache.openmeetings.core.servlet.outputhandler.DownloadHandler.java
@Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try {// w ww. j a v a 2 s.co m request.setCharacterEncoding(StandardCharsets.UTF_8.name()); log.debug("\nquery = " + request.getQueryString()); log.debug("\n\nfileName = " + request.getParameter("fileName")); log.debug("\n\nparentPath = " + request.getParameter("parentPath")); String queryString = request.getQueryString(); if (queryString == null) { queryString = ""; } String sid = request.getParameter("sid"); if (sid == null) { sid = "default"; } log.debug("sid: " + sid); Long users_id = getBean(SessiondataDao.class).check(sid); Set<Right> rights = getBean(UserDao.class).getRights(users_id); if (rights != null && !rights.isEmpty()) { String room_id = request.getParameter("room_id"); if (room_id == null) { room_id = "default"; } String moduleName = request.getParameter("moduleName"); if (moduleName == null) { moduleName = "nomodule"; } String parentPath = request.getParameter("parentPath"); if (parentPath == null) { parentPath = "nomodule"; } String requestedFile = request.getParameter("fileName"); if (requestedFile == null) { requestedFile = ""; } String fileIdParam = request.getParameter("fileId"); Long fileId = null; if (fileIdParam != null) { fileId = Long.valueOf(fileIdParam); } // make a complete name out of domain(group) + 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 = request.getParameter("remoteUserid"); working_dir = OmFileHelper .getUploadProfilesUserDir(remoteUser_id == null ? "0" : remoteUser_id); logNonExistentFolder(working_dir); } else if (moduleName.equals("remoteuserprofilebig")) { String remoteUser_id = request.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 = request.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 = defaultImageName; if (moduleName.equals("remoteuserprofile")) { requestedFile = defaultProfileImageName; } else if (moduleName.equals("remoteuserprofilebig")) { requestedFile = defaultProfileImageNameBig; } else if (moduleName.equals("userprofile")) { requestedFile = defaultProfileImageName; } else if (moduleName.equals("chat")) { requestedFile = defaultChatImageName; } } else if (requestedFile.endsWith(".swf")) { requestedFile = defaultSWFName; } else { requestedFile = defaultImageName; } full_path = new File(OmFileHelper.getDefaultDir(), requestedFile); } log.debug("full_path: " + full_path); if (!full_path.exists() || !full_path.canRead()) { 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 (request.getHeader("User-Agent") != null) { if ((request.getHeader("User-Agent").contains("Firefox")) || (request.getHeader("User-Agent").contains("Opera"))) { browserType = 1; } } log.debug("Detected browser type:" + browserType); response.reset(); response.resetBuffer(); try (OutputStream out = response.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 response.setContentType("application/x-shockwave-flash"); response.setHeader("Content-Length", "" + full_path.length()); } else { response.setContentType("APPLICATION/OCTET-STREAM"); String fileNameResult = requestedFile; if (fileId != null && fileId > 0) { FileExplorerItem fileExplorerItem = getBean(FileExplorerItemDao.class).get(fileId); if (fileExplorerItem != null) { fileNameResult = fileExplorerItem.getName().substring(0, fileExplorerItem.getName().length() - 4) + fileNameResult.substring(fileNameResult.length() - 4, fileNameResult.length()); } } if (browserType == 0) { response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileNameResult, StandardCharsets.UTF_8.name())); } else { response.setHeader("Content-Disposition", "attachment; filename*=UTF-8'en'" + URLEncoder.encode(fileNameResult, StandardCharsets.UTF_8.name())); } response.setHeader("Content-Length", "" + full_path.length()); } OmFileHelper.copyFile(full_path, out); out.flush(); } } } else { log.error("ERROR DownloadHandler: not authorized FileDownload "); } } catch (ServerNotInitializedException e) { return; } catch (Exception er) { log.error("Error downloading: ", er); } }
From source file:edu.chalmers.dat076.moviefinder.controller.FileController.java
/** * Process the actual request./*w w w .ja va 2 s . 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. */ private void processRequest(HttpServletRequest request, HttpServletResponse response, boolean content, String path, String defaultContentType) throws IOException { // Validate the requested file ------------------------------------------------------------ // URL-decode the file name (might contain spaces and on) and prepare file object. File file = new File(path); // 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() + FileControllerUtils.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 && FileControllerUtils.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 && !FileControllerUtils.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<>(); // 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 = FileControllerUtils.sublong(part, 0, part.indexOf("-")); long end = FileControllerUtils.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 = request.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 = defaultContentType; //} // 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 && FileControllerUtils.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 && FileControllerUtils.accepts(accept, contentType) ? "inline" : "attachment"; } // Initialize response. response.reset(); response.setBufferSize(FileControllerUtils.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, FileControllerUtils.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. FileControllerUtils.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. FileControllerUtils.copy(input, output, r.start, r.length); } } else { // Return multiple parts of file. response.setContentType("multipart/byteranges; boundary=" + FileControllerUtils.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("--" + FileControllerUtils.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. FileControllerUtils.copy(input, output, r.start, r.length); } // End with multipart boundary. sos.println(); sos.println("--" + FileControllerUtils.MULTIPART_BOUNDARY + "--"); } } } finally { // Gently close streams. FileControllerUtils.close(output); FileControllerUtils.close(input); } }