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