1 package com.atlassian.plugin.servlet.download.plugin;
2
3 import com.atlassian.plugin.ModuleDescriptor;
4 import com.atlassian.plugin.event.PluginEventListener;
5 import com.atlassian.plugin.event.PluginEventManager;
6 import com.atlassian.plugin.event.events.PluginModuleDisabledEvent;
7 import com.atlassian.plugin.event.events.PluginModuleEnabledEvent;
8 import com.atlassian.plugin.servlet.DownloadException;
9 import com.atlassian.plugin.servlet.DownloadStrategy;
10
11 import java.util.Map;
12 import java.util.concurrent.ConcurrentHashMap;
13
14 import javax.servlet.http.HttpServletRequest;
15 import javax.servlet.http.HttpServletResponse;
16
17 import org.slf4j.Logger;
18 import org.slf4j.LoggerFactory;
19
20
21
22
23
24
25
26
27
28 public class PluggableDownloadStrategy implements DownloadStrategy
29 {
30 private static final Logger log = LoggerFactory.getLogger(PluggableDownloadStrategy.class);
31 private final Map<String, DownloadStrategy> strategies = new ConcurrentHashMap<String, DownloadStrategy>();
32
33 public PluggableDownloadStrategy(final PluginEventManager pluginEventManager)
34 {
35 pluginEventManager.register(this);
36 }
37
38 public boolean matches(final String urlPath)
39 {
40 for (final DownloadStrategy strategy : strategies.values())
41 {
42 if (strategy.matches(urlPath))
43 {
44 if (log.isDebugEnabled())
45 {
46 log.debug("Matched plugin download strategy: " + strategy.getClass().getName());
47 }
48 return true;
49 }
50 }
51 return false;
52 }
53
54 public void serveFile(final HttpServletRequest request, final HttpServletResponse response) throws DownloadException
55 {
56 for (final DownloadStrategy strategy : strategies.values())
57 {
58 if (strategy.matches(request.getRequestURI().toLowerCase()))
59 {
60 strategy.serveFile(request, response);
61 return;
62 }
63 }
64 throw new DownloadException(
65 "Found plugin download strategy during matching but not when trying to serve. Enable debug logging for more information.");
66 }
67
68 public void register(final String key, final DownloadStrategy strategy)
69 {
70 if (strategies.containsKey(key))
71 {
72 log.warn("Replacing existing download strategy with module key: " + key);
73 }
74 strategies.put(key, strategy);
75 }
76
77 public void unregister(final String key)
78 {
79 strategies.remove(key);
80 }
81
82 @PluginEventListener
83 public void pluginModuleEnabled(final PluginModuleEnabledEvent event)
84 {
85 final ModuleDescriptor<?> module = event.getModule();
86 if (!(module instanceof DownloadStrategyModuleDescriptor))
87 {
88 return;
89 }
90
91 register(module.getCompleteKey(), (DownloadStrategy) module.getModule());
92 }
93
94 @PluginEventListener
95 public void pluginModuleDisabled(final PluginModuleDisabledEvent event)
96 {
97 final ModuleDescriptor<?> module = event.getModule();
98 if (!(module instanceof DownloadStrategyModuleDescriptor))
99 {
100 return;
101 }
102
103 unregister(module.getCompleteKey());
104 }
105 }