List of usage examples for javax.servlet.http HttpServletRequest getDateHeader
public long getDateHeader(String name);
long
value that represents a Date
object. 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 www. j ava 2 s. c o m*/ } 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:helma.servlet.AbstractServletClient.java
private boolean checkNotModified(File file, HttpServletRequest req, HttpServletResponse res) { // we do two rounds of conditional requests: // first ETag based, then based on last modified date. // calculate ETag checksum on last modified date and content length. byte[] checksum = new byte[16]; long n = file.lastModified(); for (int i = 0; i < 8; i++) { checksum[i] = (byte) (n); n >>>= 8;//w ww . j a va 2s . co m } n = file.length(); for (int i = 8; i < 16; i++) { checksum[i] = (byte) (n); n >>>= 8; } String etag = "\"" + new String(Base64.encode(checksum)) + "\""; res.setHeader("ETag", etag); String etagHeader = req.getHeader("If-None-Match"); if (etagHeader != null) { StringTokenizer st = new StringTokenizer(etagHeader, ", \r\n"); while (st.hasMoreTokens()) { if (etag.equals(st.nextToken())) { return true; } } } // as a fallback, since some browsers don't support ETag based // conditional GET for embedded images and stuff, check last modified date. // date headers don't do milliseconds, round to seconds long lastModified = (file.lastModified() / 1000) * 1000; long ifModifiedSince = req.getDateHeader("If-Modified-Since"); if (lastModified == ifModifiedSince) { return true; } res.setDateHeader("Last-Modified", lastModified); return false; }
From source file:org.osaf.cosmo.webcal.WebcalServlet.java
/** * Handles GET requests for calendar collections. Returns a 200 * <code>text/calendar</code> response containing an iCalendar * representation of all of the calendar items within the * collection.//from ww w . j a va2 s .co m * * Returns 404 if the request's path info does not specify a * collection path or if the identified collection is not found. * * Returns 405 if the item with the identified uid is not a * calendar collection. */ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (log.isDebugEnabled()) log.debug("handling GET for " + req.getPathInfo()); // requests will usually come in with the collection's display // name appended to the collection path so that clients will // save the file with that name CollectionPath cp = CollectionPath.parse(req.getPathInfo(), true); if (cp == null) { resp.setStatus(HttpServletResponse.SC_NOT_FOUND); return; } Item item; try { item = contentService.findItemByUid(cp.getUid()); } // handle security errors by returing 403 catch (CosmoSecurityException e) { resp.sendError(HttpServletResponse.SC_FORBIDDEN, e.getMessage()); return; } if (item == null) { resp.setStatus(HttpServletResponse.SC_NOT_FOUND); return; } if (!(item instanceof CollectionItem)) { resp.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED, "Requested item not a collection"); return; } CollectionItem collection = (CollectionItem) item; if (StampUtils.getCalendarCollectionStamp(collection) == null) { resp.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED, "Requested item not a calendar collection"); return; } EntityTag etag = new EntityTag(collection.getEntityTag()); // set ETag resp.setHeader("ETag", etag.toString()); // check for If-None-Match EntityTag[] requestEtags = getIfNoneMatch(req); if (requestEtags != null && requestEtags.length != 0) { if (EntityTag.matchesAny(etag, requestEtags)) { resp.setStatus(304); return; } } // check for If-Modified-Since long since = req.getDateHeader("If-Modified-Since"); // If present and if collection's modified date not more recent, // return 304 not modified if (since != -1) { long lastModified = collection.getModifiedDate().getTime() / 1000 * 1000; if (lastModified <= since) { resp.setStatus(304); return; } } // set Last-Modified resp.setDateHeader("Last-Modified", collection.getModifiedDate().getTime()); resp.setStatus(HttpServletResponse.SC_OK); resp.setContentType(ICALENDAR_MEDIA_TYPE); resp.setCharacterEncoding("UTF-8"); // send Content-Disposition to provide another hint to clients // on how to save and name the downloaded file String filename = collection.getDisplayName() + "." + ICALENDAR_FILE_EXTENSION; resp.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\""); // get icalendar Calendar calendar = entityConverter.convertCollection(collection); // Filter if necessary so we play nicely with clients // that don't adhere to spec if (clientFilterManager != null) clientFilterManager.filterCalendar(calendar); // spool ICalendarOutputter.output(calendar, resp.getOutputStream()); }
From source file:org.apache.felix.webconsole.AbstractWebConsolePlugin.java
/** * If the request addresses a resource which may be served by the * <code>getResource</code> method of the * {@link #getResourceProvider() resource provider}, this method serves it * and returns <code>true</code>. Otherwise <code>false</code> is returned. * <code>false</code> is also returned if the resource provider has no * <code>getResource</code> method. * <p>/*from w w w . ja va 2 s.c o m*/ * If <code>true</code> is returned, the request is considered complete and * request processing terminates. Otherwise request processing continues * with normal plugin rendering. * * @param request The request object * @param response The response object * @return <code>true</code> if the request causes a resource to be sent back. * * @throws IOException If an error occurs accessing or spooling the resource. */ private final boolean spoolResource(HttpServletRequest request, HttpServletResponse response) throws IOException { // no resource if no resource accessor Method getResourceMethod = getGetResourceMethod(); if (getResourceMethod == null) { return false; } String pi = request.getPathInfo(); InputStream ins = null; try { // check for a resource, fail if none URL url = (URL) getResourceMethod.invoke(getResourceProvider(), new Object[] { pi }); if (url == null) { return false; } // open the connection and the stream (we use the stream to be able // to at least hint to close the connection because there is no // method to explicitly close the conneciton, unfortunately) URLConnection connection = url.openConnection(); ins = connection.getInputStream(); // FELIX-2017 Equinox may return an URL for a non-existing // resource but then (instead of throwing) return null on // getInputStream. We should account for this situation and // just assume a non-existing resource in this case. if (ins == null) { return false; } // check whether we may return 304/UNMODIFIED long lastModified = connection.getLastModified(); if (lastModified > 0) { long ifModifiedSince = request.getDateHeader("If-Modified-Since"); if (ifModifiedSince >= (lastModified / 1000 * 1000)) { // Round down to the nearest second for a proper compare // A ifModifiedSince of -1 will always be less response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return true; } // have to send, so set the last modified header now response.setDateHeader("Last-Modified", lastModified); } // describe the contents response.setContentType(getServletContext().getMimeType(pi)); response.setIntHeader("Content-Length", connection.getContentLength()); // spool the actual contents OutputStream out = response.getOutputStream(); byte[] buf = new byte[2048]; int rd; while ((rd = ins.read(buf)) >= 0) { out.write(buf, 0, rd); } // over and out ... return true; } catch (IllegalAccessException iae) { // log or throw ??? } catch (InvocationTargetException ite) { // log or throw ??? // Throwable cause = ite.getTargetException(); } finally { IOUtils.closeQuietly(ins); } return false; }
From source file:org.messic.server.facade.controllers.rest.SongController.java
@ApiMethod(path = "/services/songs/{songSid}/audio", verb = ApiVerb.GET, description = "Get the audio binary from a song resource of an album", produces = { MediaType.APPLICATION_OCTET_STREAM_VALUE }) @ApiErrors(apierrors = { @ApiError(code = UnknownMessicRESTException.VALUE, description = "Unknown error"), @ApiError(code = NotAuthorizedMessicRESTException.VALUE, description = "Forbidden access"), @ApiError(code = IOMessicRESTException.VALUE, description = "IO error trying to get the audio resource") }) @RequestMapping(value = "/{songSid}/audio", method = { RequestMethod.GET, RequestMethod.HEAD }) @ResponseStatus(HttpStatus.OK)//from ww w . ja va 2 s .c o m public void getSongWithRanges( @ApiParam(name = "songSid", description = "SID of the song resource we want to download", paramType = ApiParamType.PATH, required = true) @PathVariable Long songSid, HttpServletRequest request, HttpServletResponse response) throws NotAuthorizedMessicRESTException, IOMessicRESTException, UnknownMessicRESTException { User user = SecurityUtil.getCurrentUser(); try { //http://balusc.blogspot.com.es/2009/02/fileservlet-supporting-resume-and.html // Whether the request body should be written (GET) or not (HEAD). boolean content = request.getMethod().equalsIgnoreCase("GET"); APISong.AudioSongStream ass = songAPI.getAudioSong(user, songSid); // Validate and process Range and If-Range headers. String eTag = songSid + "_" + ass.contentLength + "_" + ass.lastModified; long expires = System.currentTimeMillis() + Range.DEFAULT_EXPIRE_TIME; // Validate request headers for caching --------------------------------------------------- // If-None-Match header should contain "*" or ETag. If so, then return 304. String ifNoneMatch = request.getHeader("If-None-Match"); if (ifNoneMatch != null && Range.matches(ifNoneMatch, eTag)) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); response.setHeader("ETag", eTag); // Required in 304. response.setDateHeader("Expires", expires); // Postpone cache with 1 week. return; } // If-Modified-Since header should be greater than LastModified. If so, then return 304. // This header is ignored if any If-None-Match header is specified. long ifModifiedSince = request.getDateHeader("If-Modified-Since"); if (ifNoneMatch == null && ifModifiedSince != -1 && ifModifiedSince + 1000 > ass.lastModified) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); response.setHeader("ETag", eTag); // Required in 304. response.setDateHeader("Expires", expires); // Postpone cache with 1 week. return; } // Validate request headers for resume ---------------------------------------------------- // If-Match header should contain "*" or ETag. If not, then return 412. String ifMatch = request.getHeader("If-Match"); if (ifMatch != null && !Range.matches(ifMatch, eTag)) { response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); return; } // If-Unmodified-Since header should be greater than LastModified. If not, then return 412. long ifUnmodifiedSince = request.getDateHeader("If-Unmodified-Since"); if (ifUnmodifiedSince != -1 && ifUnmodifiedSince + 1000 <= ass.lastModified) { response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); return; } // Validate and process range ------------------------------------------------------------- // Prepare some variables. The full Range represents the complete file. Range full = new Range(0, ass.contentLength - 1, ass.contentLength); List<Range> ranges = new ArrayList<Range>(); String range = request.getHeader("Range"); if (range != null) { // Range header should match format "bytes=n-n,n-n,n-n...". If not, then return 416. if (!range.matches("^bytes=\\d*-\\d*(,\\d*-\\d*)*$")) { response.setHeader("Content-Range", "bytes */" + ass.contentLength); // Required in 416. response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); return; } // If-Range header should either match ETag or be greater then LastModified. If not, // then return full file. String ifRange = request.getHeader("If-Range"); if (ifRange != null && !ifRange.equals(eTag)) { try { long ifRangeTime = request.getDateHeader("If-Range"); // Throws IAE if invalid. if (ifRangeTime != -1 && ifRangeTime + 1000 < ass.lastModified) { ranges.add(full); } } catch (IllegalArgumentException ignore) { ranges.add(full); } } // If any valid If-Range header, then process each part of byte range. if (ranges.isEmpty()) { for (String part : range.substring(6).split(",")) { // Assuming a file with length of 100, the following examples returns bytes at: // 50-80 (50 to 80), 40- (40 to length=100), -20 (length-20=80 to length=100). long start = Range.sublong(part, 0, part.indexOf("-")); long end = Range.sublong(part, part.indexOf("-") + 1, part.length()); if (start == -1) { start = ass.contentLength - end; end = ass.contentLength - 1; } else if (end == -1 || end > ass.contentLength - 1) { end = ass.contentLength - 1; } // Check if Range is syntactically valid. If not, then return 416. if (start > end) { response.setHeader("Content-Range", "bytes */" + ass.contentLength); // Required in 416. response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); return; } // Add range. ranges.add(new Range(start, end, ass.contentLength)); } } } // Prepare and initialize response -------------------------------------------------------- // Get content type by file name and set default GZIP support and content disposition. String contentType = "audio/mpeg"; boolean acceptsGzip = false; String disposition = "inline"; // // If content type is unknown, then set the default value. // // For all content types, see: http://www.w3schools.com/media/media_mimeref.asp // // To add new content types, add new mime-mapping entry in web.xml. // if ( contentType == null ) // { // contentType = "application/octet-stream"; // } // If content type is text, then determine whether GZIP content encoding is supported by // the browser and expand content type with the one and right character encoding. if (contentType.startsWith("text")) { String acceptEncoding = request.getHeader("Accept-Encoding"); acceptsGzip = acceptEncoding != null && Range.accepts(acceptEncoding, "gzip"); contentType += ";charset=UTF-8"; } // Else, expect for images, determine content disposition. If content type is supported by // the browser, then set to inline, else attachment which will pop a 'save as' dialogue. else if (!contentType.startsWith("image")) { String accept = request.getHeader("Accept"); disposition = accept != null && Range.accepts(accept, contentType) ? "inline" : "attachment"; } // Initialize response. response.reset(); response.setBufferSize(Range.DEFAULT_BUFFER_SIZE); response.setHeader("Content-Disposition", disposition + ";filename=\"" + ass.songFileName + "\""); response.setHeader("Accept-Ranges", "bytes"); response.setHeader("ETag", eTag); response.setDateHeader("Last-Modified", ass.lastModified); response.setDateHeader("Expires", expires); // Send requested file (part(s)) to client ------------------------------------------------ // Prepare streams. OutputStream output = null; try { // Open streams. output = response.getOutputStream(); if (ranges.isEmpty() || ranges.get(0) == full) { // Return full file. Range r = full; response.setContentType(contentType); response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total); if (content) { if (acceptsGzip) { // The browser accepts GZIP, so GZIP the content. response.setHeader("Content-Encoding", "gzip"); output = new GZIPOutputStream(output, Range.DEFAULT_BUFFER_SIZE); } else { // Content length is not directly predictable in case of GZIP. // So only add it if there is no means of GZIP, else browser will hang. response.setHeader("Content-Length", String.valueOf(r.length)); } // Copy full range. Range.copy(ass.raf, output, r.start, r.length); } } else if (ranges.size() == 1) { // Return single part of file. Range r = ranges.get(0); response.setContentType(contentType); response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total); response.setHeader("Content-Length", String.valueOf(r.length)); response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206. if (content) { // Copy single part range. Range.copy(ass.raf, output, r.start, r.length); } } else { // Return multiple parts of file. response.setContentType("multipart/byteranges; boundary=" + Range.MULTIPART_BOUNDARY); response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206. if (content) { // Cast back to ServletOutputStream to get the easy println methods. ServletOutputStream sos = (ServletOutputStream) output; // Copy multi part range. for (Range r : ranges) { // Add multipart boundary and header fields for every range. sos.println(); sos.println("--" + Range.MULTIPART_BOUNDARY); sos.println("Content-Type: " + contentType); sos.println("Content-Range: bytes " + r.start + "-" + r.end + "/" + r.total); // Copy single part range of multi part range. Range.copy(ass.raf, output, r.start, r.length); } // End with multipart boundary. sos.println(); sos.println("--" + Range.MULTIPART_BOUNDARY + "--"); } } } finally { // Gently close streams. Range.close(output); Range.close(ass.is); Range.close(ass.raf); } return; } catch (IOException ioe) { log.error("failed!", ioe); throw new IOMessicRESTException(ioe); } catch (Exception e) { throw new UnknownMessicRESTException(e); } }
From source file:org.gaul.s3proxy.S3ProxyHandler.java
private static void addContentMetdataFromHttpRequest(BlobBuilder.PayloadBlobBuilder builder, HttpServletRequest request) {// w w w . j a v a 2s. c o m ImmutableMap.Builder<String, String> userMetadata = ImmutableMap.builder(); for (String headerName : Collections.list(request.getHeaderNames())) { if (startsWithIgnoreCase(headerName, USER_METADATA_PREFIX)) { userMetadata.put(headerName.substring(USER_METADATA_PREFIX.length()), Strings.nullToEmpty(request.getHeader(headerName))); } } builder.cacheControl(request.getHeader(HttpHeaders.CACHE_CONTROL)) .contentDisposition(request.getHeader(HttpHeaders.CONTENT_DISPOSITION)) .contentEncoding(request.getHeader(HttpHeaders.CONTENT_ENCODING)) .contentLanguage(request.getHeader(HttpHeaders.CONTENT_LANGUAGE)) .userMetadata(userMetadata.build()); String contentType = request.getContentType(); if (contentType != null) { builder.contentType(contentType); } long expires = request.getDateHeader(HttpHeaders.EXPIRES); if (expires != -1) { builder.expires(new Date(expires)); } }
From source file:org.polymap.core.mapeditor.services.SimpleWmsServer.java
protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { log.debug("Request: " + request.getQueryString()); final Map<String, String> kvp = parseKvpSet(request.getQueryString()); try {//from ww w . ja v a 2 s . c o m sessionContext.execute(new Callable() { public Object call() throws Exception { final String layerRenderKey = kvp.get("LAYERS"); assert !layerRenderKey.contains(INNER_DELIMETER); // width/height int width = Integer.parseInt(kvp.get("WIDTH")); int height = Integer.parseInt(kvp.get("HEIGHT")); // BBOX ReferencedEnvelope bbox = parseBBox(kvp.get("BBOX")); String srsCode = kvp.get("SRS"); // XXX hack support for EPSG:3857 : send different srs and crs // CoordinateReferenceSystem crs = srsCode.equals( "EPSG:3857" ) // ? CRS.decode( "EPSG:900913" ) // : CRS.decode( srsCode ); CoordinateReferenceSystem crs = CRS.decode(srsCode); bbox = new ReferencedEnvelope(bbox, crs); // FORMAT String format = kvp.get("FORMAT"); format = format != null ? format : "image/png"; log.debug(" --layers= " + layerRenderKey); log.debug(" --imageSize= " + width + "x" + height); log.debug(" --bbox= " + bbox); crs = bbox.getCoordinateReferenceSystem(); log.debug(" --CRS= " + bbox.getCoordinateReferenceSystem().getName()); // find/create pipeline final Pipeline pipeline = getOrCreatePipeline(layerRenderKey); //ILayer layer = Iterables.getOnlyElement( pipeline.getLayers() ); long modifiedSince = request.getDateHeader("If-Modified-Since"); final ProcessorRequest pr = new GetMapRequest(null, // layers srsCode, bbox, format, width, height, modifiedSince); // process final LazyInit<ServletOutputStream> out = new PlainLazyInit( new Supplier<ServletOutputStream>() { public ServletOutputStream get() { try { return response.getOutputStream(); } catch (IOException e) { throw new RuntimeException(e); } } }); try { pipeline.process(pr, new ResponseHandler() { public void handle(ProcessorResponse pipeResponse) throws Exception { if (pipeResponse == EncodedImageResponse.NOT_MODIFIED) { response.setStatus(304); } else { long lastModified = ((EncodedImageResponse) pipeResponse).getLastModified(); // lastModified is only set if response comes from cache -> // allow the browser to use a cached tile for max-age without a request if (lastModified > 0) { response.setDateHeader("Last-Modified", lastModified); response.setHeader("Cache-Control", "max-age=180,must-revalidate"); } // disable browser cache if there is no internal Cache for this layer else { response.setHeader("Cache-Control", "no-cache,no-store,must-revalidate"); response.setDateHeader("Expires", 0); response.setHeader("Pragma", "no-cache"); } byte[] chunk = ((EncodedImageResponse) pipeResponse).getChunk(); int len = ((EncodedImageResponse) pipeResponse).getChunkSize(); out.get().write(chunk, 0, len); } } }); } catch (Throwable e) { log.warn("Pipeline exception: " + e, e); response.setStatus(502); } if (out.isInitialized()) { out.get().flush(); } response.flushBuffer(); return null; } }); } catch (IOException e) { // assuming that this is an EOF exception log.info("Exception: " + e); } catch (Exception e) { log.warn(e.toString(), e); } finally { // XXX do I have to close out? //out.close(); } }
From source file:org.sakaiproject.sdata.tool.JCRHandler.java
@Override public void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try {//w w w .j a va 2s .c o m snoopRequest(request); ResourceDefinition rp = resourceDefinitionFactory.getSpec(request); String mimeType = ContentTypes.getContentType(rp.getRepositoryPath(), request.getContentType()); String charEncoding = null; if (mimeType.startsWith("text")) { charEncoding = request.getCharacterEncoding(); } Node n = jcrNodeFactory.getNode(rp.getRepositoryPath()); boolean created = false; if (n == null) { n = jcrNodeFactory.createFile(rp.getRepositoryPath(), mimeType); created = true; if (n == null) { throw new RuntimeException( "Failed to create node at " + rp.getRepositoryPath() + " type " + JCRConstants.NT_FILE); } } else { NodeType nt = n.getPrimaryNodeType(); if (!JCRConstants.NT_FILE.equals(nt.getName())) { response.reset(); response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Content Can only be put to a file, resource type is " + nt.getName()); return; } } GregorianCalendar gc = new GregorianCalendar(); long lastMod = request.getDateHeader(LAST_MODIFIED); if (lastMod > 0) { gc.setTimeInMillis(lastMod); } else { gc.setTime(new Date()); } InputStream in = request.getInputStream(); saveStream(n, in, mimeType, charEncoding, gc); in.close(); if (created) { response.setStatus(HttpServletResponse.SC_CREATED); } else { response.setStatus(HttpServletResponse.SC_NO_CONTENT); } } catch (UnauthorizedException ape) { // catch any Unauthorized exceptions and send a 401 response.reset(); response.sendError(HttpServletResponse.SC_UNAUTHORIZED, ape.getMessage()); } catch (PermissionDeniedException pde) { // catch any permission denied exceptions, and send a 403 response.reset(); response.sendError(HttpServletResponse.SC_FORBIDDEN, pde.getMessage()); } catch (SDataException e) { sendError(request, response, e); LOG.error("Failed To service Request " + e.getMessage()); } catch (Exception e) { sendError(request, response, e); snoopRequest(request); LOG.error("Failed TO service Request ", e); } }
From source file:org.gss_project.gss.server.rest.FilesHandler.java
/** * Handles an authentication failure. If no Authorization or Date request * parameters and no Authorization, Date or X-GSS-Date headers were present, * this is a browser request, so redirect to login and then let the user get * back to the file. Otherwise it's a bogus client request and Forbidden is * returned./*from w w w .j a va 2 s. co m*/ */ private void handleAuthFailure(HttpServletRequest req, HttpServletResponse resp) throws IOException { if (req.getParameter(AUTHORIZATION_PARAMETER) == null && req.getParameter(DATE_PARAMETER) == null && req.getHeader(AUTHORIZATION_HEADER) == null && req.getDateHeader(DATE_HEADER) == -1 && req.getDateHeader(GSS_DATE_HEADER) == -1) resp.sendRedirect(getConfiguration().getString("loginUrl") + "?next=" + req.getRequestURL().toString()); else resp.sendError(HttpServletResponse.SC_FORBIDDEN); }
From source file:eionet.eunis.servlets.DownloadServlet.java
/** * Process the actual request./*w ww. j a v a 2s . c om*/ * * @param request The request to be processed. * @param response The response to be created. * @param content Whether the request body should be written (GET) or not (HEAD). * @throws IOException If something fails at I/O level. * @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); } }