View Javadoc

1   package com.atlassian.plugin.webresource;
2   
3   import static com.atlassian.plugin.webresource.ContextBatchPluginResource.URL_PREFIX;
4   
5   import com.atlassian.plugin.servlet.DownloadableResource;
6   
7   import java.util.HashSet;
8   import java.util.LinkedHashSet;
9   import java.util.Map;
10  import java.util.Set;
11  import java.util.regex.Matcher;
12  import java.util.regex.Pattern;
13  
14  /**
15   * Provides a fallback to serve resources relative to a context batch resource
16   * In practice, the resources url should be transformed via the
17   * {{com.atlassian.plugin.webresource.RelativeURLTransformResource}}.
18   * This builder is in place in case this does not happen
19   * @since 2.9.0
20   */
21  public class ContextBatchSubResourceBuilder implements DownloadableResourceBuilder
22  {
23      public static final Pattern CONTEXT_BATCH_PATTERN = Pattern.compile(URL_PREFIX + "\\w*/([^/]*)/(?!batch\\.js)(.*)$");
24  
25      private final ResourceDependencyResolver dependencyResolver;
26      private final DownloadableResourceFinder resourceFinder;
27  
28      public ContextBatchSubResourceBuilder(final ResourceDependencyResolver dependencyResolver, final DownloadableResourceFinder resourceFinder)
29      {
30          this.dependencyResolver = dependencyResolver;
31          this.resourceFinder = resourceFinder;
32      }
33  
34      public boolean matches(final String path)
35      {
36          return CONTEXT_BATCH_PATTERN.matcher(path).find();
37      }
38  
39      public DownloadableResource parse(final String path, final Map<String, String> params) throws UrlParseException
40      {
41          final Matcher m = CONTEXT_BATCH_PATTERN.matcher(path);
42          if (!m.find())
43          {
44              throw new UrlParseException("Context batch url could not be parsed.");
45          }
46  
47          final String key = m.group(1);
48          final String resourceName = m.group(2);
49  
50          final LinkedHashSet<String> includedContexts = new LinkedHashSet<String>();
51          final Set<String> excludedContexts = new HashSet<String>();
52  
53          ContextBatchOperations.parseContexts(key, includedContexts, excludedContexts);
54          
55          for (final String context : includedContexts)
56          {
57              for (final WebResourceModuleDescriptor moduleDescriptor : dependencyResolver.getDependenciesInContext(context))
58              {
59                  final DownloadableResource resource = resourceFinder.find(moduleDescriptor.getCompleteKey(), resourceName);
60                  if (resource != null)
61                  {
62                      return resource;
63                  }
64              }
65          }
66          return null; // 404 not found
67      }
68  }