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", e);
35              httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error while serving file");
36          }
37      }
38  
39      /**
40       * Returns a list of {@link DownloadStrategy} objects in the order that they will be matched against.
41       * The list returned should be cached as this method is called for every request.
42       */
43      protected abstract List<DownloadStrategy> getDownloadStrategies();
44  
45      private DownloadStrategy getDownloadStrategy(HttpServletRequest httpServletRequest)
46      {
47          String url = httpServletRequest.getRequestURI().toLowerCase();
48          for (DownloadStrategy downloadStrategy : getDownloadStrategies())
49          {
50              if (downloadStrategy.matches(url))
51              {
52                  return downloadStrategy;
53              }
54          }
55          return null;
56      }
57  }