View Javadoc

1   package com.atlassian.plugin.servlet;
2   
3   import org.apache.commons.logging.Log;
4   import org.apache.commons.logging.LogFactory;
5   
6   import javax.servlet.http.HttpServlet;
7   import javax.servlet.http.HttpServletRequest;
8   import javax.servlet.http.HttpServletResponse;
9   import java.io.IOException;
10  import java.util.List;
11  
12  public abstract class AbstractFileServerServlet extends HttpServlet
13  {
14      public static final String PATH_SEPARATOR = "/";
15      public static final String RESOURCE_URL_PREFIX = "resources";
16      public static final String SERVLET_PATH = "download";
17      private static final Log log = LogFactory.getLog(AbstractFileServerServlet.class);
18  
19      protected final void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException
20      {
21          DownloadStrategy downloadStrategy = getDownloadStrategy(httpServletRequest);
22          if (downloadStrategy == null)
23          {
24              httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND, "The file you were looking for was not found");
25              return;
26          }
27  
28          try
29          {
30              downloadStrategy.serveFile(httpServletRequest, httpServletResponse);
31          }
32          catch (DownloadException e)
33          {
34              log.error("Error while serving file for request:" + httpServletRequest.getRequestURI(), e);
35              if (!httpServletResponse.isCommitted())
36              {
37                  httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error while serving file");
38              }
39          }
40      }
41  
42      /**
43       * Returns a list of {@link DownloadStrategy} objects in the order that they will be matched against.
44       * The list returned should be cached as this method is called for every request.
45       */
46      protected abstract List<DownloadStrategy> getDownloadStrategies();
47  
48      private DownloadStrategy getDownloadStrategy(HttpServletRequest httpServletRequest)
49      {
50          String url = httpServletRequest.getRequestURI().toLowerCase();
51          for (DownloadStrategy downloadStrategy : getDownloadStrategies())
52          {
53              if (downloadStrategy.matches(url))
54              {
55                  return downloadStrategy;
56              }
57          }
58          return null;
59      }
60  }