1 package com.atlassian.plugin.servlet;
2
3 /**
4 * Parses resource download URLs for a plugin resource download strategy, and can determine whether a given URL is valid
5 * for that download strategy.
6 * <p/>
7 * The URLs are in the form "/servletPath/strategyPrefix/moduleCompleteKey/resourceName", where the 'servletPath' is
8 * defined as {@link BaseFileServerServlet#SERVLET_PATH}, the 'strategyPrefix' is defined by a constructor parameter,
9 * the remainder is parsed by this parser into a {@link PluginResource}.
10 */
11 public class ResourceUrlParser
12 {
13 private final String strategyPrefix;
14
15 /**
16 * Create a parser with the given strategy prefix for parsing URLs.
17 * <p/>
18 * For example, a strategy prefix of 'resources' means that this parser will match URLs which include
19 * 'download/resources'. (Where 'download' is defined as {@link BaseFileServerServlet#SERVLET_PATH}.)
20 *
21 * @param strategyPrefix a String which will be found following 'download' at the start of matching URLs.
22 */
23 public ResourceUrlParser(String strategyPrefix)
24 {
25 this.strategyPrefix = strategyPrefix;
26 }
27
28 /**
29 * Parses resource download URLs for this plugin resource download strategy, returning a {@link PluginResource}.
30 * Returns <tt>null</tt> if the URL does not match (i.e. {@link #matches(String)} returns <tt>false</tt>), or the
31 * final part of the URL cannot be split into a moduleCompleteKey and resourceName (i.e. there's no slash in the
32 * final component).
33 * <p/>
34 * Parsing uses the download strategy prefix to determine where in the URL string to start. The strategy prefix and
35 * one character following it (typically a slash) is skipped, then the remainder is split on the first slash found.
36 *
37 * @param resourceUrl the URL of the resource request
38 * @return a resource which includes the plugin or plugin module's complete key and the resource name, or
39 * <tt>null</tt> if the URL doesn't parse correctly.
40 */
41 public PluginResource parse(String resourceUrl)
42 {
43 if (!matches(resourceUrl))
44 return null;
45
46 int indexOfStrategyPrefix = resourceUrl.indexOf(strategyPrefix);
47 String libraryAndResource = resourceUrl.substring(indexOfStrategyPrefix + strategyPrefix.length() + 1);
48 String[] parts = libraryAndResource.split("/", 2);
49
50 if (parts.length != 2)
51 return null;
52 return new PluginResource(parts[0], parts[1]);
53 }
54
55 /**
56 * Returns true if the provided URL matches a the URL prefix defined for this download strategy.
57 *
58 * @param resourceUrl the URL of the resource request
59 * @return <tt>true</tt> if the URL designates a request for this download strategy, otherwise <tt>false</tt>.
60 */
61 public boolean matches(String resourceUrl)
62 {
63 return resourceUrl.indexOf(BaseFileServerServlet.SERVLET_PATH + "/" + strategyPrefix) != -1;
64 }
65 }