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:org.exist.http.urlrewrite.XQueryURLRewrite.java
@Override protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws IOException, ServletException { if (rewriteConfig == null) { configure();/*w ww.j av a 2s. c o m*/ rewriteConfig = new RewriteConfig(this); } final long start = System.currentTimeMillis(); final HttpServletRequest request = servletRequest; final HttpServletResponse response = servletResponse; if (LOG.isTraceEnabled()) { LOG.trace(request.getRequestURI()); } final Descriptor descriptor = Descriptor.getDescriptorSingleton(); if (descriptor != null && descriptor.requestsFiltered()) { final String attr = (String) request.getAttribute("XQueryURLRewrite.forwarded"); if (attr == null) { // request = new HttpServletRequestWrapper(request, /*formEncoding*/ "utf-8" ); //logs the request if specified in the descriptor descriptor.doLogRequestInReplayLog(request); request.setAttribute("XQueryURLRewrite.forwarded", "true"); } } Subject user = defaultUser; Subject requestUser = HttpAccount.getUserFromServletRequest(request); if (requestUser != null) { user = requestUser; } else { // Secondly try basic authentication final String auth = request.getHeader("Authorization"); if (auth != null) { requestUser = authenticator.authenticate(request, response); if (requestUser != null) { user = requestUser; } } } try { configure(); //checkCache(user); final RequestWrapper modifiedRequest = new RequestWrapper(request); final URLRewrite staticRewrite = rewriteConfig.lookup(modifiedRequest); if (staticRewrite != null && !staticRewrite.isControllerForward()) { modifiedRequest.setPaths(staticRewrite.resolve(modifiedRequest), staticRewrite.getPrefix()); if (LOG.isTraceEnabled()) { LOG.trace("Forwarding to target: " + staticRewrite.getTarget()); } staticRewrite.doRewrite(modifiedRequest, response); } else { if (LOG.isTraceEnabled()) { LOG.trace("Processing request URI: " + request.getRequestURI()); } if (staticRewrite != null) { // fix the request URI staticRewrite.updateRequest(modifiedRequest); } // check if the request URI is already in the url cache ModelAndView modelView = getFromCache(request.getHeader("Host") + request.getRequestURI(), user); if (LOG.isDebugEnabled()) { LOG.debug("Checked cache for URI: " + modifiedRequest.getRequestURI() + " original: " + request.getRequestURI()); } // no: create a new model and view configuration if (modelView == null) { modelView = new ModelAndView(); // Execute the query Sequence result = Sequence.EMPTY_SEQUENCE; DBBroker broker = null; try { broker = pool.get(user); modifiedRequest.setAttribute(RQ_ATTR_REQUEST_URI, request.getRequestURI()); final Properties outputProperties = new Properties(); outputProperties.setProperty(OutputKeys.INDENT, "yes"); outputProperties.setProperty(OutputKeys.ENCODING, "UTF-8"); outputProperties.setProperty(OutputKeys.MEDIA_TYPE, MimeType.XML_TYPE.getName()); result = runQuery(broker, modifiedRequest, response, modelView, staticRewrite, outputProperties); logResult(broker, result); if (response.isCommitted()) { return; } // process the query result if (result.getItemCount() == 1) { final Item resource = result.itemAt(0); if (!Type.subTypeOf(resource.getType(), Type.NODE)) { throw new ServletException( "XQueryURLRewrite: urlrewrite query should return an element!"); } Node node = ((NodeValue) resource).getNode(); if (node.getNodeType() == Node.DOCUMENT_NODE) { node = ((Document) node).getDocumentElement(); } if (node.getNodeType() != Node.ELEMENT_NODE) { //throw new ServletException("Redirect XQuery should return an XML element!"); response(broker, response, outputProperties, result); return; } Element elem = (Element) node; if (!(Namespaces.EXIST_NS.equals(elem.getNamespaceURI()))) { response(broker, response, outputProperties, result); return; // throw new ServletException("Redirect XQuery should return an element in namespace " + Namespaces.EXIST_NS); } if (Namespaces.EXIST_NS.equals(elem.getNamespaceURI()) && "dispatch".equals(elem.getLocalName())) { node = elem.getFirstChild(); while (node != null) { if (node.getNodeType() == Node.ELEMENT_NODE && Namespaces.EXIST_NS.equals(node.getNamespaceURI())) { final Element action = (Element) node; if ("view".equals(action.getLocalName())) { parseViews(modifiedRequest, action, modelView); } else if ("error-handler".equals(action.getLocalName())) { parseErrorHandlers(modifiedRequest, action, modelView); } else if ("cache-control".equals(action.getLocalName())) { final String option = action.getAttribute("cache"); modelView.setUseCache("yes".equals(option)); } else { final URLRewrite urw = parseAction(modifiedRequest, action); if (urw != null) { modelView.setModel(urw); } } } node = node.getNextSibling(); } if (modelView.getModel() == null) { modelView.setModel(new PassThrough(config, elem, modifiedRequest)); } } else if (Namespaces.EXIST_NS.equals(elem.getNamespaceURI()) && "ignore".equals(elem.getLocalName())) { modelView.setModel(new PassThrough(config, elem, modifiedRequest)); final NodeList nl = elem.getElementsByTagNameNS(Namespaces.EXIST_NS, "cache-control"); if (nl.getLength() > 0) { elem = (Element) nl.item(0); final String option = elem.getAttribute("cache"); modelView.setUseCache("yes".equals(option)); } } else { response(broker, response, outputProperties, result); return; } } else if (result.getItemCount() > 1) { response(broker, response, outputProperties, result); return; } if (modelView.useCache()) { LOG.debug("Caching request to " + request.getRequestURI()); urlCache.put(modifiedRequest.getHeader("Host") + request.getRequestURI(), modelView); } } finally { pool.release(broker); } // store the original request URI to org.exist.forward.request-uri modifiedRequest.setAttribute(RQ_ATTR_REQUEST_URI, request.getRequestURI()); modifiedRequest.setAttribute(RQ_ATTR_SERVLET_PATH, request.getServletPath()); } if (LOG.isTraceEnabled()) { LOG.trace("URLRewrite took " + (System.currentTimeMillis() - start) + "ms."); } final HttpServletResponse wrappedResponse = new CachingResponseWrapper(response, modelView.hasViews() || modelView.hasErrorHandlers()); if (modelView.getModel() == null) { modelView.setModel(new PassThrough(config, modifiedRequest)); } if (staticRewrite != null) { if (modelView.getModel().doResolve()) { staticRewrite.rewriteRequest(modifiedRequest); } else { modelView.getModel().setAbsolutePath(modifiedRequest); } } modifiedRequest.allowCaching(!modelView.hasViews()); doRewrite(modelView.getModel(), modifiedRequest, wrappedResponse); int status = ((CachingResponseWrapper) wrappedResponse).getStatus(); if (status == HttpServletResponse.SC_NOT_MODIFIED) { response.flushBuffer(); } else if (status < 400) { if (modelView.hasViews()) { applyViews(modelView, modelView.views, response, modifiedRequest, wrappedResponse); } else { ((CachingResponseWrapper) wrappedResponse).flush(); } } else { // HTTP response code indicates an error if (modelView.hasErrorHandlers()) { final byte[] data = ((CachingResponseWrapper) wrappedResponse).getData(); if (data != null) { modifiedRequest.setAttribute(RQ_ATTR_ERROR, new String(data, UTF_8)); } applyViews(modelView, modelView.errorHandlers, response, modifiedRequest, wrappedResponse); } else { flushError(response, wrappedResponse); } } } // Sequence result; // if ((result = (Sequence) request.getAttribute(RQ_ATTR_RESULT)) != null) { // writeResults(response, broker, result); // } } catch (final Throwable e) { LOG.error("Error while processing " + servletRequest.getRequestURI() + ": " + e.getMessage(), e); throw new ServletException("An error occurred while processing request to " + servletRequest.getRequestURI() + ": " + e.getMessage(), e); } }
From source file:org.nunux.poc.portal.ProxyServlet.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/*from w w w .j a v a2 s . c om*/ * @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 */ private void executeProxyRequest(HttpMethod httpMethodProxyRequest, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, ServletException { if (httpServletRequest.isSecure()) { Protocol.registerProtocol("https", new Protocol("https", new EasySSLProtocolSocketFactory(), 443)); } // Create a default HttpClient HttpClient httpClient = new HttpClient(); httpMethodProxyRequest.setFollowRedirects(false); // Execute the request int intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest); InputStream response = httpMethodProxyRequest.getResponseBodyAsStream(); // 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("Received 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(); if (followRedirects) { if (stringLocation.contains("jsessionid")) { Cookie cookie = new Cookie("JSESSIONID", stringLocation.substring(stringLocation.indexOf("jsessionid=") + 11)); cookie.setPath("/"); httpServletResponse.addCookie(cookie); //debug("redirecting: set jessionid (" + cookie.getValue() + ") cookie from URL"); } else if (httpMethodProxyRequest.getResponseHeader("Set-Cookie") != null) { Header header = httpMethodProxyRequest.getResponseHeader("Set-Cookie"); String[] cookieDetails = header.getValue().split(";"); String[] nameValue = cookieDetails[0].split("="); if (nameValue[0].equalsIgnoreCase("jsessionid")) { httpServletRequest.getSession().setAttribute("jsessionid" + this.getProxyHostAndPort(), nameValue[1]); debug("redirecting: store jsessionid: " + nameValue[1]); } else { Cookie cookie = new Cookie(nameValue[0], nameValue[1]); cookie.setPath("/"); //debug("redirecting: setting cookie: " + cookie.getName() + ":" + cookie.getValue() + " on " + cookie.getPath()); httpServletResponse.addCookie(cookie); } } 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) { if (header.getName().equals("Transfer-Encoding") && header.getValue().equals("chunked") || header.getName().equals("Content-Encoding") && header.getValue().equals("gzip") || // don't copy gzip header header.getName().equals("WWW-Authenticate")) { // don't copy WWW-Authenticate header so browser doesn't prompt on failed basic auth // proxy servlet does not support chunked encoding } else if (header.getName().equals("Set-Cookie")) { String[] cookieDetails = header.getValue().split(";"); String[] nameValue = cookieDetails[0].split("="); if (nameValue[0].equalsIgnoreCase("jsessionid")) { httpServletRequest.getSession().setAttribute("jsessionid" + this.getProxyHostAndPort(), nameValue[1]); debug("redirecting: store jsessionid: " + nameValue[1]); } else { httpServletResponse.setHeader(header.getName(), header.getValue()); } } else { httpServletResponse.setHeader(header.getName(), header.getValue()); } } List<Header> responseHeaders = Arrays.asList(headerArrayResponse); if (isBodyParameterGzipped(responseHeaders)) { debug("GZipped: true"); int length = 0; if (!followRedirects && intProxyResponseCode == HttpServletResponse.SC_MOVED_TEMPORARILY) { String gz = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue(); httpServletResponse.setStatus(HttpServletResponse.SC_OK); intProxyResponseCode = HttpServletResponse.SC_OK; httpServletResponse.setHeader(STRING_LOCATION_HEADER, gz); } else { final byte[] bytes = ungzip(httpMethodProxyRequest.getResponseBody()); length = bytes.length; response = new ByteArrayInputStream(bytes); } httpServletResponse.setContentLength(length); } // Send the content to the client debug("Received status code: " + intProxyResponseCode, "Response: " + response); //httpServletResponse.getWriter().write(response); copy(response, httpServletResponse.getOutputStream()); }
From source file:axiom.servlet.AbstractServletClient.java
/** * Forward the request to a static file. The file must be reachable via * the context's protectedStatic resource base. *///w ww. j a va2s .c o m void sendForward(HttpServletResponse res, HttpServletRequest req, ResponseTrans axiomres) throws IOException { String forward = axiomres.getForward(); ServletContext cx = getServletConfig().getServletContext(); String path = cx.getRealPath(forward); if (path == null) throw new IOException("Resource " + forward + " not found"); File file = new File(path); // calculate checksom on last modified date and content length. byte[] checksum = getChecksum(file); 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())) { res.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return; } } } int length = (int) file.length(); res.setContentLength(length); res.setContentType(axiomres.getContentType()); InputStream in = cx.getResourceAsStream(forward); if (in == null) throw new IOException("Can't read " + path); try { OutputStream out = res.getOutputStream(); int bufferSize = 4096; byte buffer[] = new byte[bufferSize]; int l; while (length > 0) { if (length < bufferSize) l = in.read(buffer, 0, length); else l = in.read(buffer, 0, bufferSize); if (l == -1) break; length -= l; out.write(buffer, 0, l); } } finally { in.close(); } }
From source file:com.qlkh.client.server.proxy.ProxyServlet.java
/** * Executes the {@link org.apache.commons.httpclient.HttpMethod} passed in and sends the proxy response * back to the client via the given {@link javax.servlet.http.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 java.io.IOException Can be thrown by the {@link org.apache.commons.httpclient.HttpClient}.executeMethod * @throws javax.servlet.ServletException Can be thrown to indicate that another error has occurred */// w w w . j a v a2 s. co m private void executeProxyRequest(HttpMethod httpMethodProxyRequest, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, ServletException { if (httpServletRequest.isSecure()) { Protocol.registerProtocol("https", new Protocol("https", new EasySSLProtocolSocketFactory(), 443)); } // Create a default HttpClient HttpClient httpClient = new HttpClient(); httpMethodProxyRequest.setFollowRedirects(false); // Execute the request int intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest); InputStream response = httpMethodProxyRequest.getResponseBodyAsStream(); // 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("Received 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(); if (followRedirects) { if (stringLocation.contains("jsessionid")) { Cookie cookie = new Cookie("JSESSIONID", stringLocation.substring(stringLocation.indexOf("jsessionid=") + 11)); cookie.setPath("/"); httpServletResponse.addCookie(cookie); //debug("redirecting: set jessionid (" + cookie.getValue() + ") cookie from URL"); } else if (httpMethodProxyRequest.getResponseHeader("Set-Cookie") != null) { Header header = httpMethodProxyRequest.getResponseHeader("Set-Cookie"); String[] cookieDetails = header.getValue().split(";"); String[] nameValue = cookieDetails[0].split("="); Cookie cookie = new Cookie(nameValue[0], nameValue[1]); cookie.setPath("/"); //debug("redirecting: setting cookie: " + cookie.getName() + ":" + cookie.getValue() + " on " + cookie.getPath()); httpServletResponse.addCookie(cookie); } 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) { if (header.getName().equals("Transfer-Encoding") && header.getValue().equals("chunked") || header.getName().equals("Content-Encoding") && header.getValue().equals("gzip") || // don't copy gzip header header.getName().equals("WWW-Authenticate")) { // don't copy WWW-Authenticate header so browser doesn't prompt on failed basic auth // proxy servlet does not support chunked encoding } else { httpServletResponse.setHeader(header.getName(), header.getValue()); } } List<Header> responseHeaders = Arrays.asList(headerArrayResponse); if (isBodyParameterGzipped(responseHeaders)) { debug("GZipped: true"); int length = 0; if (!followRedirects && intProxyResponseCode == HttpServletResponse.SC_MOVED_TEMPORARILY) { String gz = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue(); httpServletResponse.setStatus(HttpServletResponse.SC_OK); intProxyResponseCode = HttpServletResponse.SC_OK; httpServletResponse.setHeader(STRING_LOCATION_HEADER, gz); } else { final byte[] bytes = ungzip(httpMethodProxyRequest.getResponseBody()); length = bytes.length; response = new ByteArrayInputStream(bytes); } httpServletResponse.setContentLength(length); } // Send the content to the client debug("Received status code: " + intProxyResponseCode, "Response: " + response); //httpServletResponse.getWriter().write(response); copy(response, httpServletResponse.getOutputStream()); }
From source file:grails.plugin.cache.web.filter.PageFragmentCachingFilter.java
protected int determineResponseStatus(HttpServletRequest request, PageInfo pageInfo) { int statusCode = pageInfo.getStatusCode(); if (!pageInfo.isModified(request)) { log.debug("Content not modified since {} sending 304", request.getHeader(HttpHeaders.IF_MODIFIED_SINCE)); statusCode = HttpServletResponse.SC_NOT_MODIFIED; } else if (pageInfo.isMatch(request)) { log.debug("Content matches entity tag {} sending 304", request.getHeader(HttpHeaders.IF_NONE_MATCH)); statusCode = HttpServletResponse.SC_NOT_MODIFIED; }/*from w w w . ja va2 s.co m*/ return statusCode; }
From source file:net.yacy.http.servlets.YaCyDefaultServlet.java
protected boolean passConditionalHeaders(HttpServletRequest request, HttpServletResponse response, Resource resource) throws IOException { try {/* w ww.ja va 2 s . c om*/ if (!request.getMethod().equals(HttpMethod.HEAD.asString())) { String ifms = request.getHeader(HttpHeader.IF_MODIFIED_SINCE.asString()); if (ifms != null) { long ifmsl = request.getDateHeader(HttpHeader.IF_MODIFIED_SINCE.asString()); if (ifmsl != -1) { if (resource.lastModified() / 1000 <= ifmsl / 1000) { response.reset(); response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); response.flushBuffer(); return false; } } } // Parse the if[un]modified dates and compare to resource long date = request.getDateHeader(HttpHeader.IF_UNMODIFIED_SINCE.asString()); if (date != -1) { if (resource.lastModified() / 1000 > date / 1000) { response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); return false; } } } } catch (IllegalArgumentException iae) { if (!response.isCommitted()) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, iae.getMessage()); return false; } throw iae; } return true; }
From source file:com.ibm.jaggr.core.impl.AbstractAggregatorImpl.java
protected void processAggregatorRequest(HttpServletRequest req, HttpServletResponse resp) { final String sourceMethod = "processAggregatorRequest"; //$NON-NLS-1$ boolean isTraceLogging = log.isLoggable(Level.FINER); if (isTraceLogging) { log.entering(AbstractAggregatorImpl.class.getName(), sourceMethod, new Object[] { req, resp }); }/*w w w. ja va 2 s . c o m*/ req.setAttribute(AGGREGATOR_REQATTRNAME, this); ConcurrentMap<String, Object> concurrentMap = new ConcurrentHashMap<String, Object>(); req.setAttribute(CONCURRENTMAP_REQATTRNAME, concurrentMap); try { // Validate config last-modified if development mode is enabled if (getOptions().isDevelopmentMode()) { long lastModified = -1; URI configUri = getConfig().getConfigUri(); if (configUri != null) { try { // try to get platform URI from IResource in case uri specifies // aggregator specific scheme like namedbundleresource configUri = newResource(configUri).getURI(); } catch (UnsupportedOperationException e) { // Not fatal. Just use uri as specified. } lastModified = configUri.toURL().openConnection().getLastModified(); } if (lastModified > getConfig().lastModified()) { if (reloadConfig()) { // If the config has been modified, then dependencies will be revalidated // asynchronously. Rather than forcing the current request to wait, return // a response that will display an alert informing the user of what is // happening and asking them to reload the page. String content = "alert('" + //$NON-NLS-1$ StringUtil.escapeForJavaScript(Messages.ConfigModified) + "');"; //$NON-NLS-1$ resp.addHeader("Cache-control", "no-store"); //$NON-NLS-1$ //$NON-NLS-2$ CopyUtil.copy(new StringReader(content), resp.getOutputStream()); return; } } } getTransport().decorateRequest(req); notifyRequestListeners(RequestNotifierAction.start, req, resp); ILayer layer = getLayer(req); long modifiedSince = req.getDateHeader("If-Modified-Since"); //$NON-NLS-1$ long lastModified = (Math.max(getCacheManager().getCache().getCreated(), layer.getLastModified(req)) / 1000) * 1000; if (modifiedSince >= lastModified) { if (log.isLoggable(Level.FINER)) { log.finer("Returning Not Modified response for layer in servlet" + //$NON-NLS-1$ getName() + ":" //$NON-NLS-1$ + req.getAttribute(IHttpTransport.REQUESTEDMODULENAMES_REQATTRNAME).toString()); } resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED); } else { // Get the InputStream for the response. This call sets the Content-Type, // Content-Length and Content-Encoding headers in the response. InputStream in = layer.getInputStream(req, resp); // if any of the readers included an error response, then don't cache the layer. if (req.getAttribute(ILayer.NOCACHE_RESPONSE_REQATTRNAME) != null) { resp.addHeader("Cache-Control", "no-store"); //$NON-NLS-1$ //$NON-NLS-2$ } else { resp.setDateHeader("Last-Modified", lastModified); //$NON-NLS-1$ int expires = getConfig().getExpires(); resp.addHeader("Cache-Control", //$NON-NLS-1$ "public" + (expires > 0 ? (", max-age=" + expires) : "") //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ ); } CopyUtil.copy(in, resp.getOutputStream()); } notifyRequestListeners(RequestNotifierAction.end, req, resp); } catch (DependencyVerificationException e) { // clear the cache now even though it will be cleared when validateDeps has // finished (asynchronously) so that any new requests will be forced to wait // until dependencies have been validated. getCacheManager().clearCache(); getDependencies().validateDeps(false); resp.addHeader("Cache-control", "no-store"); //$NON-NLS-1$ //$NON-NLS-2$ if (getOptions().isDevelopmentMode()) { String msg = StringUtil.escapeForJavaScript(MessageFormat.format(Messages.DepVerificationFailed, new Object[] { e.getMessage(), "aggregator " + //$NON-NLS-1$ "validatedeps " + //$NON-NLS-1$ getName() + " clean", //$NON-NLS-1$ getWorkingDirectory().toString().replace("\\", "\\\\") //$NON-NLS-1$ //$NON-NLS-2$ })); String content = "alert('" + msg + "');"; //$NON-NLS-1$ //$NON-NLS-2$ try { CopyUtil.copy(new StringReader(content), resp.getOutputStream()); } catch (IOException e1) { if (log.isLoggable(Level.SEVERE)) { log.log(Level.SEVERE, e1.getMessage(), e1); } resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } } else { resp.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } } catch (ProcessingDependenciesException e) { resp.addHeader("Cache-control", "no-store"); //$NON-NLS-1$ //$NON-NLS-2$ if (getOptions().isDevelopmentMode()) { String content = "alert('" + StringUtil.escapeForJavaScript(Messages.Busy) + "');"; //$NON-NLS-1$ //$NON-NLS-2$ try { CopyUtil.copy(new StringReader(content), resp.getOutputStream()); } catch (IOException e1) { if (log.isLoggable(Level.SEVERE)) { log.log(Level.SEVERE, e1.getMessage(), e1); } resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } } else { resp.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } } catch (BadRequestException e) { exceptionResponse(req, resp, e, HttpServletResponse.SC_BAD_REQUEST); } catch (NotFoundException e) { exceptionResponse(req, resp, e, HttpServletResponse.SC_NOT_FOUND); } catch (Exception e) { exceptionResponse(req, resp, e, HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } finally { concurrentMap.clear(); } if (isTraceLogging) { log.exiting(AbstractAggregatorImpl.class.getName(), sourceMethod); } }
From source file:org.dspace.app.xmlui.cocoon.BitstreamReader.java
/** * Write the actual data out to the response. * * Some implementation notes:/*from w ww .j a v a 2s . c om*/ * * 1) We set a short expiration time just in the hopes of preventing someone * from overloading the server by clicking reload a bunch of times. I * Realize that this is nowhere near 100% effective but it may help in some * cases and shouldn't hurt anything. * * 2) We accept partial downloads, thus if you lose a connection halfway * through most web browser will enable you to resume downloading the * bitstream. */ public void generate() throws IOException, SAXException, ProcessingException { if (this.bitstreamInputStream == null) { return; } // Only allow If-Modified-Since protocol if request is from a spider // since response headers would encourage a browser to cache results // that might change with different authentication. if (isSpider) { // Check for if-modified-since header -- ONLY if not authenticated long modSince = request.getDateHeader("If-Modified-Since"); if (modSince != -1 && item != null && item.getLastModified().getTime() < modSince) { // Item has not been modified since requested date, // hence bitstream has not been, either; return 304 response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return; } } // Only set Last-Modified: header for spiders or anonymous // access, since it might encourage browse to cache the result // which might leave a result only available to authenticated // users in the cache for a response later to anonymous user. try { if (item != null && (isSpider || ContextUtil.obtainContext(request).getCurrentUser() == null)) { // TODO: Currently just borrow the date of the item, since // we don't have last-mod dates for Bitstreams response.setDateHeader("Last-Modified", item.getLastModified().getTime()); } } catch (SQLException e) { throw new ProcessingException(e); } byte[] buffer = new byte[BUFFER_SIZE]; int length = -1; // Only encourage caching if this is not a restricted resource, i.e. // if it is accessed anonymously or is readable by Anonymous: if (isAnonymouslyReadable) { response.setDateHeader("Expires", System.currentTimeMillis() + expires); } // If this is a large bitstream then tell the browser it should treat it as a download. int threshold = ConfigurationManager.getIntProperty("xmlui.content_disposition_threshold"); if (bitstreamSize > threshold && threshold != 0) { String name = bitstreamName; // Try and make the download file name formatted for each browser. try { String agent = request.getHeader("USER-AGENT"); if (agent != null && agent.contains("MSIE")) { name = URLEncoder.encode(name, "UTF8"); } else if (agent != null && agent.contains("Mozilla")) { name = MimeUtility.encodeText(name, "UTF8", "B"); } } catch (UnsupportedEncodingException see) { // do nothing } response.setHeader("Content-Disposition", "attachment;filename=" + '"' + name + '"'); } ByteRange byteRange = null; // Turn off partial downloads, they cause problems // and are only rarely used. Specifically some windows pdf // viewers are incapable of handling this request. You can // uncomment the following lines to turn this feature back on. // response.setHeader("Accept-Ranges", "bytes"); // String ranges = request.getHeader("Range"); // if (ranges != null) // { // try // { // ranges = ranges.substring(ranges.indexOf('=') + 1); // byteRange = new ByteRange(ranges); // } // catch (NumberFormatException e) // { // byteRange = null; // if (response instanceof HttpResponse) // { // // Respond with status 416 (Request range not // // satisfiable) // response.setStatus(416); // } // } // } try { if (byteRange != null) { String entityLength; String entityRange; if (this.bitstreamSize != -1) { entityLength = "" + this.bitstreamSize; entityRange = byteRange.intersection(new ByteRange(0, this.bitstreamSize)).toString(); } else { entityLength = "*"; entityRange = byteRange.toString(); } response.setHeader("Content-Range", entityRange + "/" + entityLength); if (response instanceof HttpResponse) { // Response with status 206 (Partial content) response.setStatus(206); } int pos = 0; int posEnd; while ((length = this.bitstreamInputStream.read(buffer)) > -1) { posEnd = pos + length - 1; ByteRange intersection = byteRange.intersection(new ByteRange(pos, posEnd)); if (intersection != null) { out.write(buffer, (int) intersection.getStart() - pos, (int) intersection.length()); } pos += length; } } else { response.setHeader("Content-Length", String.valueOf(this.bitstreamSize)); while ((length = this.bitstreamInputStream.read(buffer)) > -1) { out.write(buffer, 0, length); } out.flush(); } } finally { try { // Close the bitstream input stream so that we don't leak a file descriptor this.bitstreamInputStream.close(); // Close the output stream as per Cocoon docs: http://cocoon.apache.org/2.2/core-modules/core/2.2/681_1_1.html out.close(); } catch (IOException ioe) { // Closing the stream threw an IOException but do we want this to propagate up to Cocoon? // No point since the user has already got the bitstream contents. log.warn("Caught IO exception when closing a stream: " + ioe.getMessage()); } } }
From source file:org.ireland.jnetty.webapp.ErrorPageManager.java
/** * Handles an error status code.//from w w w .jav a 2 s . com * * @return true if we've forwarded to an error page. */ private boolean handleErrorStatus(CauchoRequest request, CauchoResponse response, int code, String message) throws ServletException, IOException { if (code == HttpServletResponse.SC_OK || code == HttpServletResponse.SC_MOVED_TEMPORARILY || code == HttpServletResponse.SC_NOT_MODIFIED) return false; if (request.getRequestDepth(0) > 16) return false; else if (request.getAttribute(RequestDispatcher.ERROR_REQUEST_URI) != null) { return false; } response.killCache(); String location = getErrorPage(code); if (location == null) location = _defaultLocation; WebApp webApp = getWebApp(); if (webApp == null && _host == null) return false; if (location != null && !location.equals(request.getRequestURI())) { request.setAttribute(RequestDispatcher.ERROR_STATUS_CODE, new Integer(code)); request.setAttribute(RequestDispatcher.ERROR_MESSAGE, message); request.setAttribute(RequestDispatcher.ERROR_REQUEST_URI, request.getRequestURI()); String servletName = getServletName(request); if (servletName != null) request.setAttribute(RequestDispatcher.ERROR_SERVLET_NAME, servletName); try { RequestDispatcher disp = null; // can't use filters because of error pages due to filters // or security. if (webApp != null) disp = webApp.getRequestDispatcher(location); else if (_host != null) disp = _host.getWebAppContainer().getRequestDispatcher(location); // disp.forward(request, this, "GET", false); if (disp != null) { ((RequestDispatcherImpl) disp).error(request, response); } else return false; } catch (Throwable e) { sendServletError(e, request, response); } return true; } return false; }