View Javadoc

1   package com.atlassian.plugins.rest.common.security.jersey;
2   
3   import com.atlassian.plugin.PluginAccessor;
4   import com.atlassian.plugin.event.PluginEventManager;
5   import com.atlassian.plugin.tracker.DefaultPluginModuleTracker;
6   import com.atlassian.plugin.tracker.PluginModuleTracker;
7   import com.atlassian.plugins.rest.common.security.CorsAllowed;
8   import com.atlassian.plugins.rest.common.security.descriptor.CorsDefaults;
9   import com.atlassian.plugins.rest.common.security.descriptor.CorsDefaultsModuleDescriptor;
10  import com.sun.jersey.api.model.AbstractMethod;
11  import com.sun.jersey.spi.container.ResourceFilter;
12  import com.sun.jersey.spi.container.ResourceFilterFactory;
13  import org.springframework.beans.factory.DisposableBean;
14  
15  import javax.ws.rs.HttpMethod;
16  import javax.ws.rs.ext.Provider;
17  import java.lang.annotation.Annotation;
18  import java.util.Collections;
19  import java.util.List;
20  
21  /**
22   * Factory for the Cross-Origin Resource Sharing resource filter, triggering off {@link com.atlassian.plugins.rest.common.security.CorsAllowed}.
23   *
24   * @since 2.6
25   */
26  @Provider
27  public class CorsResourceFilterFactory implements ResourceFilterFactory, DisposableBean
28  {
29      private final PluginModuleTracker<CorsDefaults,CorsDefaultsModuleDescriptor> tracker;
30  
31      public CorsResourceFilterFactory(PluginAccessor pluginAccessor, PluginEventManager pluginEventManager)
32      {
33          tracker = new DefaultPluginModuleTracker<CorsDefaults, CorsDefaultsModuleDescriptor>(pluginAccessor, pluginEventManager, CorsDefaultsModuleDescriptor.class);
34      }
35  
36      public List<ResourceFilter> create(final AbstractMethod method)
37      {
38          if (method.isAnnotationPresent(CorsAllowed.class)
39                  || method.getResource().isAnnotationPresent(CorsAllowed.class)
40                  || method.getResource().getResourceClass().getPackage().isAnnotationPresent(CorsAllowed.class))
41          {
42              String targetMethod = HttpMethod.GET;
43              for (Annotation ann : method.getAnnotations())
44              {
45                  HttpMethod m = ann.annotationType().getAnnotation(HttpMethod.class);
46                  if (m != null)
47                  {
48                      targetMethod = m.value();
49                      break;
50                  }
51              }
52  
53              return Collections.<ResourceFilter>singletonList(new CorsResourceFilter(tracker, targetMethod));
54          }
55          return Collections.emptyList();
56      }
57  
58      public void destroy() throws Exception
59      {
60          tracker.close();
61      }
62  }