View Javadoc

1   package com.atlassian.plugins.rest.common.filter;
2   
3   import com.google.common.collect.ImmutableMap;
4   import com.sun.jersey.spi.container.ContainerRequest;
5   import com.sun.jersey.spi.container.ContainerRequestFilter;
6   import org.apache.commons.lang.StringUtils;
7   import org.apache.commons.lang.Validate;
8   
9   import javax.ws.rs.core.HttpHeaders;
10  import static javax.ws.rs.core.MediaType.*;
11  import javax.ws.rs.core.UriBuilder;
12  import javax.ws.rs.ext.Provider;
13  import java.net.URI;
14  import java.util.Collection;
15  import java.util.LinkedList;
16  import java.util.List;
17  import java.util.Map;
18  import java.util.regex.Pattern;
19  
20  /**
21   * <p>A filter to handle URI with extensions. It will set the correct accept header for each extension and remove the extension
22   * from the URI to allow for normal processing of the request.</p>
23   * <p>Currently supported extension and their matching headers are defined in {@link #EXTENSION_TO_ACCEPT_HEADER the extension to header mapping}.</p>
24   * <p>One can exclude URIs from being processed by this filter. Simply create the filter with a collection of {@link Pattern patterns} to be excluded.</p>
25   * <p><strong>Example:</strong> URI <code>http://localhost:8080/app/rest/my/resource.json</code> would be automatically mapped to URI <code>http://localhost:8080/app/rest/my/resource</code>
26   * with its <code>accept</code> header set to <code>application/json</code></p>
27   */
28  @Provider
29  public class ExtensionJerseyFilter implements ContainerRequestFilter
30  {
31      private static final String DOT = ".";
32  
33      private final Collection<Pattern> pathExcludePatterns;
34  
35      public ExtensionJerseyFilter()
36      {
37          pathExcludePatterns = new LinkedList<Pattern>();
38      }
39  
40      public ExtensionJerseyFilter(Collection<String> pathExcludePatterns)
41      {
42          Validate.notNull(pathExcludePatterns);
43          this.pathExcludePatterns = compilePatterns(pathExcludePatterns);
44      }
45  
46      final static Map<String, String> EXTENSION_TO_ACCEPT_HEADER = new ImmutableMap.Builder<String, String>()
47              .put("txt", TEXT_PLAIN)
48              .put("htm", TEXT_HTML)
49              .put("html", TEXT_HTML)
50              .put("json", APPLICATION_JSON)
51              .put("xml", APPLICATION_XML)
52              .put("atom", APPLICATION_ATOM_XML)
53              .build();
54  
55      public ContainerRequest filter(ContainerRequest request)
56      {
57          // the path to the request without query params
58          final String absolutePath = request.getAbsolutePath().toString();
59  
60          final String extension = StringUtils.substringAfterLast(absolutePath, DOT);
61          if (shouldFilter("/" + StringUtils.difference(request.getBaseUri().toString(), absolutePath), extension))
62          {
63              request.getRequestHeaders().putSingle(HttpHeaders.ACCEPT, EXTENSION_TO_ACCEPT_HEADER.get(extension));
64              final String absolutePathWithoutExtension = StringUtils.substringBeforeLast(absolutePath, DOT);
65              request.setUris(request.getBaseUri(), getRequestUri(absolutePathWithoutExtension, request.getQueryParameters()));
66          }
67          return request;
68      }
69  
70      private boolean shouldFilter(String restPath, String extension)
71      {
72          for (Pattern pattern : pathExcludePatterns)
73          {
74              if (pattern.matcher(restPath).matches())
75              {
76                  return false;
77              }
78          }
79          return EXTENSION_TO_ACCEPT_HEADER.containsKey(extension);
80      }
81  
82      private URI getRequestUri(String absolutePathWithoutExtension, Map<String, List<String>> queryParams)
83      {
84          final UriBuilder requestUriBuilder = UriBuilder.fromPath(absolutePathWithoutExtension);
85          for (Map.Entry<String, List<String>> queryParamEntry : queryParams.entrySet())
86          {
87              for (String value : queryParamEntry.getValue())
88              {
89                  requestUriBuilder.queryParam(queryParamEntry.getKey(), value);
90              }
91          }
92          return requestUriBuilder.build();
93      }
94  
95      private Collection<Pattern> compilePatterns(Collection<String> pathExcludePatterns)
96      {
97          final Collection<Pattern> patterns = new LinkedList<Pattern>();
98          for (String pattern : pathExcludePatterns)
99          {
100             patterns.add(Pattern.compile(pattern));
101         }
102         return patterns;
103     }
104 }