List of usage examples for javax.servlet.http HttpServletResponse reset
public void reset();
From source file:httpUtils.HttpUtils.java
/** * Parse the request headers, build the response, stream back file * @param request/*from w w w .ja v a2s . c om*/ * @param response * @param dataStream * @param fileLength * @param fileName * @param fileLastModified * @param contentType * @return */ private static HttpServletResponse getFileAsStream(HttpServletRequest request, HttpServletResponse response, InputStream dataStream, long fileLength, String fileName, long fileLastModified, String contentType) { if (dataStream == null) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); return response; } if (StringUtils.isEmpty(fileName) || fileLastModified == 0L) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return response; } String ifNoneMatch = request.getHeader("If-None-Match"); if (ifNoneMatch != null && matches(ifNoneMatch, fileName)) { response.setHeader("ETag", fileName); response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return response; } long ifModifiedSince = request.getDateHeader("If-Modified-Since"); if (ifNoneMatch == null && ifModifiedSince != -1 && ifModifiedSince + 1000 > fileLastModified) { response.setHeader("ETag", fileName); response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return response; } String ifMatch = request.getHeader("If-Match"); if (ifMatch != null && !matches(ifMatch, fileName)) { response.setStatus(HttpServletResponse.SC_PRECONDITION_FAILED); return response; } long ifUnmodifiedSince = request.getDateHeader("If-Unmodified-Since"); if (ifUnmodifiedSince != -1 && ifUnmodifiedSince + 1000 <= fileLastModified) { response.setStatus(HttpServletResponse.SC_PRECONDITION_FAILED); return response; } Range full = new Range(0, fileLength - 1, fileLength); List<Range> ranges = new ArrayList<Range>(); String range = request.getHeader("Range"); if (range != null) { if (!range.matches("^bytes=\\d*-\\d*(,\\d*-\\d*)*$")) { response.setHeader("Content-Range", "bytes */" + fileLength); response.setStatus(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); return response; } String ifRange = request.getHeader("If-Range"); if (ifRange != null && !ifRange.equals(fileName)) { try { long ifRangeTime = request.getDateHeader("If-Range"); if (ifRangeTime != -1) { ranges.add(full); } } catch (IllegalArgumentException ignore) { ranges.add(full); } } 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 = fileLength - end; end = fileLength - 1; } else if (end == -1 || end > fileLength - 1) { end = fileLength - 1; } // Check if Range is syntactically valid. If not, then // return 416. if (start > end) { response.setHeader("Content-Range", "bytes */" + fileLength); // Required // in // 416. response.setStatus(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); return response; } // Add range. ranges.add(new Range(start, end, fileLength)); } } } // 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(HttpUtils.DEFAULT_BUFFER_SIZE); response.setHeader("Content-Disposition", disposition + ";filename=\"" + fileName + "\""); response.setHeader("Accept-Ranges", "bytes"); response.setHeader("ETag", fileName); response.setDateHeader("Last-Modified", fileLastModified); response.setDateHeader("Expires", System.currentTimeMillis() + HttpUtils.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, fileLength, 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, fileLength, r.start, r.length); } else { // Return multiple parts of file. response.setContentType("multipart/byteranges; boundary=" + HttpUtils.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("--" + HttpUtils.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, fileLength, r.start, r.length); } // End with multipart boundary. sos.println(); sos.println("--" + HttpUtils.MULTIPART_BOUNDARY + "--"); } } catch (Exception e) { log.error("get file as stream failed", e); } finally { // Gently close streams. close(output); close(input); close(dataStream); } return response; }
From source file:org.apache.roller.weblogger.ui.rendering.servlets.PlanetFeedServlet.java
/** * Handle GET requests for weblog pages. *//* w ww . j av a 2s .com*/ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { log.debug("Entering"); PlanetManager planet = PlanetFactory.getPlanet().getPlanetManager(); PlanetRequest planetRequest = null; try { planetRequest = new PlanetRequest(request); } catch (Exception e) { // some kind of error parsing the request log.debug("error creating planet request", e); response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // figure planet last modified date Date lastModified = planetCache.getLastModified(); // Respond with 304 Not Modified if it is not modified. if (ModDateHeaderUtil.respondIfNotModified(request, response, lastModified.getTime())) { return; } // set content type String accepts = request.getHeader("Accept"); String userAgent = request.getHeader("User-Agent"); if (accepts != null && userAgent != null && accepts.indexOf("*/*") != -1 && userAgent.startsWith("Mozilla")) { // client is a browser and now that we offer styled feeds we want // browsers to load the page rather than popping up the download // dialog, so we provide a content-type that browsers will display response.setContentType("text/xml"); } else { response.setContentType("application/rss+xml; charset=utf-8"); } // set last-modified date ModDateHeaderUtil.setLastModifiedHeader(response, lastModified.getTime()); // cached content checking String cacheKey = PlanetCache.CACHE_ID + ":" + this.generateKey(planetRequest); CachedContent entry = (CachedContent) planetCache.get(cacheKey); if (entry != null) { response.setContentLength(entry.getContent().length); response.getOutputStream().write(entry.getContent()); return; } // looks like we need to render content @SuppressWarnings("unchecked") HashMap<String, Object> model = new HashMap(); try { // populate the rendering model if (request.getParameter("group") != null) { Planet planetObject = planet.getPlanet("default"); model.put("group", planet.getGroup(planetObject, request.getParameter("group"))); } model.put("planet", planet); model.put("date", new Date()); model.put("utils", new UtilitiesModel()); model.put("siteName", PlanetRuntimeConfig.getProperty("site.name")); model.put("siteDescription", PlanetRuntimeConfig.getProperty("site.description")); model.put("lastModified", lastModified); if (StringUtils.isNotEmpty(PlanetRuntimeConfig.getProperty("site.absoluteurl"))) { model.put("absoluteSite", PlanetRuntimeConfig.getProperty("site.absoluteurl")); } else { model.put("absoluteSite", WebloggerRuntimeConfig.getAbsoluteContextURL()); } model.put("feedStyle", new Boolean(WebloggerRuntimeConfig.getBooleanProperty("site.newsfeeds.styledFeeds"))); int numEntries = WebloggerRuntimeConfig.getIntProperty("site.newsfeeds.defaultEntries"); int entryCount = numEntries; String sCount = request.getParameter("count"); if (sCount != null) { try { entryCount = Integer.parseInt(sCount); } catch (NumberFormatException e) { log.warn("Improperly formatted count parameter"); } if (entryCount > numEntries) { entryCount = numEntries; } if (entryCount < 0) { entryCount = 0; } } model.put("entryCount", new Integer(entryCount)); } catch (Exception ex) { log.error("Error loading model objects for page", ex); if (!response.isCommitted()) { response.reset(); } response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } // lookup Renderer we are going to use Renderer renderer = null; try { log.debug("Looking up renderer"); Template template = new StaticTemplate("templates/planet/planetrss.vm", "velocity"); renderer = RendererManager.getRenderer(template, DeviceType.mobile); } catch (Exception e) { // nobody wants to render my content :( log.error("Couldn't find renderer for planet rss", e); if (!response.isCommitted()) { response.reset(); } response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // render content. use default size of about 24K for a standard page CachedContent rendererOutput = new CachedContent(24567); try { log.debug("Doing rendering"); renderer.render(model, rendererOutput.getCachedWriter()); // flush rendered output and close rendererOutput.flush(); rendererOutput.close(); } catch (Exception e) { // bummer, error during rendering log.error("Error during rendering for planet rss", e); if (!response.isCommitted()) { response.reset(); } response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // post rendering process // flush rendered content to response log.debug("Flushing response output"); response.setContentLength(rendererOutput.getContent().length); response.getOutputStream().write(rendererOutput.getContent()); // cache rendered content. this.planetCache.put(cacheKey, rendererOutput); log.debug("Exiting"); }
From source file:com.palantir.stash.stashbot.servlet.BuildStatusReportingServlet.java
@Override public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { try {// w ww .ja v a 2 s .co m // Look at JenkinsManager class if you change this: // final two arguments could be empty... final String URL_FORMAT = "BASE_URL/REPO_ID_OR_SLUG/PULLREQUEST_ID]"; final String pathInfo = req.getPathInfo(); final String[] parts = pathInfo.split("/"); // need at *least* 3 parts to be correct if (parts.length < 3) { throw new IllegalArgumentException("The format of the URL is " + URL_FORMAT); } // Last part is always the PR String pullRequestPart = parts[parts.length - 1]; // First part is always empty because string starts with '/', last is pr, the rest is the slug String slugOrId = StringUtils.join(Arrays.copyOfRange(parts, 1, parts.length - 1), "/"); Repository repo; try { int repoId = Integer.valueOf(slugOrId); repo = rs.getById(repoId); if (repo == null) { throw new IllegalArgumentException("Unable to find repository for repo id " + repoId); } } catch (NumberFormatException e) { // we have a slug, try to get a repo ID from that // slug should look like this: projects/PROJECT_KEY/repos/REPO_SLUG/pull-requests String[] newParts = slugOrId.split("/"); if (newParts.length != 5) { throw new IllegalArgumentException( "The format of the REPO_ID_OR_SLUG is an ID, or projects/PROJECT_KEY/repos/REPO_SLUG/pull-requests"); } Project p = ps.getByKey(newParts[1]); if (p == null) { throw new IllegalArgumentException("Unable to find project for project key" + newParts[1]); } repo = rs.getBySlug(p.getKey(), newParts[3]); if (repo == null) { throw new IllegalArgumentException("Unable to find repository for project key" + newParts[1] + " and repo slug " + newParts[3]); } } final long pullRequestId; final PullRequest pullRequest; try { pullRequestId = Long.parseLong(pullRequestPart); } catch (NumberFormatException e) { throw new IllegalArgumentException("Unable to parse pull request id " + parts[7], e); } pullRequest = prs.getById(repo.getId(), pullRequestId); if (pullRequest == null) { throw new IllegalArgumentException("Unable to find pull request for repo id " + repo.getId().toString() + " pr id " + pullRequestId); } PullRequestMergeability canMerge = prs.canMerge(repo.getId(), pullRequestId); JSONObject output = new JSONObject(); output.put("repoId", repo.getId()); output.put("prId", pullRequestId); output.put("url", nb.repo(repo).pullRequest(pullRequest.getId()).buildAbsolute()); output.put("canMerge", canMerge.canMerge()); if (!canMerge.canMerge()) { JSONArray vetoes = new JSONArray(); for (PullRequestMergeVeto prmv : canMerge.getVetos()) { JSONObject prmvjs = new JSONObject(); prmvjs.put("summary", prmv.getSummaryMessage()); prmvjs.put("details", prmv.getDetailedMessage()); vetoes.put(prmvjs); } // You might expect a conflict would be included in the list of merge blockers. You'd be mistaken. if (canMerge.isConflicted()) { JSONObject prmvjs = new JSONObject(); prmvjs.put("summary", "This pull request is unmergeable due to conflicts."); prmvjs.put("details", "You will need to resolve conflicts to be able to merge."); vetoes.put(prmvjs); } output.put("vetoes", vetoes); } log.debug("Serving build status: " + output.toString()); printOutput(output, req, res); } catch (Exception e) { res.reset(); res.setStatus(500); res.setContentType("application/json"); Writer w = res.getWriter(); try { w.append(new JSONObject().put("error", e.getMessage()).toString()); } catch (JSONException e1) { throw new RuntimeException("Errorception!", e1); } w.close(); } }
From source file:org.apache.roller.weblogger.ui.rendering.servlets.FeedServlet.java
/** * Handle GET requests for weblog feeds. *///from w w w . ja v a2 s . c o m public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { log.debug("Entering"); Weblog weblog = null; boolean isSiteWide = false; WeblogFeedRequest feedRequest = null; try { // parse the incoming request and extract the relevant data feedRequest = new WeblogFeedRequest(request); weblog = feedRequest.getWeblog(); if (weblog == null) { throw new WebloggerException("unable to lookup weblog: " + feedRequest.getWeblogHandle()); } // is this the site-wide weblog? isSiteWide = WebloggerRuntimeConfig.isSiteWideWeblog(feedRequest.getWeblogHandle()); } catch (Exception e) { // invalid feed request format or weblog doesn't exist log.debug("error creating weblog feed request", e); response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // determine the lastModified date for this content long lastModified = System.currentTimeMillis(); if (isSiteWide) { lastModified = siteWideCache.getLastModified().getTime(); } else if (weblog.getLastModified() != null) { lastModified = weblog.getLastModified().getTime(); } // Respond with 304 Not Modified if it is not modified. if (ModDateHeaderUtil.respondIfNotModified(request, response, lastModified)) { return; } // set last-modified date ModDateHeaderUtil.setLastModifiedHeader(response, lastModified); // set content type String accepts = request.getHeader("Accept"); String userAgent = request.getHeader("User-Agent"); if (WebloggerRuntimeConfig.getBooleanProperty("site.newsfeeds.styledFeeds") && accepts != null && accepts.indexOf("*/*") != -1 && userAgent != null && userAgent.startsWith("Mozilla")) { // client is a browser and feed style is enabled so we want // browsers to load the page rather than popping up the download // dialog, so we provide a content-type that browsers will display response.setContentType("text/xml"); } else if ("rss".equals(feedRequest.getFormat())) { response.setContentType("application/rss+xml; charset=utf-8"); } else if ("atom".equals(feedRequest.getFormat())) { response.setContentType("application/atom+xml; charset=utf-8"); } // generate cache key String cacheKey = null; if (isSiteWide) { cacheKey = siteWideCache.generateKey(feedRequest); } else { cacheKey = weblogFeedCache.generateKey(feedRequest); } // cached content checking CachedContent cachedContent = null; if (isSiteWide) { cachedContent = (CachedContent) siteWideCache.get(cacheKey); } else { cachedContent = (CachedContent) weblogFeedCache.get(cacheKey, lastModified); } if (cachedContent != null) { log.debug("HIT " + cacheKey); response.setContentLength(cachedContent.getContent().length); response.getOutputStream().write(cachedContent.getContent()); return; } else { log.debug("MISS " + cacheKey); } // validation. make sure that request input makes sense. boolean invalid = false; if (feedRequest.getLocale() != null) { // locale view only allowed if weblog has enabled it if (!feedRequest.getWeblog().isEnableMultiLang()) { invalid = true; } } if (feedRequest.getWeblogCategoryName() != null) { // category specified. category must exist. if (feedRequest.getWeblogCategory() == null) { invalid = true; } } else if (feedRequest.getTags() != null && feedRequest.getTags().size() > 0) { try { // tags specified. make sure they exist. WeblogEntryManager wmgr = WebloggerFactory.getWeblogger().getWeblogEntryManager(); invalid = !wmgr.getTagComboExists(feedRequest.getTags(), (isSiteWide) ? null : weblog); } catch (WebloggerException ex) { invalid = true; } } if (invalid) { if (!response.isCommitted()) response.reset(); response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // do we need to force a specific locale for the request? if (feedRequest.getLocale() == null && !weblog.isShowAllLangs()) { feedRequest.setLocale(weblog.getLocale()); } // looks like we need to render content HashMap model = new HashMap(); String pageId = null; try { // determine what template to render with boolean siteWide = WebloggerRuntimeConfig.isSiteWideWeblog(weblog.getHandle()); if (siteWide && "entries".equals(feedRequest.getType()) && feedRequest.getTerm() != null) { pageId = "site-search-atom.vm"; } else if ("entries".equals(feedRequest.getType()) && feedRequest.getTerm() != null) { pageId = "feeds/weblog-search-atom.vm"; } else if (siteWide) { pageId = "site-" + feedRequest.getType() + "-" + feedRequest.getFormat() + ".vm"; } else { pageId = "weblog-" + feedRequest.getType() + "-" + feedRequest.getFormat() + ".vm"; } // populate the rendering model Map initData = new HashMap(); initData.put("parsedRequest", feedRequest); // define url strategy initData.put("urlStrategy", WebloggerFactory.getWeblogger().getUrlStrategy()); // Load models for feeds String feedModels = WebloggerConfig.getProperty("rendering.feedModels"); ModelLoader.loadModels(feedModels, model, initData, true); // Load special models for site-wide blog if (siteWide) { String siteModels = WebloggerConfig.getProperty("rendering.siteModels"); ModelLoader.loadModels(siteModels, model, initData, true); } // Load weblog custom models ModelLoader.loadCustomModels(weblog, model, initData); // Load search models if search feed if ("entries".equals(feedRequest.getType()) && feedRequest.getTerm() != null) { ModelLoader.loadModels(SearchResultsFeedModel.class.getName(), model, initData, true); } } catch (WebloggerException ex) { log.error("ERROR loading model for page", ex); if (!response.isCommitted()) response.reset(); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } // lookup Renderer we are going to use Renderer renderer = null; try { log.debug("Looking up renderer"); Template template = new StaticTemplate(pageId, "velocity"); renderer = RendererManager.getRenderer(template, MobileDeviceRepository.DeviceType.standard); } catch (Exception e) { // nobody wants to render my content :( // TODO: this log message has been disabled because it fills up // the logs with useless errors due to the fact that the way these // template ids are formed comes directly from the request and it // often gets bunk data causing invalid template ids. // at some point we should have better validation on the input so // that we can quickly dispatch invalid feed requests and only // get this far if we expect the template to be found //log.error("Couldn't find renderer for page "+pageId, e); if (!response.isCommitted()) response.reset(); response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // render content. use default size of about 24K for a standard page CachedContent rendererOutput = new CachedContent(24567); try { log.debug("Doing rendering"); renderer.render(model, rendererOutput.getCachedWriter()); // flush rendered output and close rendererOutput.flush(); rendererOutput.close(); } catch (Exception e) { // bummer, error during rendering log.error("Error during rendering for page " + pageId, e); if (!response.isCommitted()) response.reset(); response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // post rendering process // flush rendered content to response log.debug("Flushing response output"); response.setContentLength(rendererOutput.getContent().length); response.getOutputStream().write(rendererOutput.getContent()); // cache rendered content. only cache if user is not logged in? log.debug("PUT " + cacheKey); if (isSiteWide) { siteWideCache.put(cacheKey, rendererOutput); } else { weblogFeedCache.put(cacheKey, rendererOutput); } log.debug("Exiting"); }
From source file:com.tasktop.c2c.server.web.proxy.ajp.AjpProtocol.java
public void forward(HttpServletRequest request, HttpServletResponse response) throws IOException { debug(request, "forward"); Packet packet = new Packet(); packet.reset();//from ww w .j ava 2 s .c o m // AJP13_FORWARD_REQUEST packet.write(Type.REQUEST_FORWARD.code); packet.write(computeMethod(request.getMethod()).code); packet.write(request.getProtocol()); packet.write(request.getRequestURI()); packet.write(request.getRemoteAddr()); packet.write(request.getRemoteAddr()); packet.write(request.getServerName()); packet.write(request.getServerPort()); packet.write(request.isSecure()); // request headers Map<String, String> headers = new HashMap<String, String>(); @SuppressWarnings("rawtypes") Enumeration headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { String headerName = headerNames.nextElement().toString(); String headerValue = request.getHeader(headerName); headerValue = headerFilter.processRequestHeader(headerName, headerValue); if (headerValue != null) { headers.put(headerName, headerValue); } } packet.write(headers.size()); for (Map.Entry<String, String> header : headers.entrySet()) { HttpRequestHeader headerType = HttpRequestHeader.fromHeaderName(header.getKey()); if (headerType != null) { packet.write(headerType.code); } else { packet.write(header.getKey()); } String headerValue = header.getValue(); packet.write(headerValue == null ? "" : headerValue); } // request attributes Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication != null) { packet.write(Attribute.REMOTE_USER.code); packet.write(authentication.getName()); } String queryString = request.getQueryString(); if (queryString != null) { packet.write(Attribute.QUERY_STRING.code); packet.write(queryString); } // packet terminator packet.write((byte) 0xff); final Object socketKey = new AjpPoolableConnectionFactory.Key(proxyHost, proxyPort); Socket connection; try { connection = allocateSocket(socketKey); debug("allocated", connection); } catch (IOException e) { throw e; } catch (Exception e) { if (e instanceof RuntimeException) { throw (RuntimeException) e; } throw new RuntimeException(e); } boolean invalidate = true; try { OutputStream outputStream = connection.getOutputStream(); InputStream inputStream = connection.getInputStream(); packet.write(outputStream); packet.reset(); int bytesWritten = 0; int contentLength = request.getContentLength(); if (contentLength == -1) { // Unknown content length contentLength = Integer.MAX_VALUE; } ServletInputStream requestInput = request.getInputStream(); OutputStream responseOutput = null; boolean reuse = false; if (request.getHeader("Content-Length") != null) { bytesWritten += processRequestBody(packet, outputStream, bytesWritten, contentLength, requestInput, contentLength); debug("sent [" + bytesWritten + "] initial body bytes", connection); } for (;; packet.reset()) { debug("reading packet", connection); packet.read(inputStream); Type packetType = Type.fromCode(packet.readByte()); debug("received " + packetType, connection); if (packetType == Type.END_RESPONSE) { reuse = packet.readBoolean(); break; } switch (packetType) { case GET_BODY_CHUNK: int requestedSize = packet.readInt(); packet.reset(); int chunkSize = processRequestBody(packet, outputStream, bytesWritten, contentLength, requestInput, requestedSize); bytesWritten += chunkSize; debug("sent [" + chunkSize + "] bytes of body chunk", connection); break; case SEND_HEADERS: { response.reset(); int httpStatusCode = packet.readInt(); packet.readString(); // status message, not used response.setStatus(httpStatusCode); int headerCount = packet.readInt(); for (int x = 0; x < headerCount; ++x) { byte b = packet.readByte(); packet.unreadByte(); String headerName; if (b == ((byte) 0xA0)) { int headerCode = packet.readInt(); headerName = HttpResponseHeader.fromCode(headerCode).headerName; } else { headerName = packet.readString(); } String headerValue = packet.readString(); headerValue = headerFilter.processResponseHeader(headerName, headerValue); if (headerValue != null) { response.setHeader(headerName, headerValue); } } } break; case SEND_BODY_CHUNK: if (responseOutput == null) { responseOutput = response.getOutputStream(); } packet.copy(responseOutput); break; } } // ORDER DEPENDENCY: this should come last invalidate = !reuse; if (responseOutput != null) { responseOutput.close(); } } finally { if (!shareConnections) { invalidate = true; } deallocateSocket(socketKey, connection, invalidate); debug("released " + (invalidate ? "invalidate" : "reuse"), connection); } }
From source file:org.apache.roller.weblogger.ui.rendering.servlets.SearchServlet.java
/** * Handle GET requests for weblog pages. *//*from w w w. j a v a 2 s. c om*/ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { log.debug("Entering"); Weblog weblog = null; WeblogSearchRequest searchRequest = null; // first off lets parse the incoming request and validate it try { searchRequest = new WeblogSearchRequest(request); // now make sure the specified weblog really exists weblog = WebloggerFactory.getWeblogger().getWeblogManager() .getWeblogByHandle(searchRequest.getWeblogHandle(), Boolean.TRUE); } catch (Exception e) { // invalid search request format or weblog doesn't exist log.debug("error creating weblog search request", e); response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // Get the deviceType from user agent MobileDeviceRepository.DeviceType deviceType = MobileDeviceRepository.getRequestType(request); // for previews we explicitly set the deviceType attribute if (request.getParameter("type") != null) { deviceType = request.getParameter("type").equals("standard") ? MobileDeviceRepository.DeviceType.standard : MobileDeviceRepository.DeviceType.mobile; } // do we need to force a specific locale for the request? if (searchRequest.getLocale() == null && !weblog.isShowAllLangs()) { searchRequest.setLocale(weblog.getLocale()); } // lookup template to use for rendering ThemeTemplate page = null; try { // try looking for a specific search page page = weblog.getTheme().getTemplateByAction(ThemeTemplate.ACTION_SEARCH); // if not found then fall back on default page if (page == null) { page = weblog.getTheme().getDefaultTemplate(); } // if still null then that's a problem if (page == null) { throw new WebloggerException("Could not lookup default page " + "for weblog " + weblog.getHandle()); } } catch (Exception e) { log.error("Error getting default page for weblog " + weblog.getHandle(), e); } // set the content type response.setContentType("text/html; charset=utf-8"); // looks like we need to render content Map model = new HashMap(); try { PageContext pageContext = JspFactory.getDefaultFactory().getPageContext(this, request, response, "", false, 8192, true); // populate the rendering model Map initData = new HashMap(); initData.put("request", request); initData.put("pageContext", pageContext); // this is a little hacky, but nothing we can do about it // we need the 'weblogRequest' to be a pageRequest so other models // are properly loaded, which means that searchRequest needs its // own custom initData property aside from the standard weblogRequest. // possible better approach is make searchRequest extend pageRequest. WeblogPageRequest pageRequest = new WeblogPageRequest(); pageRequest.setWeblogHandle(searchRequest.getWeblogHandle()); pageRequest.setWeblogCategoryName(searchRequest.getWeblogCategoryName()); initData.put("parsedRequest", pageRequest); initData.put("searchRequest", searchRequest); // define url strategy initData.put("urlStrategy", WebloggerFactory.getWeblogger().getUrlStrategy()); // Load models for pages String searchModels = WebloggerConfig.getProperty("rendering.searchModels"); ModelLoader.loadModels(searchModels, model, initData, true); // Load special models for site-wide blog if (WebloggerRuntimeConfig.isSiteWideWeblog(weblog.getHandle())) { String siteModels = WebloggerConfig.getProperty("rendering.siteModels"); ModelLoader.loadModels(siteModels, model, initData, true); } // Load weblog custom models ModelLoader.loadCustomModels(weblog, model, initData); // ick, gotta load pre-3.0 model stuff as well :( ModelLoader.loadOldModels(model, request, response, pageContext, pageRequest, WebloggerFactory.getWeblogger().getUrlStrategy()); // manually add search model again to support pre-3.0 weblogs Model searchModel = new SearchResultsModel(); searchModel.init(initData); model.put("searchResults", searchModel); } catch (WebloggerException ex) { log.error("Error loading model objects for page", ex); if (!response.isCommitted()) response.reset(); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } // Development only. Reload if theme has been modified if (themeReload && !weblog.getEditorTheme().equals(WeblogTemplate.ACTION_CUSTOM) && (searchRequest.getPathInfo() == null || searchRequest.getPathInfo() != null && !searchRequest.getPathInfo().endsWith(".css"))) { try { ThemeManager manager = WebloggerFactory.getWeblogger().getThemeManager(); boolean reloaded = manager.reLoadThemeFromDisk(weblog.getEditorTheme()); if (reloaded) { if (WebloggerRuntimeConfig.isSiteWideWeblog(searchRequest.getWeblogHandle())) { SiteWideCache.getInstance().clear(); } else { WeblogPageCache.getInstance().clear(); } I18nMessages.reloadBundle(weblog.getLocaleInstance()); } } catch (Exception ex) { log.error("ERROR - reloading theme " + ex); } } // lookup Renderer we are going to use Renderer renderer = null; try { log.debug("Looking up renderer"); renderer = RendererManager.getRenderer(page, deviceType); } catch (Exception e) { // nobody wants to render my content :( log.error("Couldn't find renderer for rsd template", e); if (!response.isCommitted()) response.reset(); response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // render content CachedContent rendererOutput = new CachedContent(4096); try { log.debug("Doing rendering"); renderer.render(model, rendererOutput.getCachedWriter()); // flush rendered output and close rendererOutput.flush(); rendererOutput.close(); } catch (Exception e) { // bummer, error during rendering log.error("Error during rendering for rsd template", e); if (!response.isCommitted()) response.reset(); response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // post rendering process // flush rendered content to response log.debug("Flushing response output"); response.setContentLength(rendererOutput.getContent().length); response.getOutputStream().write(rendererOutput.getContent()); log.debug("Exiting"); }
From source file:org.openmeetings.servlet.outputhandler.ExportToImage.java
@Override protected void service(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException { try {// w w w. j a va2s . co m if (getUserManagement() == null || getSessionManagement() == null || getGenerateImage() == null) { return; } String sid = httpServletRequest.getParameter("sid"); if (sid == null) { sid = "default"; } log.debug("sid: " + sid); String hash = httpServletRequest.getParameter("hash"); if (hash == null) { hash = ""; } log.debug("hash: " + hash); String fileName = httpServletRequest.getParameter("fileName"); if (fileName == null) { fileName = "file_xyz"; } String exportType = httpServletRequest.getParameter("exportType"); if (exportType == null) { exportType = "svg"; } Long users_id = getSessionManagement().checkSession(sid); Long user_level = getUserManagement().getUserLevelByID(users_id); log.debug("users_id: " + users_id); log.debug("user_level: " + user_level); if (user_level != null && user_level > 0 && hash != "") { PrintBean pBean = PrintService.getPrintItemByHash(hash); // Whiteboard Objects @SuppressWarnings("rawtypes") List whiteBoardMap = pBean.getMap(); // Get a DOMImplementation. DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation(); // Create an instance of org.w3c.dom.Document. // String svgNS = "http://www.w3.org/2000/svg"; String svgNS = SVGDOMImplementation.SVG_NAMESPACE_URI; Document document = domImpl.createDocument(svgNS, "svg", null); // Get the root element (the 'svg' element). Element svgRoot = document.getDocumentElement(); // Set the width and height attributes on the root 'svg' // element. svgRoot.setAttributeNS(null, "width", "" + pBean.getWidth()); svgRoot.setAttributeNS(null, "height", "" + pBean.getHeight()); log.debug("pBean.getWidth(),pBean.getHeight()" + pBean.getWidth() + "," + pBean.getHeight()); // Create an instance of the SVG Generator. SVGGraphics2D svgGenerator = new SVGGraphics2D(document); svgGenerator = WhiteboardMapToSVG.getInstance().convertMapToSVG(svgGenerator, whiteBoardMap); // Finally, stream out SVG to the standard output using // UTF-8 encoding. boolean useCSS = true; // we want to use CSS style attributes // Writer out = new OutputStreamWriter(System.out, "UTF-8"); if (exportType.equals("svg")) { // OutputStream out = httpServletResponse.getOutputStream(); // httpServletResponse.setContentType("APPLICATION/OCTET-STREAM"); // httpServletResponse.setHeader("Content-Disposition","attachment; filename=\"" // + requestedFile + "\""); Writer out = httpServletResponse.getWriter(); svgGenerator.stream(out, useCSS); } else if (exportType.equals("png") || exportType.equals("jpg") || exportType.equals("gif") || exportType.equals("tif") || exportType.equals("pdf")) { String current_dir = getServletContext().getRealPath("/"); String working_dir = current_dir + OpenmeetingsVariables.UPLOAD_TEMP_DIR + File.separatorChar; String requestedFileSVG = fileName + "_" + CalendarPatterns.getTimeForStreamId(new Date()) + ".svg"; String resultFileName = fileName + "_" + CalendarPatterns.getTimeForStreamId(new Date()) + "." + exportType; log.debug("current_dir: " + current_dir); log.debug("working_dir: " + working_dir); log.debug("requestedFileSVG: " + requestedFileSVG); log.debug("resultFileName: " + resultFileName); File svgFile = new File(working_dir + requestedFileSVG); File resultFile = new File(working_dir + resultFileName); log.debug("svgFile: " + svgFile.getAbsolutePath()); log.debug("resultFile: " + resultFile.getAbsolutePath()); log.debug("svgFile P: " + svgFile.getPath()); log.debug("resultFile P: " + resultFile.getPath()); FileWriter out = new FileWriter(svgFile); svgGenerator.stream(out, useCSS); // Get file and handle download RandomAccessFile rf = new RandomAccessFile(resultFile.getAbsoluteFile(), "r"); httpServletResponse.reset(); httpServletResponse.resetBuffer(); OutputStream outStream = httpServletResponse.getOutputStream(); httpServletResponse.setContentType("APPLICATION/OCTET-STREAM"); httpServletResponse.setHeader("Content-Disposition", "attachment; filename=\"" + resultFileName + "\""); httpServletResponse.setHeader("Content-Length", "" + rf.length()); byte[] buffer = new byte[1024]; int readed = -1; while ((readed = rf.read(buffer, 0, buffer.length)) > -1) { outStream.write(buffer, 0, readed); } outStream.close(); rf.close(); out.flush(); out.close(); } } } catch (Exception er) { log.error("ERROR ", er); System.out.println("Error exporting: " + er); er.printStackTrace(); } }
From source file:uk.ac.susx.tag.method51.webapp.handler.DatabaseHandler.java
protected static void getDataJsonOrCsv(MySQLConnectionParams dbParams, String database, String table, GetDataParams.Format format, Integer limit, final Long sinceId, final Long offset, Character csvFieldSep, Request baseRequest, HttpServletResponse response) throws IOException { dbParams.setDatabase(database);//from ww w . j a v a 2 s . c o m String select = String.format(SELECT_ALL_SQL, table); try (Connection con = dbParams.buildConnection(); PreparedStatement stmt = con.prepareStatement(select)) { // allow them to get all tweets since some id Long lastId = sinceId; // if they didn't specify an id if (lastId == null) { // then we need an offset if (offset == null) { // if they didn't supply an offset either, just set // the last id to 0 so we get all the tweets. lastId = 0L; } else { // use the offset to find the id of the tweet at that // offset lastId = getFirstId(con, table, offset) - 1; // -1 for inclusivity } } //this also tests the connection, db, and table existence before modifying request Integer total = getCount(con, table); ; if (limit == null) { limit = total; } if (format == GetDataParams.Format.JSON) { response.setContentType("application/json;charset=utf-8"); } else if (format == GetDataParams.Format.CSV) { response.setContentType("text/csv;charset=utf-8"); } else { throw new GetDataParams.UnknownFormatException(); } response.setStatus(HttpServletResponse.SC_OK); baseRequest.setHandled(true); int count = 0; try (OutputStream outStream = response.getOutputStream();) { if (format == GetDataParams.Format.JSON) { outStream.write("[".getBytes()); } boolean firstTime = true; while (count < total && count < limit) { stmt.setLong(1, lastId); int l = Math.min(limit, Math.min(SQL_CHUNK_SIZE, total - count)); stmt.setLong(2, l); ResultSet rs = stmt.executeQuery(); ResultSetMetaData rsmd = rs.getMetaData(); int cols = rsmd.getColumnCount(); int intermediateCount = 0; while (rs.next() && count < limit) { if (!firstTime) { if (format == GetDataParams.Format.JSON) { outStream.write(",".getBytes()); } } else { if (format == GetDataParams.Format.CSV) { //write headers StringBuilder sb = new StringBuilder(); for (int i = 0; i < cols; i++) { sb.append(rsmd.getColumnLabel(i + 1)); if (i < cols - 1) { sb.append(csvFieldSep); } } sb.append("\n"); outStream.write(sb.toString().getBytes()); } firstTime = false; } if (format == GetDataParams.Format.JSON) { Tweet tweet = Schema.resultSetToTweet(rs); String json = tweet.toJsonString(); outStream.write(json.getBytes()); outStream.write("\n".getBytes()); } else if (format == GetDataParams.Format.CSV) { StringBuilder sb = new StringBuilder(); for (int i = 1; i <= cols; ++i) { Object field = rs.getObject(i); if (field != null) { if (field instanceof String) { field = ((String) field).replace("\n", "").replace("\r", "") .replace(csvFieldSep, ' '); } sb.append(field.toString()); } sb.append(csvFieldSep); } sb.delete(sb.length() - 1, sb.length()); sb.append("\n"); String csv = sb.toString(); outStream.write(csv.getBytes()); } count += 1; ++intermediateCount; long id = rs.getLong("id"); if (id > lastId) { lastId = id; } } rs.close(); if (intermediateCount == 0) { break; } } if (format == GetDataParams.Format.JSON) { outStream.write("]".getBytes()); } } } catch (SQLException e) { response.reset(); throw new IOException(e); } }
From source file:org.restcomm.connect.http.filters.FileCacheServlet.java
/** * Process the actual request./*from ww w .ja v 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. */ 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(); if (logger.isDebugEnabled()) { logger.debug("Requested path:" + requestedFile); } // Check if file is actually supplied to the request URL. if (requestedFile == null) { logger.debug("No file requested, return 404."); // 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; } Configuration rootConfiguration = (Configuration) request.getServletContext() .getAttribute(Configuration.class.getName()); Configuration runtimeConfiguration = rootConfiguration.subset("runtime-settings"); String basePath = runtimeConfiguration.getString("cache-path"); int bufferSize = runtimeConfiguration.getInteger("cache-buffer-size", DEFAULT_BUFFER_SIZE); long expireTime = runtimeConfiguration.getLong("cache-expire-time", DEFAULT_EXPIRE_TIME); // URL-decode the file name (might contain spaces and on) and prepare file object. String fDecodedPath = URLDecoder.decode(requestedFile, "UTF-8"); File file = new File(basePath, fDecodedPath); // Check if file actually exists in filesystem. if (!file.exists()) { logger.debug("Requested file not found, return 404."); // 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() + expireTime; // 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)) { logger.debug("IfNoneMatch/Etag not matching, return 304."); 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) { logger.debug("IfModifiedSince not matching, return 304."); 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)) { logger.debug("ifMatch not matching, return 412."); 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) { logger.debug("ifUnmodifiedSince not matching, return 412."); response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); return; } // Prepare and initialize response -------------------------------------------------------- // Get content type by file name and content disposition. String contentType = getServletContext().getMimeType(fileName); 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, expand content type with the one and right character encoding. if (contentType.startsWith("text")) { 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(bufferSize); 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. FileInputStream input = null; OutputStream output = null; if (content) { logger.debug("Content requested,streaming."); // Open streams. input = new FileInputStream(file); output = response.getOutputStream(); long streamed = stream(input, output, bufferSize); if (logger.isDebugEnabled()) { logger.debug("Bytes streamed:" + streamed); } } }
From source file:net.dorokhov.pony.web.server.common.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;/* w w w . ja va2 s. 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 && 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<>(); // 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. response.setContentType(contentType); response.setHeader("Content-Range", "bytes " + full.start + "-" + full.end + "/" + full.total); response.setHeader("Content-Length", String.valueOf(full.length)); copy(input, output, length, full.start, full.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); } }