List of usage examples for javax.servlet.http HttpServletResponse SC_NOT_MODIFIED
int SC_NOT_MODIFIED
To view the source code for javax.servlet.http HttpServletResponse SC_NOT_MODIFIED.
Click Source Link
From source file:com.liferay.lms.servlet.SCORMFileServerServlet.java
/** * Procesa los metodos HTTP GET y POST.<br> * Busca en la ruta que se le ha pedido el comienzo del directorio * "contenidos" y sirve el fichero.// w ww. j a va 2 s . c o m */ protected void processRequest(HttpServletRequest request, HttpServletResponse response, boolean content) throws ServletException, java.io.IOException { String mime_type; String charset; String patharchivo; String uri; try { User user = PortalUtil.getUser(request); if (user == null) { String userId = null; String companyId = null; Cookie[] cookies = ((HttpServletRequest) request).getCookies(); if (Validator.isNotNull(cookies)) { for (Cookie c : cookies) { if ("COMPANY_ID".equals(c.getName())) { companyId = c.getValue(); } else if ("ID".equals(c.getName())) { userId = hexStringToStringByAscii(c.getValue()); } } } if (userId != null && companyId != null) { try { Company company = CompanyLocalServiceUtil.getCompany(Long.parseLong(companyId)); Key key = company.getKeyObj(); String userIdPlain = Encryptor.decrypt(key, userId); user = UserLocalServiceUtil.getUser(Long.valueOf(userIdPlain)); // Now you can set the liferayUser into a thread local // for later use or // something like that. } catch (Exception pException) { throw new RuntimeException(pException); } } } String rutaDatos = SCORMContentLocalServiceUtil.getBaseDir(); // Se comprueba que el usuario tiene permisos para acceder. // Damos acceso a todo el mundo al directorio "personalizacion", // para permitir mostrar a todos la pantalla de identificacion. uri = URLDecoder.decode(request.getRequestURI(), "UTF-8"); uri = uri.substring(uri.indexOf("scorm/") + "scorm/".length()); patharchivo = rutaDatos + "/" + uri; String[] params = uri.split("/"); long groupId = GetterUtil.getLong(params[1]); String uuid = params[2]; SCORMContent scormContent = SCORMContentLocalServiceUtil.getSCORMContentByUuidAndGroupId(uuid, groupId); boolean allowed = false; if (user == null) { user = UserLocalServiceUtil.getDefaultUser(PortalUtil.getDefaultCompanyId()); } PermissionChecker pc = PermissionCheckerFactoryUtil.create(user); allowed = pc.hasPermission(groupId, SCORMContent.class.getName(), scormContent.getScormId(), ActionKeys.VIEW); if (!allowed) { AssetEntry scormAsset = AssetEntryLocalServiceUtil.getEntry(SCORMContent.class.getName(), scormContent.getPrimaryKey()); long scormAssetId = scormAsset.getEntryId(); int typeId = new Long((new SCORMLearningActivityType()).getTypeId()).intValue(); long[] groupIds = user.getGroupIds(); for (long gId : groupIds) { List<LearningActivity> acts = LearningActivityLocalServiceUtil .getLearningActivitiesOfGroupAndType(gId, typeId); for (LearningActivity act : acts) { String entryId = LearningActivityLocalServiceUtil.getExtraContentValue(act.getActId(), "assetEntry"); if (Validator.isNotNull(entryId) && Long.valueOf(entryId) == scormAssetId) { allowed = pc.hasPermission(gId, LearningActivity.class.getName(), act.getActId(), ActionKeys.VIEW); if (allowed) { break; } } } if (allowed) { break; } } } if (allowed) { File archivo = new File(patharchivo); // Si el archivo existe y no es un directorio se sirve. Si no, // no se hace nada. if (archivo.exists() && archivo.isFile()) { // El content type siempre antes del printwriter mime_type = MimeTypesUtil.getContentType(archivo); charset = ""; if (archivo.getName().toLowerCase().endsWith(".html") || archivo.getName().toLowerCase().endsWith(".htm")) { mime_type = "text/html"; if (isISO(FileUtils.readFileToString(archivo))) { charset = "ISO-8859-1"; } } if (archivo.getName().toLowerCase().endsWith(".swf")) { mime_type = "application/x-shockwave-flash"; } if (archivo.getName().toLowerCase().endsWith(".mp4")) { mime_type = "video/mp4"; } if (archivo.getName().toLowerCase().endsWith(".flv")) { mime_type = "video/x-flv"; } response.setContentType(mime_type); if (Validator.isNotNull(charset)) { response.setCharacterEncoding(charset); } response.addHeader("Content-Type", mime_type + (Validator.isNotNull(charset) ? "; " + charset : "")); /*if (archivo.getName().toLowerCase().endsWith(".swf") || archivo.getName().toLowerCase().endsWith(".flv")) { response.addHeader("Content-Length", String.valueOf(archivo.length())); } */ if (archivo.getName().toLowerCase().endsWith("imsmanifest.xml")) { FileInputStream fis = new FileInputStream(patharchivo); String sco = ParamUtil.get(request, "scoshow", ""); Document manifest = SAXReaderUtil.read(fis); if (sco.length() > 0) { Element organizatEl = manifest.getRootElement().element("organizations") .element("organization"); Element selectedItem = selectItem(organizatEl, sco); if (selectedItem != null) { selectedItem.detach(); java.util.List<Element> items = organizatEl.elements("item"); for (Element item : items) { organizatEl.remove(item); } organizatEl.add(selectedItem); } } //clean unused resources. Element resources = manifest.getRootElement().element("resources"); java.util.List<Element> theResources = resources.elements("resource"); Element organizatEl = manifest.getRootElement().element("organizations") .element("organization"); java.util.List<String> identifiers = getIdentifierRefs(organizatEl); for (Element resource : theResources) { String identifier = resource.attributeValue("identifier"); if (!identifiers.contains(identifier)) { resources.remove(resource); } } response.getWriter().print(manifest.asXML()); fis.close(); return; } if (mime_type.startsWith("text") || mime_type.endsWith("javascript") || mime_type.equals("application/xml")) { java.io.OutputStream out = response.getOutputStream(); FileInputStream fis = new FileInputStream(patharchivo); byte[] buffer = new byte[512]; int i = 0; while (fis.available() > 0) { i = fis.read(buffer); if (i == 512) out.write(buffer); else out.write(buffer, 0, i); } fis.close(); out.flush(); out.close(); return; } //If not manifest String fileName = archivo.getName(); long length = archivo.length(); long lastModified = archivo.lastModified(); String eTag = fileName + "_" + length + "_" + lastModified; long expires = System.currentTimeMillis() + DEFAULT_EXPIRE_TIME; 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; } 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; } // 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)); } } } boolean acceptsGzip = false; String disposition = "inline"; if (mime_type.startsWith("text")) { //String acceptEncoding = request.getHeader("Accept-Encoding"); // acceptsGzip = acceptEncoding != null && accepts(acceptEncoding, "gzip"); // mime_type += ";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 (!mime_type.startsWith("image")) { String accept = request.getHeader("Accept"); disposition = accept != null && accepts(accept, mime_type) ? "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(archivo, "r"); output = response.getOutputStream(); if (ranges.isEmpty() || ranges.get(0) == full) { // Return full file. Range r = full; response.setContentType(mime_type); response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total); if (content) { // 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(mime_type); 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: " + mime_type); 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); } } else { //java.io.OutputStream out = response.getOutputStream(); response.sendError(404); //out.write(uri.getBytes()); } } else { response.sendError(401); } } catch (Exception e) { System.out.println("Error en el processRequest() de ServidorArchivos: " + e.getMessage()); } }
From source file:com.meltmedia.cadmium.servlets.BasicFileServlet.java
public boolean handleConditions(FileRequestContext context) throws IOException { // check the conditions context.eTag = context.path + "_" + lastUpdated; context.ifMatch = context.request.getHeader(IF_MATCH_HEADER); if (context.ifMatch != null && !validateStrong(context.ifMatch, context.eTag)) { context.response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); return true; }//w ww. java2 s. c o m context.range = context.request.getHeader(RANGE_HEADER); try { context.inRangeDate = context.request.getDateHeader(IF_RANGE_HEADER); if (context.inRangeDate != -1 && context.inRangeDate >= lastUpdated) { if (!parseRanges(context)) { invalidRanges(context); return true; } } } catch (IllegalArgumentException iae) { logger.error("Invalid range serving request: " + context.path, iae); context.inRangeETag = context.request.getHeader(IF_RANGE_HEADER); if (context.inRangeETag != null && validateStrong(context.inRangeETag, context.eTag)) { if (!parseRanges(context)) { invalidRanges(context); return true; } } } if (context.inRangeDate == -1 && context.inRangeETag == null) { if (!parseRanges(context)) { invalidRanges(context); return true; } } context.ifNoneMatch = context.request.getHeader(IF_NONE_MATCH_HEADER); if (context.ifNoneMatch != null && validateStrong(context.ifNoneMatch, context.eTag)) { context.response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); context.response.setHeader(ETAG_HEADER, context.eTag); context.response.setDateHeader(LAST_MODIFIED_HEADER, lastUpdated); return true; } context.ifModifiedSince = context.request.getDateHeader(IF_MODIFIED_SINCE_HEADER); if (context.ifModifiedSince != -1 && context.ifModifiedSince >= lastUpdated) { context.response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); context.response.setHeader(ETAG_HEADER, context.eTag); context.response.setDateHeader(LAST_MODIFIED_HEADER, lastUpdated); return true; } context.ifUnmodifiedSince = context.request.getDateHeader(IF_UNMODIFIED_SINCE_HEADER); if (context.ifUnmodifiedSince != -1 && context.ifUnmodifiedSince < lastUpdated) { context.response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); return true; } return false; }
From source file:com.adobe.cq.wcm.core.components.internal.servlets.AdaptiveImageServletTest.java
@Test public void testGIFUploadedToDAMBrowserCached() throws Exception { MockSlingHttpServletResponse response = spy(aemContext.response()); MockSlingHttpServletRequest request = prepareRequest(IMAGE6_PATH, "img", "gif"); // 1 millisecond less than the jcr:lastModified value from test-conf.json request.addDateHeader("If-Modified-Since", 1489998822137L); servlet.doGet(request, response);//from w w w .ja va2s.co m assertEquals(HttpServletResponse.SC_NOT_MODIFIED, response.getStatus()); }
From source file:com.google.gwt.jolokia.server.servlet.ProxyServlet.java
protected boolean doResponseRedirectOrNotModifiedLogic(HttpServletRequest servletRequest, HttpServletResponse servletResponse, HttpResponse proxyResponse, int statusCode) throws ServletException, IOException { // Check if the proxy response is a redirect // The following code is adapted from // org.tigris.noodle.filters.CheckForRedirect if (statusCode >= HttpServletResponse.SC_MULTIPLE_CHOICES /* 300 */ && statusCode < HttpServletResponse.SC_NOT_MODIFIED /* 304 */) { Header locationHeader = proxyResponse.getLastHeader(HttpHeaders.LOCATION); if (locationHeader == null) { throw new ServletException("Received status code: " + statusCode + " but no " + HttpHeaders.LOCATION + " header was found in the response"); }//w w w. jav a2 s. c o m // Modify the redirect to go to this proxy servlet rather that the // proxied host String locStr = rewriteUrlFromResponse(servletRequest, locationHeader.getValue()); servletResponse.sendRedirect(locStr); return true; } // 304 needs special handling. See: // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304 // We get a 304 whenever passed an 'If-Modified-Since' // header and the data on disk has not changed; server // responds w/ a 304 saying I'm not going to send the // body because the file has not changed. if (statusCode == HttpServletResponse.SC_NOT_MODIFIED) { servletResponse.setIntHeader(HttpHeaders.CONTENT_LENGTH, 0); servletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return true; } return false; }
From source file:it.geosdi.era.server.servlet.HTTPProxy.java
/** * Executes the {@link HttpMethod} passed in and sends the proxy response * back to the client via the given {@link HttpServletResponse} * @param httpMethodProxyRequest An object representing the proxy request to be made * @param httpServletResponse An object by which we can send the proxied * response back to the client * @param digest //from w w w .j a va 2 s .c om * @throws IOException Can be thrown by the {@link HttpClient}.executeMethod * @throws ServletException Can be thrown to indicate that another error has occurred */ private void executeProxyRequest(HttpMethod httpMethodProxyRequest, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, String user, String password) throws IOException, ServletException { // Create a default HttpClient HttpClient httpClient = new HttpClient(); if (user != null && password != null) { UsernamePasswordCredentials upc = new UsernamePasswordCredentials(user, password); httpClient.getState().setCredentials(AuthScope.ANY, upc); } httpMethodProxyRequest.setFollowRedirects(false); // Execute the request int intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest); // Check if the proxy response is a redirect // The following code is adapted from org.tigris.noodle.filters.CheckForRedirect // Hooray for open source software if (intProxyResponseCode >= HttpServletResponse.SC_MULTIPLE_CHOICES /* 300 */ && intProxyResponseCode < HttpServletResponse.SC_NOT_MODIFIED /* 304 */) { String stringStatusCode = Integer.toString(intProxyResponseCode); String stringLocation = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue(); if (stringLocation == null) { throw new ServletException("Recieved status code: " + stringStatusCode + " but no " + STRING_LOCATION_HEADER + " header was found in the response"); } // Modify the redirect to go to this proxy servlet rather that the proxied host String stringMyHostName = httpServletRequest.getServerName(); if (httpServletRequest.getServerPort() != 80) { stringMyHostName += ":" + httpServletRequest.getServerPort(); } stringMyHostName += httpServletRequest.getContextPath(); httpServletResponse.sendRedirect( stringLocation.replace(getProxyHostAndPort() + this.getProxyPath(), stringMyHostName)); return; } else if (intProxyResponseCode == HttpServletResponse.SC_NOT_MODIFIED) { // 304 needs special handling. See: // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304 // We get a 304 whenever passed an 'If-Modified-Since' // header and the data on disk has not changed; server // responds w/ a 304 saying I'm not going to send the // body because the file has not changed. httpServletResponse.setIntHeader(STRING_CONTENT_LENGTH_HEADER_NAME, 0); httpServletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return; } // Pass the response code back to the client httpServletResponse.setStatus(intProxyResponseCode); // Pass response headers back to the client Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders(); for (Header header : headerArrayResponse) { // Skip GZIP Responses if (header.getName().equalsIgnoreCase(HTTP_HEADER_ACCEPT_ENCODING) && header.getValue().toLowerCase().contains("gzip")) continue; else if (header.getName().equalsIgnoreCase(HTTP_HEADER_CONTENT_ENCODING) && header.getValue().toLowerCase().contains("gzip")) continue; else if (header.getName().equalsIgnoreCase(HTTP_HEADER_TRANSFER_ENCODING)) continue; else httpServletResponse.setHeader(header.getName(), header.getValue()); } // Send the content to the client InputStream inputStreamServerResponse = httpMethodProxyRequest.getResponseBodyAsStream(); OutputStream outputStreamClientResponse = httpServletResponse.getOutputStream(); int read; while ((read = inputStreamServerResponse.read()) > 0) { if (escapeHtmlFull(read) > 0) { outputStreamClientResponse.write(read); } } inputStreamServerResponse.close(); outputStreamClientResponse.write('\n'); outputStreamClientResponse.flush(); outputStreamClientResponse.close(); }
From source file:com.vmware.appfactory.common.base.AbstractController.java
/** * Apply Etag caching to the request. In the request header, * if the 'If-None-Match' field is either empty or does not match * with the new token; it then set current date in the 'Last-Modified' * field. Otherwise, it sends 304 code back in the response. * * @param request - a HttpServletRequest. * @param response - a HttpServletResponse. * @param newToken - a new token to be set in the response's Etag header. * @return it always returns previous token from the request's * 'If-None-Match' header./*from www. j a v a2s . c o m*/ * @throws IOException if any error raised while setting * Etag caching related Http headers. */ protected String applyETagCache(HttpServletRequest request, HttpServletResponse response, String newToken, boolean setExpires) throws IOException { if (!StringUtils.hasLength(newToken)) { throw new IllegalArgumentException("Invalid newToken - " + newToken); } // Get the current date/time final Calendar cal = Calendar.getInstance(); cal.set(Calendar.MILLISECOND, 0); final Date lastModified = cal.getTime(); response.setHeader("Pragma", "cache"); response.setHeader("Cache-Control", "public, must-revalidate"); // Set the Expires and Cache-Control: max-age headers to 1 year in the future if (setExpires) { // Get the date/time 1 year from now cal.add(Calendar.YEAR, 1); final Date expires = cal.getTime(); response.addHeader("Cache-Control", "max-age=3153600"); response.setDateHeader("Expires", expires.getTime()); } // Always store new token in the ETag header. response.setHeader("ETag", newToken); String previousToken = request.getHeader("If-None-Match"); if (newToken.equals(previousToken)) { response.sendError(HttpServletResponse.SC_NOT_MODIFIED); response.setHeader("Last-Modified", request.getHeader("If-Modified-Since")); } else { response.setDateHeader("Last-Modified", lastModified.getTime()); } return previousToken; }
From source file:com.wordpress.metaphorm.authProxy.httpClient.impl.OAuthProxyConnectionApacheHttpCommonsClientImpl.java
/** * Executes the {@link HttpMethod} passed in and sends the proxy response * back to the client via the given {@link HttpServletResponse} * @param httpMethodProxyRequest An object representing the proxy request to be made * @param httpServletResponse An object by which we can send the proxied * response back to the client * @throws IOException Can be thrown by the {@link HttpClient}.executeMethod * @throws ServletException Can be thrown to indicate that another error has occurred *//*from w w w. j av a 2s .co m*/ private void executeProxyRequest(HttpMethod httpMethodProxyRequest) throws IOException, RedirectRequiredException { //Utils.traceRequest(httpServletRequest); // Create a default HttpClient HttpClient httpClient = new HttpClient(); httpMethodProxyRequest.setFollowRedirects(false); _log.debug("Sending request to " + httpMethodProxyRequest.getURI()); for (Header header : httpMethodProxyRequest.getRequestHeaders()) { _log.debug(" Header \"" + header.getName() + "\" = \"" + header.getValue() + "\""); } // Execute the request int intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest); // Persist the respose headers this.responseHeaderMap = new HashMap<String, List<String>>(); for (Header header : this.httpMethod.getResponseHeaders()) { responseHeaderMap.put(header.getName(), Arrays.asList(header.getValue())); } // Check if the proxy response is a redirect // The following code is adapted from org.tigris.noodle.filters.CheckForRedirect // Hooray for open source software if (intProxyResponseCode >= HttpServletResponse.SC_MULTIPLE_CHOICES /* 300 */ && intProxyResponseCode < HttpServletResponse.SC_NOT_MODIFIED /* 304 */) { String stringStatusCode = Integer.toString(intProxyResponseCode); String stringLocation = httpMethodProxyRequest.getResponseHeader(HttpConstants.STRING_LOCATION_HEADER) .getValue(); if (stringLocation == null) { throw new IOException("Recieved status code: " + stringStatusCode + " but no " + HttpConstants.STRING_LOCATION_HEADER + " header was found in the response"); } throw new RedirectRequiredException(new URL(stringLocation)); } else if (intProxyResponseCode == HttpServletResponse.SC_NOT_MODIFIED) { // 304 needs special handling. See: // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304 // We get a 304 whenever passed an 'If-Modified-Since' // header and the data on disk has not changed; server // responds w/ a 304 saying I'm not going to send the // body because the file has not changed. //httpServletResponse.setIntHeader(HttpConstants.STRING_CONTENT_LENGTH_HEADER_NAME, 0); //httpServletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED); } // Pass the response code back to the client this.httpStatusCode = intProxyResponseCode; _log.debug("Response code was " + this.httpStatusCode); // Pass response headers back to the client // TODO: Implement support for proxying response headers //Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders(); //for(Header header : headerArrayResponse) { // httpServletResponse.setHeader(header.getName(), header.getValue()); //} // Send the content to the client //InputStream inputStreamProxyResponse = httpMethodProxyRequest.getResponseBodyAsStream(); //BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStreamProxyResponse); //OutputStream outputStreamClientResponse = httpServletResponse.getOutputStream(); //int intNextByte; //while ( ( intNextByte = bufferedInputStream.read() ) != -1 ) { // outputStreamClientResponse.write(intNextByte); //} }
From source file:org.seasar.mayaa.impl.engine.EngineImpl.java
protected void doResourceService(ServiceCycle cycle) { if (cycle == null) { throw new IllegalArgumentException(); }/* w ww . ja v a2s . c om*/ String path = cycle.getRequestScope().getRequestedPath(); SourceDescriptor source = SourceUtil.getSourceDescriptor(path); source.setSystemID(path); String[] modifiedSinces = (String[]) cycle.getRequestScope().getHeaderValues() .getAttribute("If-Modified-Since"); if (modifiedSinces != null && modifiedSinces.length > 0) { String modifiedSince = modifiedSinces[0]; Date sinceDate = null; DateFormat format = DateFormatPool.borrowRFC1123Format(); try { sinceDate = format.parse(modifiedSince); } catch (ParseException e) { DateFormat format2 = DateFormatPool.borrowRFC2822Format(); try { sinceDate = format2.parse(modifiedSince); } catch (ParseException e2) { // give up } finally { DateFormatPool.returnFormat(format2); } } finally { DateFormatPool.returnFormat(format); } Date sourceTimestamp = new Date(source.getTimestamp().getTime() / 1000 * 1000); if (sinceDate != null && sourceTimestamp.after(sinceDate) == false) { cycle.getResponse().setStatus(HttpServletResponse.SC_NOT_MODIFIED); return; } } InputStream stream = source.getInputStream(); if (stream != null) { DateFormat format = DateFormatPool.borrowRFC1123Format(); try { cycle.getResponse().setHeader("Last-Modified", format.format(source.getTimestamp())); } finally { DateFormatPool.returnFormat(format); } OutputStream out = cycle.getResponse().getOutputStream(); try { byte[] buffer = new byte[512]; int readln; while ((readln = stream.read(buffer)) != -1) { out.write(buffer, 0, readln); } out.flush(); } catch (IOException e) { if (EngineUtil.isClientAbortException(e)) { stream = null; } else { throw new RuntimeException(e); } } finally { if (stream != null) { IOUtil.close(stream); } } } else { cycle.getResponse().setStatus(HttpServletResponse.SC_NOT_FOUND); } }
From source file:org.ops4j.pax.web.resources.jsf.OsgiResourceHandler.java
@Override public void handleResourceRequest(FacesContext facesContext) throws IOException { final Map<String, String> requestParameterMap = facesContext.getExternalContext().getRequestParameterMap(); if (!"osgi".equals(requestParameterMap.get(OsgiResource.REQUEST_PARAM_TYPE))) { // no OsgiResource...proceed with default ResourceHandler super.handleResourceRequest(facesContext); }// w w w. j a va2s.c o m String localePrefix = requestParameterMap.get(OsgiResource.REQUEST_PARAM_LOCALE); String libraryName = requestParameterMap.get(OsgiResource.REQUEST_PARAM_LIBRARY); String libraryVersion = requestParameterMap.get(OsgiResource.REQUEST_PARAM_LIBRARY_VERSION); String resourceVersion = requestParameterMap.get(OsgiResource.REQUEST_PARAM_RESOURCE_VERSION); String resourceBasePath = ResourceHandlerUtils.calculateResourceBasePath(facesContext); if (resourceBasePath == null) { // No base name could be calculated, so no further //advance could be done here. HttpServletResponse.SC_NOT_FOUND //cannot be returned since we cannot extract the //resource base name return; } // We neet to get an instance of HttpServletResponse, but sometimes // the response object is wrapped by several instances of // ServletResponseWrapper (like ResponseSwitch). // Since we are handling a resource, we can expect to get an // HttpServletResponse. HttpServletResponse httpServletResponse = ResourceHandlerUtils .getHttpServletResponse(facesContext.getExternalContext().getResponse()); if (httpServletResponse == null) { throw new IllegalStateException("Could not obtain an instance of HttpServletResponse."); } if (ResourceHandlerUtils.isResourceIdentifierExcluded(facesContext, resourceBasePath, excludedResourceExtensions)) { httpServletResponse.setStatus(HttpServletResponse.SC_NOT_FOUND); return; } // extract resourceName. if none was found set Response to 404 String resourceName; if (resourceBasePath.startsWith(ResourceHandler.RESOURCE_IDENTIFIER)) { resourceName = resourceBasePath.substring(ResourceHandler.RESOURCE_IDENTIFIER.length() + 1); if (!ResourceValidationUtils.isValidResourceName(resourceName)) { httpServletResponse.setStatus(HttpServletResponse.SC_NOT_FOUND); return; } } else { //Does not have the conditions for be a resource call httpServletResponse.setStatus(HttpServletResponse.SC_NOT_FOUND); return; } if (libraryName != null && !ResourceValidationUtils.isValidLibraryName(libraryName)) { httpServletResponse.setStatus(HttpServletResponse.SC_NOT_FOUND); return; } String resourceIdentifier = createResourceIdentifier(localePrefix, resourceName, resourceVersion, libraryName, libraryVersion); OsgiResource resource; // in this case we have the full path to the resource, no version-magic needed ResourceInfo resourceInfo = getServiceAndExecute(service -> service.locateResource(resourceIdentifier)); if (resourceInfo == null) { httpServletResponse.setStatus(HttpServletResponse.SC_NOT_FOUND); return; } resource = new OsgiResource(resourceInfo.getUrl(), localePrefix, resourceName, resourceVersion, libraryName, libraryVersion, resourceInfo.getLastModified()); // Resource has not changed, return 304 if (!resource.userAgentNeedsUpdate(facesContext)) { httpServletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return; } // serve httpServletResponse .setContentType(ResourceHandlerUtils.getContentType(resource, facesContext.getExternalContext())); Map<String, String> headers = resource.getResponseHeaders(); for (Map.Entry<String, String> entry : headers.entrySet()) { httpServletResponse.setHeader(entry.getKey(), entry.getValue()); } // Sets the preferred buffer size for the body of the response facesContext.getExternalContext().setResponseBufferSize(this.resourceBufferSize); //serve up the bytes (taken from trinidad ResourceServlet) try { //byte[] buffer = new byte[_BUFFER_SIZE]; byte[] buffer = new byte[this.resourceBufferSize]; try (InputStream in = resource.getInputStream(); OutputStream out = httpServletResponse.getOutputStream()) { int count = ResourceHandlerUtils.pipeBytes(in, out, buffer); //set the content length if (!httpServletResponse.isCommitted()) { httpServletResponse.setContentLength(count); } } } catch (IOException e) { if (logger.isErrorEnabled()) { logger.error("Error trying to load resource '{}' with library '{}' : {}", new Object[] { resourceName, libraryName, e.getMessage(), e }); } // return 404 httpServletResponse.setStatus(HttpServletResponse.SC_NOT_FOUND); } }
From source file:com.github.zhanhb.ckfinder.download.PathPartial.java
/** * Check if the if-modified-since condition is satisfied. * * @param request The servlet request we are processing * @param attr File attributes//w w w . j av a 2 s . c o m */ @SuppressWarnings("NestedAssignment") private void checkIfModifiedSince(HttpServletRequest request, BasicFileAttributes attr) { try { long headerValue; // If an If-None-Match header has been specified, if modified since // is ignored. if (request.getHeader(HttpHeaders.IF_NONE_MATCH) == null && (headerValue = request.getDateHeader(HttpHeaders.IF_MODIFIED_SINCE)) != -1 && attr.lastModifiedTime().toMillis() < headerValue + 1000) { // The entity has not been modified since the date // specified by the client. This is not an error case. throw new UncheckException(HttpServletResponse.SC_NOT_MODIFIED); } } catch (IllegalArgumentException ex) { } }