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 import static com.google.common.base.Preconditions.checkNotNull;
6
7 import java.lang.reflect.InvocationTargetException;
8 import java.lang.reflect.Method;
9
10
11
12
13
14
15
16
17
18
19
20 public class ExpandConstraintEntityExpanderResolver implements EntityExpanderResolver
21 {
22 public boolean hasExpander(Class<?> type)
23 {
24 return getConstrainMethod(checkNotNull(type)) != null;
25 }
26
27 public <T> EntityExpander<T> getExpander(Class<? extends T> type)
28 {
29 final Method method = getConstrainMethod(checkNotNull(type));
30 return method != null ? (EntityExpander<T>) new ExpandConstraintEntityExpander(method) : null;
31 }
32
33 private <T> Method getConstrainMethod(Class<? extends T> type)
34 {
35 for (Method method : type.getDeclaredMethods())
36 {
37 if (method.getAnnotation(ExpandConstraint.class) != null
38 && method.getParameterTypes().length == 1
39 && method.getParameterTypes()[0].equals(Indexes.class))
40 {
41 return method;
42 }
43 }
44 return null;
45 }
46
47 private static class ExpandConstraintEntityExpander implements EntityExpander<Object>
48 {
49 private final Method method;
50
51 public ExpandConstraintEntityExpander(Method method)
52 {
53 this.method = checkNotNull(method);
54 }
55
56 public Object expand(ExpandContext<Object> context, EntityExpanderResolver expanderResolver, EntityCrawler entityCrawler)
57 {
58 final Object entity = context.getEntity();
59 try
60 {
61 method.invoke(entity, context.getEntityExpandParameter().getIndexes(context.getExpandable()));
62 }
63 catch (IllegalAccessException e)
64 {
65 throw new ExpandException(e);
66 }
67 catch (InvocationTargetException e)
68 {
69 throw new ExpandException(e);
70 }
71
72 entityCrawler.crawl(entity, context.getEntityExpandParameter().getExpandParameter(context.getExpandable()), expanderResolver);
73
74 return entity;
75 }
76 }
77 }