View Javadoc

1   package com.atlassian.plugins.rest.common.expand.resolver;
2   
3   import com.atlassian.plugins.rest.common.expand.*;
4   import com.atlassian.plugins.rest.common.expand.parameter.Indexes;
5   
6   import static com.google.common.base.Preconditions.checkNotNull;
7   
8   import java.lang.reflect.InvocationTargetException;
9   import java.lang.reflect.Method;
10  
11  /**
12   * {@link EntityExpanderResolver Entity expander resolver} that will get resolver for classes (objects) with method annotated with {@link ExpandConstraint @ExpandConstraint}.
13   * Method signature should be the same as below:
14   * <code>
15   * {@literal @}ExpandConstraint public void expandInstance(Indexes indexes)
16   * {
17   * // your code to expand the object here
18   * }
19   * </code>
20   */
21  public class ExpandConstraintEntityExpanderResolver implements EntityExpanderResolver {
22      public boolean hasExpander(Class<?> type) {
23          return getConstrainMethod(checkNotNull(type)) != null;
24      }
25  
26      public <T> EntityExpander<T> getExpander(Class<? extends T> type) {
27          final Method method = getConstrainMethod(checkNotNull(type));
28          return method != null ? (EntityExpander<T>) new ExpandConstraintEntityExpander(method) : null;
29      }
30  
31      private <T> Method getConstrainMethod(Class<? extends T> type) {
32          for (Method method : type.getDeclaredMethods()) {
33              if (method.getAnnotation(ExpandConstraint.class) != null
34                      && method.getParameterTypes().length == 1
35                      && method.getParameterTypes()[0].equals(Indexes.class)) {
36                  return method;
37              }
38          }
39          return null;
40      }
41  
42      private static class ExpandConstraintEntityExpander implements EntityExpander<Object> {
43          private final Method method;
44  
45          public ExpandConstraintEntityExpander(Method method) {
46              this.method = checkNotNull(method);
47          }
48  
49          public Object expand(ExpandContext<Object> context, EntityExpanderResolver expanderResolver, EntityCrawler entityCrawler) {
50              final Object entity = context.getEntity();
51              try {
52                  method.invoke(entity, context.getEntityExpandParameter().getIndexes(context.getExpandable()));
53              } catch (IllegalAccessException e) {
54                  throw new ExpandException(e);
55              } catch (InvocationTargetException e) {
56                  throw new ExpandException(e);
57              }
58  
59              entityCrawler.crawl(entity, context.getEntityExpandParameter().getExpandParameter(context.getExpandable()), expanderResolver);
60  
61              return entity;
62          }
63      }
64  }