1 package com.atlassian.plugin.servlet;
2
3
4 import org.slf4j.Logger;
5 import org.slf4j.LoggerFactory;
6
7 import java.io.IOException;
8 import java.util.List;
9
10 import javax.servlet.http.HttpServlet;
11 import javax.servlet.http.HttpServletRequest;
12 import javax.servlet.http.HttpServletResponse;
13
14 public abstract class AbstractFileServerServlet extends HttpServlet
15 {
16 public static final String PATH_SEPARATOR = "/";
17 public static final String RESOURCE_URL_PREFIX = "resources";
18 public static final String SERVLET_PATH = "download";
19 private static final Logger log = LoggerFactory.getLogger(AbstractFileServerServlet.class);
20
21 @Override
22 protected final void doGet(final HttpServletRequest httpServletRequest, final HttpServletResponse httpServletResponse) throws IOException
23 {
24 final DownloadStrategy downloadStrategy = getDownloadStrategy(httpServletRequest);
25 if (downloadStrategy == null)
26 {
27 httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND, "The file you were looking for was not found");
28 return;
29 }
30
31 try
32 {
33 downloadStrategy.serveFile(httpServletRequest, httpServletResponse);
34 }
35 catch (final DownloadException e)
36 {
37 log.debug("Error while serving file for request:" + httpServletRequest.getRequestURI(), e);
38 if (!httpServletResponse.isCommitted())
39 {
40 httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error while serving file");
41 }
42 }
43 }
44
45
46
47
48
49 protected abstract List<DownloadStrategy> getDownloadStrategies();
50
51 private DownloadStrategy getDownloadStrategy(final HttpServletRequest httpServletRequest)
52 {
53 final String url = httpServletRequest.getRequestURI();
54 DownloadStrategy strategy = findStrategy(url);
55
56 if(strategy==null){
57 strategy = findStrategy(url.toLowerCase());
58 }
59
60 return strategy;
61 }
62
63 private DownloadStrategy findStrategy(String url){
64 for (final DownloadStrategy downloadStrategy : getDownloadStrategies())
65 {
66 if (downloadStrategy.matches(url))
67 {
68 return downloadStrategy;
69 }
70 }
71 return null;
72 }
73 }