2 // ========================================================================
3 // Copyright (c) 1995-2014 Mort Bay Consulting Pty. Ltd.
4 // ------------------------------------------------------------------------
5 // All rights reserved. This program and the accompanying materials
6 // are made available under the terms of the Eclipse Public License v1.0
7 // and Apache License v2.0 which accompanies this distribution.
9 // The Eclipse Public License is available at
10 // http://www.eclipse.org/legal/epl-v10.html
12 // The Apache License v2.0 is available at
13 // http://www.opensource.org/licenses/apache2.0.php
15 // You may elect to redistribute this code under either of these licenses.
16 // ========================================================================
19 package org.eclipse.jetty.servlet;
21 import java.io.FileNotFoundException;
22 import java.io.IOException;
23 import java.io.InputStream;
24 import java.io.OutputStream;
25 import java.net.MalformedURLException;
27 import java.nio.ByteBuffer;
28 import java.util.Enumeration;
29 import java.util.List;
31 import javax.servlet.AsyncContext;
32 import javax.servlet.RequestDispatcher;
33 import javax.servlet.ServletContext;
34 import javax.servlet.ServletException;
35 import javax.servlet.UnavailableException;
36 import javax.servlet.http.HttpServlet;
37 import javax.servlet.http.HttpServletRequest;
38 import javax.servlet.http.HttpServletResponse;
40 import org.eclipse.jetty.http.HttpContent;
41 import org.eclipse.jetty.http.HttpField;
42 import org.eclipse.jetty.http.HttpFields;
43 import org.eclipse.jetty.http.HttpGenerator.CachedHttpField;
44 import org.eclipse.jetty.http.HttpHeader;
45 import org.eclipse.jetty.http.HttpMethod;
46 import org.eclipse.jetty.http.MimeTypes;
47 import org.eclipse.jetty.http.PathMap.MappedEntry;
48 import org.eclipse.jetty.io.WriterOutputStream;
49 import org.eclipse.jetty.server.HttpOutput;
50 import org.eclipse.jetty.server.InclusiveByteRange;
51 import org.eclipse.jetty.server.ResourceCache;
52 import org.eclipse.jetty.server.Response;
53 import org.eclipse.jetty.server.handler.ContextHandler;
54 import org.eclipse.jetty.util.BufferUtil;
55 import org.eclipse.jetty.util.Callback;
56 import org.eclipse.jetty.util.IO;
57 import org.eclipse.jetty.util.MultiPartOutputStream;
58 import org.eclipse.jetty.util.QuotedStringTokenizer;
59 import org.eclipse.jetty.util.URIUtil;
60 import org.eclipse.jetty.util.log.Log;
61 import org.eclipse.jetty.util.log.Logger;
62 import org.eclipse.jetty.util.resource.Resource;
63 import org.eclipse.jetty.util.resource.ResourceCollection;
64 import org.eclipse.jetty.util.resource.ResourceFactory;
68 /* ------------------------------------------------------------ */
69 /** The default servlet.
70 * This servlet, normally mapped to /, provides the handling for static
71 * content, OPTION and TRACE methods for the context.
72 * The following initParameters are supported, these can be set either
73 * on the servlet itself or as ServletContext initParameters with a prefix
74 * of org.eclipse.jetty.servlet.Default. :
76 * acceptRanges If true, range requests and responses are
79 * dirAllowed If true, directory listings are returned if no
80 * welcome file is found. Else 403 Forbidden.
82 * welcomeServlets If true, attempt to dispatch to welcome files
83 * that are servlets, but only after no matching static
84 * resources could be found. If false, then a welcome
85 * file must exist on disk. If "exact", then exact
86 * servlet matches are supported without an existing file.
89 * This must be false if you want directory listings,
90 * but have index.jsp in your welcome file list.
92 * redirectWelcome If true, welcome files are redirected rather than
95 * gzip If set to true, then static content will be served as
96 * gzip content encoded if a matching resource is
97 * found ending with ".gz"
99 * resourceBase Set to replace the context resource base
101 * resourceCache If set, this is a context attribute name, which the servlet
102 * will use to look for a shared ResourceCache instance.
104 * relativeResourceBase
105 * Set with a pathname relative to the base of the
106 * servlet context root. Useful for only serving static content out
107 * of only specific subdirectories.
109 * pathInfoOnly If true, only the path info will be applied to the resourceBase
111 * stylesheet Set with the location of an optional stylesheet that will be used
112 * to decorate the directory listing html.
114 * etags If True, weak etags will be generated and handled.
116 * maxCacheSize The maximum total size of the cache or 0 for no cache.
117 * maxCachedFileSize The maximum size of a file to cache
118 * maxCachedFiles The maximum number of files to cache
120 * useFileMappedBuffer
121 * If set to true, it will use mapped file buffer to serve static content
122 * when using NIO connector. Setting this value to false means that
123 * a direct buffer will be used instead of a mapped file buffer.
124 * By default, this is set to true.
126 * cacheControl If set, all static content will have this value set as the cache-control
136 public class DefaultServlet extends HttpServlet implements ResourceFactory
138 private static final Logger LOG = Log.getLogger(DefaultServlet.class);
140 private static final long serialVersionUID = 4930458713846881193L;
142 private static final CachedHttpField ACCEPT_RANGES = new CachedHttpField(HttpHeader.ACCEPT_RANGES, "bytes");
144 private ServletContext _servletContext;
145 private ContextHandler _contextHandler;
147 private boolean _acceptRanges=true;
148 private boolean _dirAllowed=true;
149 private boolean _welcomeServlets=false;
150 private boolean _welcomeExactServlets=false;
151 private boolean _redirectWelcome=false;
152 private boolean _gzip=false;
153 private boolean _pathInfoOnly=false;
154 private boolean _etags=false;
156 private Resource _resourceBase;
157 private ResourceCache _cache;
159 private MimeTypes _mimeTypes;
160 private String[] _welcomes;
161 private Resource _stylesheet;
162 private boolean _useFileMappedBuffer=false;
163 private HttpField _cacheControl;
164 private String _relativeResourceBase;
165 private ServletHandler _servletHandler;
166 private ServletHolder _defaultHolder;
168 /* ------------------------------------------------------------ */
171 throws UnavailableException
173 _servletContext=getServletContext();
174 _contextHandler = initContextHandler(_servletContext);
176 _mimeTypes = _contextHandler.getMimeTypes();
178 _welcomes = _contextHandler.getWelcomeFiles();
180 _welcomes=new String[] {"index.html","index.jsp"};
182 _acceptRanges=getInitBoolean("acceptRanges",_acceptRanges);
183 _dirAllowed=getInitBoolean("dirAllowed",_dirAllowed);
184 _redirectWelcome=getInitBoolean("redirectWelcome",_redirectWelcome);
185 _gzip=getInitBoolean("gzip",_gzip);
186 _pathInfoOnly=getInitBoolean("pathInfoOnly",_pathInfoOnly);
188 if ("exact".equals(getInitParameter("welcomeServlets")))
190 _welcomeExactServlets=true;
191 _welcomeServlets=false;
194 _welcomeServlets=getInitBoolean("welcomeServlets", _welcomeServlets);
196 _useFileMappedBuffer=getInitBoolean("useFileMappedBuffer",_useFileMappedBuffer);
198 _relativeResourceBase = getInitParameter("relativeResourceBase");
200 String rb=getInitParameter("resourceBase");
203 if (_relativeResourceBase!=null)
204 throw new UnavailableException("resourceBase & relativeResourceBase");
205 try{_resourceBase=_contextHandler.newResource(rb);}
208 LOG.warn(Log.EXCEPTION,e);
209 throw new UnavailableException(e.toString());
213 String css=getInitParameter("stylesheet");
218 _stylesheet = Resource.newResource(css);
219 if(!_stylesheet.exists())
225 if(_stylesheet == null)
227 _stylesheet = Resource.newResource(this.getClass().getResource("/jetty-dir.css"));
232 LOG.warn(e.toString());
236 String cc=getInitParameter("cacheControl");
238 _cacheControl=new CachedHttpField(HttpHeader.CACHE_CONTROL, cc);
240 String resourceCache = getInitParameter("resourceCache");
241 int max_cache_size=getInitInt("maxCacheSize", -2);
242 int max_cached_file_size=getInitInt("maxCachedFileSize", -2);
243 int max_cached_files=getInitInt("maxCachedFiles", -2);
244 if (resourceCache!=null)
246 if (max_cache_size!=-1 || max_cached_file_size!= -2 || max_cached_files!=-2)
247 LOG.debug("ignoring resource cache configuration, using resourceCache attribute");
248 if (_relativeResourceBase!=null || _resourceBase!=null)
249 throw new UnavailableException("resourceCache specified with resource bases");
250 _cache=(ResourceCache)_servletContext.getAttribute(resourceCache);
252 LOG.debug("Cache {}={}",resourceCache,_cache);
255 _etags = getInitBoolean("etags",_etags);
259 if (_cache==null && max_cached_files>0)
261 _cache= new ResourceCache(null,this,_mimeTypes,_useFileMappedBuffer,_etags);
263 if (max_cache_size>0)
264 _cache.setMaxCacheSize(max_cache_size);
265 if (max_cached_file_size>=-1)
266 _cache.setMaxCachedFileSize(max_cached_file_size);
267 if (max_cached_files>=-1)
268 _cache.setMaxCachedFiles(max_cached_files);
273 LOG.warn(Log.EXCEPTION,e);
274 throw new UnavailableException(e.toString());
277 _servletHandler= _contextHandler.getChildHandlerByClass(ServletHandler.class);
278 for (ServletHolder h :_servletHandler.getServlets())
279 if (h.getServletInstance()==this)
283 if (LOG.isDebugEnabled())
284 LOG.debug("resource base = "+_resourceBase);
288 * Compute the field _contextHandler.<br/>
289 * In the case where the DefaultServlet is deployed on the HttpService it is likely that
290 * this method needs to be overwritten to unwrap the ServletContext facade until we reach
291 * the original jetty's ContextHandler.
292 * @param servletContext The servletContext of this servlet.
293 * @return the jetty's ContextHandler for this servletContext.
295 protected ContextHandler initContextHandler(ServletContext servletContext)
297 ContextHandler.Context scontext=ContextHandler.getCurrentContext();
300 if (servletContext instanceof ContextHandler.Context)
301 return ((ContextHandler.Context)servletContext).getContextHandler();
303 throw new IllegalArgumentException("The servletContext " + servletContext + " " +
304 servletContext.getClass().getName() + " is not " + ContextHandler.Context.class.getName());
307 return ContextHandler.getCurrentContext().getContextHandler();
310 /* ------------------------------------------------------------ */
312 public String getInitParameter(String name)
314 String value=getServletContext().getInitParameter("org.eclipse.jetty.servlet.Default."+name);
316 value=super.getInitParameter(name);
320 /* ------------------------------------------------------------ */
321 private boolean getInitBoolean(String name, boolean dft)
323 String value=getInitParameter(name);
324 if (value==null || value.length()==0)
326 return (value.startsWith("t")||
327 value.startsWith("T")||
328 value.startsWith("y")||
329 value.startsWith("Y")||
330 value.startsWith("1"));
333 /* ------------------------------------------------------------ */
334 private int getInitInt(String name, int dft)
336 String value=getInitParameter(name);
338 value=getInitParameter(name);
339 if (value!=null && value.length()>0)
340 return Integer.parseInt(value);
344 /* ------------------------------------------------------------ */
345 /** get Resource to serve.
346 * Map a path to a resource. The default implementation calls
347 * HttpContext.getResource but derived servlets may provide
349 * @param pathInContext The path to find a resource for.
350 * @return The resource to serve.
353 public Resource getResource(String pathInContext)
356 if (_relativeResourceBase!=null)
357 pathInContext=URIUtil.addPaths(_relativeResourceBase,pathInContext);
361 if (_resourceBase!=null)
363 r = _resourceBase.addPath(pathInContext);
364 if (!_contextHandler.checkAlias(pathInContext,r))
367 else if (_servletContext instanceof ContextHandler.Context)
369 r = _contextHandler.getResource(pathInContext);
373 URL u = _servletContext.getResource(pathInContext);
374 r = _contextHandler.newResource(u);
377 if (LOG.isDebugEnabled())
378 LOG.debug("Resource "+pathInContext+"="+r);
380 catch (IOException e)
385 if((r==null || !r.exists()) && pathInContext.endsWith("/jetty-dir.css"))
391 /* ------------------------------------------------------------ */
393 protected void doGet(HttpServletRequest request, HttpServletResponse response)
394 throws ServletException, IOException
396 String servletPath=null;
397 String pathInfo=null;
398 Enumeration<String> reqRanges = null;
399 Boolean included =request.getAttribute(RequestDispatcher.INCLUDE_REQUEST_URI)!=null;
400 if (included!=null && included.booleanValue())
402 servletPath=(String)request.getAttribute(RequestDispatcher.INCLUDE_SERVLET_PATH);
403 pathInfo=(String)request.getAttribute(RequestDispatcher.INCLUDE_PATH_INFO);
404 if (servletPath==null)
406 servletPath=request.getServletPath();
407 pathInfo=request.getPathInfo();
412 included = Boolean.FALSE;
413 servletPath = _pathInfoOnly?"/":request.getServletPath();
414 pathInfo = request.getPathInfo();
416 // Is this a Range request?
417 reqRanges = request.getHeaders(HttpHeader.RANGE.asString());
418 if (!hasDefinedRange(reqRanges))
422 String pathInContext=URIUtil.addPaths(servletPath,pathInfo);
423 boolean endsWithSlash=(pathInfo==null?request.getServletPath():pathInfo).endsWith(URIUtil.SLASH);
426 // Find the resource and content
427 Resource resource=null;
428 HttpContent content=null;
432 String pathInContextGz=null;
434 if (!included.booleanValue() && _gzip && reqRanges==null && !endsWithSlash )
436 // Look for a gzip resource
437 pathInContextGz=pathInContext+".gz";
439 resource=getResource(pathInContextGz);
442 content=_cache.lookup(pathInContextGz);
443 resource=(content==null)?null:content.getResource();
446 // Does a gzip resource exist?
447 if (resource!=null && resource.exists() && !resource.isDirectory())
449 // Tell caches that response may vary by accept-encoding
450 response.addHeader(HttpHeader.VARY.asString(),HttpHeader.ACCEPT_ENCODING.asString());
452 // Does the client accept gzip?
453 String accept=request.getHeader(HttpHeader.ACCEPT_ENCODING.asString());
454 if (accept!=null && accept.indexOf("gzip")>=0)
463 resource=getResource(pathInContext);
466 content=_cache.lookup(pathInContext);
467 resource=content==null?null:content.getResource();
471 if (LOG.isDebugEnabled())
472 LOG.debug("uri="+request.getRequestURI()+" resource="+resource+(content!=null?" content":""));
475 if (resource==null || !resource.exists())
478 throw new FileNotFoundException("!" + pathInContext);
479 response.sendError(HttpServletResponse.SC_NOT_FOUND);
481 else if (!resource.isDirectory())
483 if (endsWithSlash && pathInContext.length()>1)
485 String q=request.getQueryString();
486 pathInContext=pathInContext.substring(0,pathInContext.length()-1);
487 if (q!=null&&q.length()!=0)
488 pathInContext+="?"+q;
489 response.sendRedirect(response.encodeRedirectURL(URIUtil.addPaths(_servletContext.getContextPath(),pathInContext)));
493 // ensure we have content
495 content=new HttpContent.ResourceAsHttpContent(resource,_mimeTypes.getMimeByExtension(resource.toString()),response.getBufferSize(),_etags);
497 if (included.booleanValue() || passConditionalHeaders(request,response, resource,content))
501 response.setHeader(HttpHeader.CONTENT_ENCODING.asString(),"gzip");
502 String mt=_servletContext.getMimeType(pathInContext);
504 response.setContentType(mt);
506 sendData(request,response,included.booleanValue(),resource,content,reqRanges);
514 if (!endsWithSlash || (pathInContext.length()==1 && request.getAttribute("org.eclipse.jetty.server.nullPathInfo")!=null))
516 StringBuffer buf=request.getRequestURL();
519 int param=buf.lastIndexOf(";");
523 buf.insert(param,'/');
524 String q=request.getQueryString();
525 if (q!=null&&q.length()!=0)
530 response.setContentLength(0);
531 response.sendRedirect(response.encodeRedirectURL(buf.toString()));
534 // else look for a welcome file
535 else if (null!=(welcome=getWelcomeFile(pathInContext)))
537 LOG.debug("welcome={}",welcome);
538 if (_redirectWelcome)
540 // Redirect to the index
541 response.setContentLength(0);
542 String q=request.getQueryString();
543 if (q!=null&&q.length()!=0)
544 response.sendRedirect(response.encodeRedirectURL(URIUtil.addPaths( _servletContext.getContextPath(),welcome)+"?"+q));
546 response.sendRedirect(response.encodeRedirectURL(URIUtil.addPaths( _servletContext.getContextPath(),welcome)));
550 // Forward to the index
551 RequestDispatcher dispatcher=request.getRequestDispatcher(welcome);
552 if (dispatcher!=null)
554 if (included.booleanValue())
555 dispatcher.include(request,response);
558 request.setAttribute("org.eclipse.jetty.server.welcome",welcome);
559 dispatcher.forward(request,response);
566 content=new HttpContent.ResourceAsHttpContent(resource,_mimeTypes.getMimeByExtension(resource.toString()),_etags);
567 if (included.booleanValue() || passConditionalHeaders(request,response, resource,content))
568 sendDirectory(request,response,resource,pathInContext);
572 catch(IllegalArgumentException e)
574 LOG.warn(Log.EXCEPTION,e);
575 if(!response.isCommitted())
576 response.sendError(500, e.getMessage());
582 else if (resource!=null)
588 /* ------------------------------------------------------------ */
589 private boolean hasDefinedRange(Enumeration<String> reqRanges)
591 return (reqRanges!=null && reqRanges.hasMoreElements());
594 /* ------------------------------------------------------------ */
596 protected void doPost(HttpServletRequest request, HttpServletResponse response)
597 throws ServletException, IOException
599 doGet(request,response);
602 /* ------------------------------------------------------------ */
604 * @see javax.servlet.http.HttpServlet#doTrace(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
607 protected void doTrace(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
609 resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
612 /* ------------------------------------------------------------ */
614 protected void doOptions(HttpServletRequest req, HttpServletResponse resp)
615 throws ServletException, IOException
617 resp.setHeader("Allow", "GET,HEAD,POST,OPTIONS");
620 /* ------------------------------------------------------------ */
622 * Finds a matching welcome file for the supplied {@link Resource}. This will be the first entry in the list of
623 * configured {@link #_welcomes welcome files} that existing within the directory referenced by the <code>Resource</code>.
624 * If the resource is not a directory, or no matching file is found, then it may look for a valid servlet mapping.
625 * If there is none, then <code>null</code> is returned.
626 * The list of welcome files is read from the {@link ContextHandler} for this servlet, or
627 * <code>"index.jsp" , "index.html"</code> if that is <code>null</code>.
629 * @return The path of the matching welcome file in context or null.
630 * @throws IOException
631 * @throws MalformedURLException
633 private String getWelcomeFile(String pathInContext) throws MalformedURLException, IOException
638 String welcome_servlet=null;
639 for (int i=0;i<_welcomes.length;i++)
641 String welcome_in_context=URIUtil.addPaths(pathInContext,_welcomes[i]);
642 Resource welcome=getResource(welcome_in_context);
643 if (welcome!=null && welcome.exists())
646 if ((_welcomeServlets || _welcomeExactServlets) && welcome_servlet==null)
648 MappedEntry<?> entry=_servletHandler.getHolderEntry(welcome_in_context);
649 if (entry!=null && entry.getValue()!=_defaultHolder &&
650 (_welcomeServlets || (_welcomeExactServlets && entry.getKey().equals(welcome_in_context))))
651 welcome_servlet=welcome_in_context;
655 return welcome_servlet;
658 /* ------------------------------------------------------------ */
659 /* Check modification date headers.
661 protected boolean passConditionalHeaders(HttpServletRequest request,HttpServletResponse response, Resource resource, HttpContent content)
666 if (!HttpMethod.HEAD.is(request.getMethod()))
670 String ifm=request.getHeader(HttpHeader.IF_MATCH.asString());
674 if (content.getETag()!=null)
676 QuotedStringTokenizer quoted = new QuotedStringTokenizer(ifm,", ",false,true);
677 while (!match && quoted.hasMoreTokens())
679 String tag = quoted.nextToken();
680 if (content.getETag().equals(tag))
687 response.setStatus(HttpServletResponse.SC_PRECONDITION_FAILED);
692 String if_non_match_etag=request.getHeader(HttpHeader.IF_NONE_MATCH.asString());
693 if (if_non_match_etag!=null && content.getETag()!=null)
695 // Look for GzipFiltered version of etag
696 if (content.getETag().equals(request.getAttribute("o.e.j.s.GzipFilter.ETag")))
698 response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
699 response.setHeader(HttpHeader.ETAG.asString(),if_non_match_etag);
703 // Handle special case of exact match.
704 if (content.getETag().equals(if_non_match_etag))
706 response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
707 response.setHeader(HttpHeader.ETAG.asString(),content.getETag());
711 // Handle list of tags
712 QuotedStringTokenizer quoted = new QuotedStringTokenizer(if_non_match_etag,", ",false,true);
713 while (quoted.hasMoreTokens())
715 String tag = quoted.nextToken();
716 if (content.getETag().equals(tag))
718 response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
719 response.setHeader(HttpHeader.ETAG.asString(),content.getETag());
724 // If etag requires content to be served, then do not check if-modified-since
729 // Handle if modified since
730 String ifms=request.getHeader(HttpHeader.IF_MODIFIED_SINCE.asString());
733 //Get jetty's Response impl
734 String mdlm=content.getLastModified();
735 if (mdlm!=null && ifms.equals(mdlm))
737 response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
739 response.setHeader(HttpHeader.ETAG.asString(),content.getETag());
740 response.flushBuffer();
744 long ifmsl=request.getDateHeader(HttpHeader.IF_MODIFIED_SINCE.asString());
745 if (ifmsl!=-1 && resource.lastModified()/1000 <= ifmsl/1000)
747 response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
749 response.setHeader(HttpHeader.ETAG.asString(),content.getETag());
750 response.flushBuffer();
755 // Parse the if[un]modified dates and compare to resource
756 long date=request.getDateHeader(HttpHeader.IF_UNMODIFIED_SINCE.asString());
757 if (date!=-1 && resource.lastModified()/1000 > date/1000)
759 response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
765 catch(IllegalArgumentException iae)
767 if(!response.isCommitted())
768 response.sendError(400, iae.getMessage());
775 /* ------------------------------------------------------------------- */
776 protected void sendDirectory(HttpServletRequest request,
777 HttpServletResponse response,
779 String pathInContext)
784 response.sendError(HttpServletResponse.SC_FORBIDDEN);
789 String base = URIUtil.addPaths(request.getRequestURI(),URIUtil.SLASH);
791 //If the DefaultServlet has a resource base set, use it
792 if (_resourceBase != null)
794 // handle ResourceCollection
795 if (_resourceBase instanceof ResourceCollection)
796 resource=_resourceBase.addPath(pathInContext);
798 //Otherwise, try using the resource base of its enclosing context handler
799 else if (_contextHandler.getBaseResource() instanceof ResourceCollection)
800 resource=_contextHandler.getBaseResource().addPath(pathInContext);
802 String dir = resource.getListHTML(base,pathInContext.length()>1);
805 response.sendError(HttpServletResponse.SC_FORBIDDEN,
810 data=dir.getBytes("UTF-8");
811 response.setContentType("text/html; charset=UTF-8");
812 response.setContentLength(data.length);
813 response.getOutputStream().write(data);
816 /* ------------------------------------------------------------ */
817 protected void sendData(HttpServletRequest request,
818 HttpServletResponse response,
822 Enumeration<String> reqRanges)
825 final long content_length = (content==null)?resource.length():content.getContentLength();
827 // Get the output stream (or writer)
828 OutputStream out =null;
832 out = response.getOutputStream();
834 // has a filter already written to the response?
835 written = out instanceof HttpOutput
836 ? ((HttpOutput)out).isWritten()
839 catch(IllegalStateException e)
841 out = new WriterOutputStream(response.getWriter());
842 written=true; // there may be data in writer buffer, so assume written
845 if ( reqRanges == null || !reqRanges.hasMoreElements() || content_length<0)
847 // if there were no ranges, send entire entity
850 resource.writeTo(out,0,content_length);
852 // else if we can't do a bypass write because of wrapping
853 else if (content==null || written || !(out instanceof HttpOutput))
856 writeHeaders(response,content,written?-1:content_length);
857 ByteBuffer buffer = (content==null)?null:content.getIndirectBuffer();
859 BufferUtil.writeTo(buffer,out);
861 resource.writeTo(out,0,content_length);
863 // else do a bypass write
867 if (response instanceof Response)
869 Response r = (Response)response;
870 writeOptionHeaders(r.getHttpFields());
871 r.setHeaders(content);
874 writeHeaders(response,content,content_length);
876 // write the content asynchronously if supported
877 if (request.isAsyncSupported())
879 final AsyncContext context = request.startAsync();
881 ((HttpOutput)out).sendContent(content,new Callback()
884 public void succeeded()
890 public void failed(Throwable x)
892 if (x instanceof IOException)
900 // otherwise write content blocking
903 ((HttpOutput)out).sendContent(content);
909 // Parse the satisfiable ranges
910 List<InclusiveByteRange> ranges =InclusiveByteRange.satisfiableRanges(reqRanges,content_length);
912 // if there are no satisfiable ranges, send 416 response
913 if (ranges==null || ranges.size()==0)
915 writeHeaders(response, content, content_length);
916 response.setStatus(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
917 response.setHeader(HttpHeader.CONTENT_RANGE.asString(),
918 InclusiveByteRange.to416HeaderRangeString(content_length));
919 resource.writeTo(out,0,content_length);
923 // if there is only a single valid range (must be satisfiable
924 // since were here now), send that range with a 216 response
925 if ( ranges.size()== 1)
927 InclusiveByteRange singleSatisfiableRange = ranges.get(0);
928 long singleLength = singleSatisfiableRange.getSize(content_length);
929 writeHeaders(response,content,singleLength );
930 response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
931 if (!response.containsHeader(HttpHeader.DATE.asString()))
932 response.addDateHeader(HttpHeader.DATE.asString(),System.currentTimeMillis());
933 response.setHeader(HttpHeader.CONTENT_RANGE.asString(),
934 singleSatisfiableRange.toHeaderRangeString(content_length));
935 resource.writeTo(out,singleSatisfiableRange.getFirst(content_length),singleLength);
939 // multiple non-overlapping valid ranges cause a multipart
940 // 216 response which does not require an overall
941 // content-length header
943 writeHeaders(response,content,-1);
944 String mimetype=(content==null?null:content.getContentType());
946 LOG.warn("Unknown mimetype for "+request.getRequestURI());
947 MultiPartOutputStream multi = new MultiPartOutputStream(out);
948 response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
949 if (!response.containsHeader(HttpHeader.DATE.asString()))
950 response.addDateHeader(HttpHeader.DATE.asString(),System.currentTimeMillis());
952 // If the request has a "Request-Range" header then we need to
953 // send an old style multipart/x-byteranges Content-Type. This
954 // keeps Netscape and acrobat happy. This is what Apache does.
956 if (request.getHeader(HttpHeader.REQUEST_RANGE.asString())!=null)
957 ctp = "multipart/x-byteranges; boundary=";
959 ctp = "multipart/byteranges; boundary=";
960 response.setContentType(ctp+multi.getBoundary());
962 InputStream in=resource.getInputStream();
965 // calculate the content-length
967 String[] header = new String[ranges.size()];
968 for (int i=0;i<ranges.size();i++)
970 InclusiveByteRange ibr = ranges.get(i);
971 header[i]=ibr.toHeaderRangeString(content_length);
974 2+multi.getBoundary().length()+2+
975 (mimetype==null?0:HttpHeader.CONTENT_TYPE.asString().length()+2+mimetype.length())+2+
976 HttpHeader.CONTENT_RANGE.asString().length()+2+header[i].length()+2+
978 (ibr.getLast(content_length)-ibr.getFirst(content_length))+1;
980 length+=2+2+multi.getBoundary().length()+2+2;
981 response.setContentLength(length);
983 for (int i=0;i<ranges.size();i++)
985 InclusiveByteRange ibr = ranges.get(i);
986 multi.startPart(mimetype,new String[]{HttpHeader.CONTENT_RANGE+": "+header[i]});
988 long start=ibr.getFirst(content_length);
989 long size=ibr.getSize(content_length);
992 // Handle non cached resource
996 in=resource.getInputStream();
1005 IO.copy(in,multi,size);
1009 // Handle cached resource
1010 (resource).writeTo(multi,start,size);
1019 /* ------------------------------------------------------------ */
1020 protected void writeHeaders(HttpServletResponse response,HttpContent content,long count)
1022 if (content.getContentType()!=null && response.getContentType()==null)
1023 response.setContentType(content.getContentType().toString());
1025 if (response instanceof Response)
1027 Response r=(Response)response;
1028 HttpFields fields = r.getHttpFields();
1030 if (content.getLastModified()!=null)
1031 fields.put(HttpHeader.LAST_MODIFIED,content.getLastModified());
1032 else if (content.getResource()!=null)
1034 long lml=content.getResource().lastModified();
1036 fields.putDateField(HttpHeader.LAST_MODIFIED,lml);
1040 r.setLongContentLength(count);
1042 writeOptionHeaders(fields);
1045 fields.put(HttpHeader.ETAG,content.getETag());
1049 long lml=content.getResource().lastModified();
1051 response.setDateHeader(HttpHeader.LAST_MODIFIED.asString(),lml);
1055 if (count<Integer.MAX_VALUE)
1056 response.setContentLength((int)count);
1058 response.setHeader(HttpHeader.CONTENT_LENGTH.asString(),Long.toString(count));
1061 writeOptionHeaders(response);
1064 response.setHeader(HttpHeader.ETAG.asString(),content.getETag());
1068 /* ------------------------------------------------------------ */
1069 protected void writeOptionHeaders(HttpFields fields)
1072 fields.put(ACCEPT_RANGES);
1074 if (_cacheControl!=null)
1075 fields.put(_cacheControl);
1078 /* ------------------------------------------------------------ */
1079 protected void writeOptionHeaders(HttpServletResponse response)
1082 response.setHeader(HttpHeader.ACCEPT_RANGES.asString(),"bytes");
1084 if (_cacheControl!=null)
1085 response.setHeader(HttpHeader.CACHE_CONTROL.asString(),_cacheControl.getValue());
1088 /* ------------------------------------------------------------ */
1090 * @see javax.servlet.Servlet#destroy()
1093 public void destroy()
1096 _cache.flushCache();