List of usage examples for javax.servlet.http HttpServletResponse setDateHeader
public void setDateHeader(String name, long date);
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>/* w ww .ja v a 2s . 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.abstracthorizon.proximity.webapp.controllers.RepositoryController.java
/** * Repository list.//from w w w.j av a 2s . c o m * * @param request the request * @param response the response * * @return the model and view * * @throws Exception the exception */ public ModelAndView repositoryList(HttpServletRequest request, HttpServletResponse response) throws Exception { String requestURI = request.getRequestURI() .substring(request.getContextPath().length() + request.getServletPath().length()); if (requestURI.length() == 0) { requestURI = "/"; } logger.debug("Got repository request on URI " + requestURI); String orderBy = request.getParameter("orderBy") == null ? "name" : request.getParameter("orderBy"); String targetRepository = request.getParameter("repositoryId"); String targetGroup = request.getParameter("repositoryGroupId"); Item item = null; ProximityRequest pRequest = new ProximityRequest(); pRequest.setPath(requestURI); pRequest.setTargetedReposId(targetRepository); pRequest.setTargetedReposGroupId(targetGroup); pRequest.setGrantee(null); pRequest.getAttributes().put(ProximityRequest.REQUEST_REMOTE_ADDRESS, request.getRemoteAddr()); // issue #42, collect header information Enumeration headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { String headerName = (String) headerNames.nextElement(); pRequest.getAttributes().put("http." + headerName.toLowerCase(), request.getHeader(headerName)); } try { logger.debug("Got request for " + targetRepository + " repository on URI: " + requestURI); item = proximity.retrieveItem(pRequest); logger.debug("Got response " + item.getProperties().getPath()); if (item.getProperties().isDirectory()) { List items = null; items = proximity.listItems(pRequest); PropertyComparator.sort(items, new MutableSortDefinition(orderBy, true, true)); Map result = new HashMap(); result.put("items", items); result.put("orderBy", orderBy); result.put("requestUri", requestURI); result.put("requestPathList", explodeUriToList(requestURI)); return new ModelAndView("repository/repositoryList", result); } else { // TODO: check for If-Modified-Since? // response.setContentType("application/octet-stream"); response.setContentType( getWebApplicationContext().getServletContext().getMimeType(item.getProperties().getName())); response.setContentLength((int) item.getProperties().getSize()); response.setDateHeader("Last-Modified", item.getProperties().getLastModified().getTime()); InputStream is = item.getStream(); OutputStream os = response.getOutputStream(); IOUtils.copy(is, os); is.close(); return null; } } catch (ItemNotFoundException ex) { logger.info("Item not found on URI " + requestURI); response.sendError(HttpServletResponse.SC_NOT_FOUND); return null; } catch (AccessDeniedException ex) { logger.info("Access forbidden to " + requestURI + " for " + request.getRemoteAddr(), ex); response.sendError(HttpServletResponse.SC_FORBIDDEN); return null; } }
From source file:org.ajax4jsf.resource.InternetResourceService.java
public void serviceResource(String resourceKey, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { InternetResource resource;// getInternetResource(request); try {//from w ww. ja v a2 s . co m resource = getResourceBuilder().getResourceForKey(resourceKey); } catch (ResourceNotFoundException e) { throw new ServletException(e); } Object resourceDataForKey = getResourceBuilder().getResourceDataForKey(resourceKey); ResourceContext resourceContext = getResourceContext(resource, request, response); resourceContext.setResourceData(resourceDataForKey); try { if (resource.isCacheable(resourceContext) && this.cacheEnabled) { // Test for client request modification time. try { long ifModifiedSince = request.getDateHeader("If-Modified-Since"); if (ifModifiedSince >= 0) { // Test for modification. 1000 ms due to round // modification // time to seconds. long lastModified = resource.getLastModified(resourceContext).getTime() - 1000; if (lastModified <= ifModifiedSince) { response.setStatus(304); return; } } } catch (IllegalArgumentException e) { log.warn(Messages.getMessage(Messages.PARSING_IF_MODIFIED_SINCE_WARNING), e); } String cacheKey = resourceKey; CachedResourceContext cachedResourceContext = new CachedResourceContext(resourceContext); CacheContext cacheLoaderContext = new CacheContext(cachedResourceContext, resource); try { CacheContent content = (CacheContent) cache.get(cacheKey, cacheLoaderContext); if (log.isDebugEnabled()) { log.debug(Messages.getMessage(Messages.GET_CONTENT_FROM_CACHE_INFO, cacheKey)); } content.sendHeaders(response); // Correct expires date for resource. long expired = resource.getExpired(resourceContext); if (expired < 0) { expired = InternetResource.DEFAULT_EXPIRE; } response.setDateHeader("Expires", System.currentTimeMillis() + expired); // response.addHeader("Cache-control", "max-age=" // + (expired / 1000L)); if (!request.getMethod().equals("HEAD")) { content.send(response); } content.flush(response); } catch (CacheException e) { log.error(Messages.getMessage(Messages.SEND_RESOURCE_ERROR), e); throw new ServletException(Messages.getMessage(Messages.SEND_RESOURCE_ERROR_2, e.getMessage()), e); } } else { getLifecycle().send(resourceContext, resource); // sendResource(resource, request, response, // resourceDataForKey); } } finally { resourceContext.release(); } }
From source file:org.apache.click.ClickServlet.java
/** * Set the HTTP headers in the servlet response. The Page response headers * are defined in {@link Page#getHeaders()}. * * @param response the response to set the headers in * @param headers the map of HTTP headers to set in the response *//* w w w. j a v a 2 s. c o m*/ protected void setPageResponseHeaders(HttpServletResponse response, Map<String, Object> headers) { for (Map.Entry<String, Object> entry : headers.entrySet()) { String name = entry.getKey(); Object value = entry.getValue(); if (value instanceof String) { String strValue = (String) value; if (!strValue.equalsIgnoreCase("Content-Encoding")) { response.setHeader(name, strValue); } } else if (value instanceof Date) { long time = ((Date) value).getTime(); response.setDateHeader(name, time); } else if (value instanceof Integer) { int intValue = (Integer) value; response.setIntHeader(name, intValue); } else if (value != null) { throw new IllegalStateException("Invalid Page header value type: " + value.getClass() + ". Header value must of type String, Date or Integer."); } } }
From source file:org.haiku.haikudepotserver.job.controller.JobController.java
/** * <p>This URL can be used to download job data that has resulted from a job being run.</p> *///w ww . j a va 2 s. c o m @RequestMapping(value = "/" + SEGMENT_JOBDATA + "/{" + KEY_GUID + "}/" + SEGMENT_DOWNLOAD, method = RequestMethod.GET) public void downloadGeneratedData(HttpServletRequest request, HttpServletResponse response, @PathVariable(value = KEY_GUID) String guid) throws IOException { Preconditions.checkArgument(PATTERN_GUID.matcher(guid).matches(), "the supplied guid does not match the required pattern"); ObjectContext context = serverRuntime.newContext(); JobSnapshot job = jobService.tryGetJobForData(guid).orElseThrow(() -> { LOGGER.warn("attempt to access job data {} for which no job exists", guid); return new JobDataAuthorizationFailure(); }); // If there is no user who is assigned to the job then the job is for nobody in particular and is thereby // secured by the GUID of the job's data; if you know the GUID then you can have the data. if (!Strings.isNullOrEmpty(job.getOwnerUserNickname())) { User user = tryObtainAuthenticatedUser(context).orElseThrow(() -> { LOGGER.warn("attempt to obtain job data {} with no authenticated user", guid); return new JobDataAuthorizationFailure(); }); User ownerUser = User.tryGetByNickname(context, job.getOwnerUserNickname()).orElseThrow(() -> { LOGGER.warn("owner of job does not seem to exist; {}", job.getOwnerUserNickname()); return new JobDataAuthorizationFailure(); }); if (!authorizationService.check(context, user, ownerUser, Permission.USER_VIEWJOBS)) { LOGGER.warn("attempt to access jobs view for; {}", job.toString()); throw new JobDataAuthorizationFailure(); } } else { LOGGER.debug("access to job [{}] allowed for unauthenticated access", job.toString()); } JobDataWithByteSource jobDataWithByteSink = jobService.tryObtainData(guid).orElseThrow(() -> { LOGGER.warn("requested job data {} not found", guid); return new JobDataAuthorizationFailure(); }); // finally access has been checked and the logic can move onto actual // delivery of the material. JobData jobData = jobDataWithByteSink.getJobData(); if (!Strings.isNullOrEmpty(jobData.getMediaTypeCode())) { response.setContentType(jobData.getMediaTypeCode()); } else { response.setContentType(MediaType.OCTET_STREAM.toString()); } response.setContentType(MediaType.CSV_UTF_8.toString()); response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + jobService.deriveDataFilename(guid)); response.setDateHeader(HttpHeaders.EXPIRES, 0); response.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache"); // now switch to async for the delivery of the data. AsyncContext async = request.startAsync(); async.setTimeout(TIMEOUT_DOWNLOAD_MILLIS); ServletOutputStream outputStream = response.getOutputStream(); outputStream.setWriteListener(new JobDataWriteListener(guid, jobService, async, outputStream)); LOGGER.info("did start async stream job data; {}", guid); }
From source file:org.jahia.services.content.files.StaticFileServlet.java
/** * Process the actual request./* w w w.j av a2 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(); // Check if file is actually supplied to the request URL. if (requestedFile == null) { // Do your thing if the file is not supplied to the request URL. // Throw an exception, or send 404, or show default/warning page, or just ignore it. response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // URL-decode the file name (might contain spaces and on) and prepare file object. File file = new File(basePath, URLDecoder.decode(requestedFile, "UTF-8")); // Check if file actually exists in filesystem. if (!file.exists() || !file.isFile()) { // Do your thing if the file appears to be non-existing. // Throw an exception, or send 404, or show default/warning page, or just ignore it. response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // Verify the file requested is a descendant of the base directory. if (!file.getCanonicalPath().startsWith(basePath)) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // Prepare some variables. The ETag is an unique identifier of the file. String fileName = file.getName(); long length = file.length(); long lastModified = file.lastModified(); String eTag = fileName + "_" + length + "_" + lastModified; long expires = System.currentTimeMillis() + DEFAULT_EXPIRE_TIME; // Validate request headers for caching --------------------------------------------------- // If-None-Match header should contain "*" or ETag. If so, then return 304. String ifNoneMatch = request.getHeader("If-None-Match"); if (ifNoneMatch != null && matches(ifNoneMatch, eTag)) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); response.setHeader("ETag", eTag); // Required in 304. response.setDateHeader("Expires", expires); // Postpone cache with 1 week. return; } // If-Modified-Since header should be greater than LastModified. If so, then return 304. // This header is ignored if any If-None-Match header is specified. long ifModifiedSince = request.getDateHeader("If-Modified-Since"); if (ifNoneMatch == null && ifModifiedSince != -1 && ifModifiedSince + 1000 > lastModified) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); response.setHeader("ETag", eTag); // Required in 304. response.setDateHeader("Expires", expires); // Postpone cache with 1 week. return; } // Validate request headers for resume ---------------------------------------------------- // If-Match header should contain "*" or ETag. If not, then return 412. String ifMatch = request.getHeader("If-Match"); if (ifMatch != null && !matches(ifMatch, eTag)) { response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); return; } // If-Unmodified-Since header should be greater than LastModified. If not, then return 412. long ifUnmodifiedSince = request.getDateHeader("If-Unmodified-Since"); if (ifUnmodifiedSince != -1 && ifUnmodifiedSince + 1000 <= lastModified) { response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); return; } // Validate and process range ------------------------------------------------------------- // Prepare some variables. The full Range represents the complete file. Range full = new Range(0, length - 1, length); List<Range> ranges = new ArrayList<Range>(); // Validate and process Range and If-Range headers. String range = request.getHeader("Range"); if (range != null) { // Range header should match format "bytes=n-n,n-n,n-n...". If not, then return 416. if (!PATTERN_RANGE.matcher(range).matches()) { response.setHeader("Content-Range", "bytes */" + length); // Required in 416. response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); return; } // If-Range header should either match ETag or be greater then LastModified. If not, // then return full file. String ifRange = request.getHeader("If-Range"); if (ifRange != null && !ifRange.equals(eTag)) { try { long ifRangeTime = request.getDateHeader("If-Range"); // Throws IAE if invalid. if (ifRangeTime != -1 && ifRangeTime + 1000 < lastModified) { ranges.add(full); } } catch (IllegalArgumentException ignore) { ranges.add(full); } } // If any valid If-Range header, then process each part of byte range. if (ranges.isEmpty()) { for (String part : Patterns.COMMA.split(range.substring(6))) { // Assuming a file with length of 100, the following examples returns bytes at: // 50-80 (50 to 80), 40- (40 to length=100), -20 (length-20=80 to length=100). long start = sublong(part, 0, part.indexOf("-")); long end = sublong(part, part.indexOf("-") + 1, part.length()); if (start == -1) { start = length - end; end = length - 1; } else if (end == -1 || end > length - 1) { end = length - 1; } // Check if Range is syntactically valid. If not, then return 416. if (start > end) { response.setHeader("Content-Range", "bytes */" + length); // Required in 416. response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); return; } // Add range. ranges.add(new Range(start, end, length)); } } } // Prepare and initialize response -------------------------------------------------------- // Get content type by file name and set default GZIP support and content disposition. String contentType = getServletContext().getMimeType(fileName); boolean acceptsGzip = false; String disposition = "inline"; // If content type is unknown, then set the default value. // For all content types, see: http://www.w3schools.com/media/media_mimeref.asp // To add new content types, add new mime-mapping entry in web.xml. if (contentType == null) { contentType = "application/octet-stream"; } // If content type is text, then determine whether GZIP content encoding is supported by // the browser and expand content type with the one and right character encoding. if (contentType.startsWith("text")) { String acceptEncoding = request.getHeader("Accept-Encoding"); acceptsGzip = enableGzip && acceptEncoding != null && accepts(acceptEncoding, "gzip"); contentType += ";charset=UTF-8"; } // Else, expect for images, determine content disposition. If content type is supported by // the browser, then set to inline, else attachment which will pop a 'save as' dialogue. else if (!contentType.startsWith("image")) { String accept = request.getHeader("Accept"); disposition = accept != null && accepts(accept, contentType) ? "inline" : "attachment"; } // Initialize response. response.reset(); response.setBufferSize(DEFAULT_BUFFER_SIZE); response.setHeader("Content-Disposition", disposition + ";filename=\"" + fileName + "\""); response.setHeader("Accept-Ranges", "bytes"); response.setHeader("ETag", eTag); response.setDateHeader("Last-Modified", lastModified); response.setDateHeader("Expires", expires); // Send requested file (part(s)) to client ------------------------------------------------ // Prepare streams. RandomAccessFile input = null; OutputStream output = null; try { // Open streams. input = new RandomAccessFile(file, "r"); output = response.getOutputStream(); if (ranges.isEmpty() || ranges.get(0) == full) { // Return full file. Range r = full; response.setContentType(contentType); response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total); if (content) { if (acceptsGzip) { // The browser accepts GZIP, so GZIP the content. response.setHeader("Content-Encoding", "gzip"); output = new GZIPOutputStream(output, DEFAULT_BUFFER_SIZE); } else { // Content length is not directly predictable in case of GZIP. // So only add it if there is no means of GZIP, else browser will hang. response.setHeader("Content-Length", String.valueOf(r.length)); } // Copy full range. copy(input, output, r.start, r.length); } } else if (ranges.size() == 1) { // Return single part of file. Range r = ranges.get(0); response.setContentType(contentType); response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total); response.setHeader("Content-Length", String.valueOf(r.length)); response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206. if (content) { // Copy single part range. copy(input, output, r.start, r.length); } } else { // Return multiple parts of file. response.setContentType("multipart/byteranges; boundary=" + MULTIPART_BOUNDARY); response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206. if (content) { // Cast back to ServletOutputStream to get the easy println methods. ServletOutputStream sos = (ServletOutputStream) output; // Copy multi part range. for (Range r : ranges) { // Add multipart boundary and header fields for every range. sos.println(); sos.println("--" + MULTIPART_BOUNDARY); sos.println("Content-Type: " + contentType); sos.println("Content-Range: bytes " + r.start + "-" + r.end + "/" + r.total); // Copy single part range of multi part range. copy(input, output, r.start, r.length); } // End with multipart boundary. sos.println(); sos.println("--" + MULTIPART_BOUNDARY + "--"); } } } finally { // Gently close streams. close(output); close(input); } }
From source file:io.fabric8.maven.proxy.impl.MavenProxyServletSupportTest.java
private Map<String, String> testUpload(String path, final byte[] contents, String location, String profile, String version, boolean hasLocationHeader) throws Exception { final String old = System.getProperty("karaf.data"); System.setProperty("karaf.data", new File("target").getCanonicalPath()); FileUtils.deleteDirectory(new File("target/tmp")); Server server = new Server(0); server.setHandler(new AbstractHandler() { @Override//w w w .j a v a 2s .com public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setStatus(HttpServletResponse.SC_NO_CONTENT); } }); server.start(); try { int localPort = server.getConnectors()[0].getLocalPort(); List<String> remoteRepos = Arrays.asList("http://relevant.not/maven2@id=central"); RuntimeProperties props = new MockRuntimeProperties(); MavenResolver resolver = createResolver("target/tmp", remoteRepos, "http", "localhost", localPort, "fuse", "fuse", null); MavenUploadProxyServlet servlet = new MavenUploadProxyServlet(resolver, props, projectDeployer); HttpServletRequest request = EasyMock.createMock(HttpServletRequest.class); EasyMock.expect(request.getPathInfo()).andReturn(path); EasyMock.expect(request.getInputStream()).andReturn(new ServletInputStream() { private int i; @Override public int read() throws IOException { if (i >= contents.length) { return -1; } return (contents[i++] & 0xFF); } }); EasyMock.expect(request.getHeader("X-Location")).andReturn(location); EasyMock.expect(request.getParameter("profile")).andReturn(profile); EasyMock.expect(request.getParameter("version")).andReturn(version); final Map<String, String> headers = new HashMap<>(); HttpServletResponse rm = EasyMock.createMock(HttpServletResponse.class); HttpServletResponse response = new HttpServletResponseWrapper(rm) { @Override public void addHeader(String name, String value) { headers.put(name, value); } }; response.setStatus(EasyMock.anyInt()); EasyMock.expectLastCall().anyTimes(); response.setContentLength(EasyMock.anyInt()); EasyMock.expectLastCall().anyTimes(); response.setContentType((String) EasyMock.anyObject()); EasyMock.expectLastCall().anyTimes(); response.setDateHeader((String) EasyMock.anyObject(), EasyMock.anyLong()); EasyMock.expectLastCall().anyTimes(); response.setHeader((String) EasyMock.anyObject(), (String) EasyMock.anyObject()); EasyMock.expectLastCall().anyTimes(); EasyMock.replay(request, rm); servlet.start(); servlet.doPut(request, response); EasyMock.verify(request, rm); Assert.assertEquals(hasLocationHeader, headers.containsKey("X-Location")); return headers; } finally { server.stop(); if (old != null) { System.setProperty("karaf.data", old); } } }
From source file:es.juntadeandalucia.mapea.proxy.ProxyRedirect.java
/*************************************************************************** * Process the HTTP Get request/*from ww w .j a va 2s. c o m*/ ***************************************************************************/ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException { String serverUrl = request.getParameter("url"); // manages a get request if it's the geoprint or getcapabilities operation boolean isGeoprint = serverUrl.toLowerCase().contains("mapeaop=geoprint"); boolean isGetCapabilities = serverUrl.toLowerCase().contains("getcapabilities"); boolean isGetFeatureInfo = serverUrl.toLowerCase().contains("wmsinfo"); if (isGeoprint || isGetCapabilities || isGetFeatureInfo) { String strErrorMessage = ""; serverUrl = checkTypeRequest(serverUrl); if (!serverUrl.equals("ERROR")) { // removes mapeaop parameter String url = serverUrl.replaceAll("\\&?\\??mapeaop=geoprint", ""); url = serverUrl.replaceAll("\\&?\\??mapeaop=getcapabilities", ""); url = serverUrl.replaceAll("\\&?\\??mapeaop=wmsinfo", ""); HttpClient client = new HttpClient(); GetMethod httpget = null; try { httpget = new GetMethod(url); HttpClientParams params = client.getParams(); params.setIntParameter(HttpClientParams.MAX_REDIRECTS, numMaxRedirects); client.executeMethod(httpget); // REDIRECTS MANAGEMENT if (httpget.getStatusCode() == HttpStatus.SC_OK) { // PATH_SECURITY_PROXY - AG Header[] respHeaders = httpget.getResponseHeaders(); int compSize = httpget.getResponseBody().length; ArrayList<Header> headerList = new ArrayList<Header>(Arrays.asList(respHeaders)); String headersString = headerList.toString(); boolean checkedContent = checkContent(headersString, compSize, serverUrl); // FIN_PATH_SECURITY_PROXY if (checkedContent) { if (request.getProtocol().compareTo("HTTP/1.0") == 0) { response.setHeader("Pragma", "no-cache"); } else if (request.getProtocol().compareTo("HTTP/1.1") == 0) { response.setHeader("Cache-Control", "no-cache"); } response.setDateHeader("Expires", -1); // set content-type headers if (isGeoprint) { response.setContentType("application/json"); } else if (isGetCapabilities) { response.setContentType("text/xml"); } /* * checks if it has requested an getfeatureinfo to modify the response content * type. */ String requesteredUrl = request.getParameter("url"); if (GETINFO_PLAIN_REGEX.matcher(requesteredUrl).matches()) { response.setContentType("text/plain"); } else if (GETINFO_GML_REGEX.matcher(requesteredUrl).matches()) { response.setContentType("application/gml+xml"); } else if (GETINFO_HTML_REGEX.matcher(requesteredUrl).matches()) { response.setContentType("text/html"); } InputStream st = httpget.getResponseBodyAsStream(); ServletOutputStream sos = response.getOutputStream(); IOUtils.copy(st, sos); } else { strErrorMessage += errorType; log.error(strErrorMessage); } } else { strErrorMessage = "Unexpected failure: " + httpget.getStatusLine().toString(); log.error(strErrorMessage); } httpget.releaseConnection(); } catch (Exception e) { log.error("Error al tratar el contenido de la peticion: " + e.getMessage(), e); } finally { if (httpget != null) { httpget.releaseConnection(); } } } else { // String errorXML = strErrorMessage; String errorXML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><error><descripcion>Error en el parametro url de entrada</descripcion></error>"; response.setContentType("text/xml"); try { PrintWriter out = response.getWriter(); out.print(errorXML); response.flushBuffer(); } catch (Exception e) { log.error(e); } } } else { doPost(request, response); } }
From source file:org.openmrs.module.patientnarratives.web.servlet.FileServlet.java
/** * Process the actual request.// w w w .j a va 2 s . c o m * @param request The request to be processed. * @param response The response to be created. * @param content Whether the request body should be written (GET) or not (HEAD). * @throws IOException If something fails at I/O level. */ private void processRequest(HttpServletRequest request, HttpServletResponse response, boolean content) throws IOException { // Validate the requested file ------------------------------------------------------------ Integer videoObsId = Integer.parseInt(request.getParameter("obsId")); Obs complexObs = Context.getObsService().getComplexObs(videoObsId, OpenmrsConstants.RAW_VIEW); ComplexData complexData = complexObs.getComplexData(); byte[] videoObjectData = ((byte[]) complexData.getData()); String fileExt_file = complexData.getTitle(); String arrFileExt[] = fileExt_file.split(" "); tempMergedVideoFile = createFile(arrFileExt[0]); String requestedFile = tempMergedVideoFile.getCanonicalPath(); FileUtils.writeByteArrayToFile(new File(requestedFile), videoObjectData); // Check if file is actually supplied to the request URL. if (requestedFile == null) { // Do your thing if the file is not supplied to the request URL. // Throw an exception, or send 404, or show default/warning page, or just ignore it. response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // URL-decode the file name (might contain spaces and on) and prepare file object. File file = new File(requestedFile); // Check if file actually exists in filesystem. if (!file.exists()) { // Do your thing if the file appears to be non-existing. // Throw an exception, or send 404, or show default/warning page, or just ignore it. response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // Prepare some variables. The ETag is an unique identifier of the file. String fileName = file.getName(); long length = file.length(); long lastModified = file.lastModified(); String eTag = fileName + "_" + length + "_" + lastModified; long expires = System.currentTimeMillis() + DEFAULT_EXPIRE_TIME; // Validate request headers for caching --------------------------------------------------- // If-None-Match header should contain "*" or ETag. If so, then return 304. String ifNoneMatch = request.getHeader("If-None-Match"); if (ifNoneMatch != null && matches(ifNoneMatch, eTag)) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); response.setHeader("ETag", eTag); // Required in 304. response.setDateHeader("Expires", expires); // Postpone cache with 1 week. return; } // If-Modified-Since header should be greater than LastModified. If so, then return 304. // This header is ignored if any If-None-Match header is specified. long ifModifiedSince = request.getDateHeader("If-Modified-Since"); if (ifNoneMatch == null && ifModifiedSince != -1 && ifModifiedSince + 1000 > lastModified) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); response.setHeader("ETag", eTag); // Required in 304. response.setDateHeader("Expires", expires); // Postpone cache with 1 week. return; } // Validate request headers for resume ---------------------------------------------------- // If-Match header should contain "*" or ETag. If not, then return 412. String ifMatch = request.getHeader("If-Match"); if (ifMatch != null && !matches(ifMatch, eTag)) { response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); return; } // If-Unmodified-Since header should be greater than LastModified. If not, then return 412. long ifUnmodifiedSince = request.getDateHeader("If-Unmodified-Since"); if (ifUnmodifiedSince != -1 && ifUnmodifiedSince + 1000 <= lastModified) { response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); return; } // Validate and process range ------------------------------------------------------------- // Prepare some variables. The full Range represents the complete file. Range full = new Range(0, length - 1, length); List<Range> ranges = new ArrayList<Range>(); // Validate and process Range and If-Range headers. String range = request.getHeader("Range"); if (range != null) { // Range header should match format "bytes=n-n,n-n,n-n...". If not, then return 416. if (!range.matches("^bytes=\\d*-\\d*(,\\d*-\\d*)*$")) { response.setHeader("Content-Range", "bytes */" + length); // Required in 416. response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); return; } // If-Range header should either match ETag or be greater then LastModified. If not, // then return full file. String ifRange = request.getHeader("If-Range"); if (ifRange != null && !ifRange.equals(eTag)) { try { long ifRangeTime = request.getDateHeader("If-Range"); // Throws IAE if invalid. if (ifRangeTime != -1 && ifRangeTime + 1000 < lastModified) { ranges.add(full); } } catch (IllegalArgumentException ignore) { ranges.add(full); } } // If any valid If-Range header, then process each part of byte range. if (ranges.isEmpty()) { for (String part : range.substring(6).split(",")) { // Assuming a file with length of 100, the following examples returns bytes at: // 50-80 (50 to 80), 40- (40 to length=100), -20 (length-20=80 to length=100). long start = sublong(part, 0, part.indexOf("-")); long end = sublong(part, part.indexOf("-") + 1, part.length()); if (start == -1) { start = length - end; end = length - 1; } else if (end == -1 || end > length - 1) { end = length - 1; } // Check if Range is syntactically valid. If not, then return 416. if (start > end) { response.setHeader("Content-Range", "bytes */" + length); // Required in 416. response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); return; } // Add range. ranges.add(new Range(start, end, length)); } } } // Prepare and initialize response -------------------------------------------------------- // Get content type by file name and set default GZIP support and content disposition. String contentType = getServletContext().getMimeType(fileName); boolean acceptsGzip = false; String disposition = "inline"; // If content type is unknown, then set the default value. // For all content types, see: http://www.w3schools.com/media/media_mimeref.asp // To add new content types, add new mime-mapping entry in web.xml. if (contentType == null) { contentType = "application/octet-stream"; } // If content type is text, then determine whether GZIP content encoding is supported by // the browser and expand content type with the one and right character encoding. if (contentType.startsWith("text")) { String acceptEncoding = request.getHeader("Accept-Encoding"); acceptsGzip = acceptEncoding != null && accepts(acceptEncoding, "gzip"); contentType += ";charset=UTF-8"; } // Else, expect for images, determine content disposition. If content type is supported by // the browser, then set to inline, else attachment which will pop a 'save as' dialogue. else if (!contentType.startsWith("image")) { String accept = request.getHeader("Accept"); disposition = accept != null && accepts(accept, contentType) ? "inline" : "attachment"; } // Initialize response. response.reset(); response.setBufferSize(DEFAULT_BUFFER_SIZE); response.setHeader("Content-Disposition", disposition + ";filename=\"" + fileName + "\""); response.setHeader("Accept-Ranges", "bytes"); response.setHeader("ETag", eTag); response.setDateHeader("Last-Modified", lastModified); response.setDateHeader("Expires", expires); // Send requested file (part(s)) to client ------------------------------------------------ // Prepare streams. RandomAccessFile input = null; OutputStream output = null; try { // Open streams. input = new RandomAccessFile(file, "r"); output = response.getOutputStream(); if (ranges.isEmpty() || ranges.get(0) == full) { // Return full file. Range r = full; response.setContentType(contentType); response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total); if (content) { if (acceptsGzip) { // The browser accepts GZIP, so GZIP the content. response.setHeader("Content-Encoding", "gzip"); output = new GZIPOutputStream(output, DEFAULT_BUFFER_SIZE); } else { // Content length is not directly predictable in case of GZIP. // So only add it if there is no means of GZIP, else browser will hang. response.setHeader("Content-Length", String.valueOf(r.length)); } // Copy full range. copy(input, output, r.start, r.length); } } else if (ranges.size() == 1) { // Return single part of file. Range r = ranges.get(0); response.setContentType(contentType); response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total); response.setHeader("Content-Length", String.valueOf(r.length)); response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206. if (content) { // Copy single part range. copy(input, output, r.start, r.length); } } else { // Return multiple parts of file. response.setContentType("multipart/byteranges; boundary=" + MULTIPART_BOUNDARY); response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206. if (content) { // Cast back to ServletOutputStream to get the easy println methods. ServletOutputStream sos = (ServletOutputStream) output; // Copy multi part range. for (Range r : ranges) { // Add multipart boundary and header fields for every range. sos.println(); sos.println("--" + MULTIPART_BOUNDARY); sos.println("Content-Type: " + contentType); sos.println("Content-Range: bytes " + r.start + "-" + r.end + "/" + r.total); // Copy single part range of multi part range. copy(input, output, r.start, r.length); } // End with multipart boundary. sos.println(); sos.println("--" + MULTIPART_BOUNDARY + "--"); } } } finally { // Gently close streams. close(output); close(input); tempMergedVideoFile.delete(); } }
From source file:fr.insalyon.creatis.vip.datamanager.server.rpc.FileUploadServiceImpl.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { User user = (User) request.getSession().getAttribute(CoreConstants.SESSION_USER); if (user != null && ServletFileUpload.isMultipartContent(request)) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try {//from w ww.ja va2 s . co m List items = upload.parseRequest(request); Iterator iter = items.iterator(); String fileName = null; FileItem fileItem = null; String path = null; String target = "uploadComplete"; String operationID = "no-id"; while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.getFieldName().equals("path")) { path = item.getString(); } else if (item.getFieldName().equals("file")) { fileName = item.getName(); fileItem = item; } else if (item.getFieldName().equals("target")) { target = item.getString(); } } if (fileName != null && !fileName.equals("")) { boolean local = path.equals("local") ? true : false; String rootDirectory = DataManagerUtil.getUploadRootDirectory(local); fileName = new File(fileName).getName().trim().replaceAll(" ", "_"); fileName = Normalizer.normalize(fileName, Normalizer.Form.NFD) .replaceAll("\\p{InCombiningDiacriticalMarks}+", ""); File uploadedFile = new File(rootDirectory + fileName); try { fileItem.write(uploadedFile); response.getWriter().write(fileName); if (!local) { // GRIDA Pool Client logger.info("(" + user.getEmail() + ") Uploading '" + uploadedFile.getAbsolutePath() + "' to '" + path + "'."); GRIDAPoolClient client = CoreUtil.getGRIDAPoolClient(); operationID = client.uploadFile(uploadedFile.getAbsolutePath(), DataManagerUtil.parseBaseDir(user, path), user.getEmail()); } else { operationID = fileName; logger.info( "(" + user.getEmail() + ") Uploaded '" + uploadedFile.getAbsolutePath() + "'."); } } catch (Exception ex) { logger.error(ex); } } response.setContentType("text/html"); response.setHeader("Pragma", "No-cache"); response.setDateHeader("Expires", 0); response.setHeader("Cache-Control", "no-cache"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<body>"); out.println("<script type=\"text/javascript\">"); out.println("if (parent." + target + ") parent." + target + "('" + operationID + "');"); out.println("</script>"); out.println("</body>"); out.println("</html>"); out.flush(); } catch (FileUploadException ex) { logger.error(ex); } } }