1 package com.atlassian.plugins.rest.common.expand.resolver;
2
3 import com.atlassian.plugins.rest.common.expand.EntityCrawler;
4 import com.atlassian.plugins.rest.common.expand.EntityExpander;
5 import com.atlassian.plugins.rest.common.expand.ExpandContext;
6 import com.atlassian.plugins.rest.common.expand.entity.ListWrapper;
7 import com.google.common.base.Preconditions;
8 import com.google.common.collect.Sets;
9
10 import java.lang.reflect.Field;
11 import java.util.Collection;
12 import java.util.Set;
13
14 import static com.atlassian.plugins.rest.common.util.ReflectionUtils.setFieldValue;
15
16
17
18
19 public class ListWrapperEntityExpanderResolver implements EntityExpanderResolver {
20 static final ListWrapperEntityExpander EXPANDER = new ListWrapperEntityExpander();
21
22 public boolean hasExpander(Class<?> type) {
23 return ListWrapper.class.isAssignableFrom(Preconditions.checkNotNull(type));
24 }
25
26 public <T> EntityExpander<T> getExpander(Class<? extends T> type) {
27 return ListWrapper.class.isAssignableFrom(type) ? (EntityExpander<T>) EXPANDER : null;
28 }
29
30 static class ListWrapperEntityExpander<T> implements EntityExpander<ListWrapper<T>> {
31 public ListWrapper<T> expand(ExpandContext<ListWrapper<T>> context, EntityExpanderResolver expanderResolver, EntityCrawler entityCrawler) {
32 final ListWrapper<T> entity = context.getEntity();
33
34 final Set<Field> collectionFields = Sets.newHashSet();
35 for (Class cls = entity.getClass(); cls != null; cls = cls.getSuperclass()) {
36 final Field[] fields = cls.getDeclaredFields();
37 for (Field field : fields) {
38 if (Collection.class.isAssignableFrom(field.getType())) {
39 collectionFields.add(field);
40 }
41 }
42 }
43 if (collectionFields.isEmpty()) {
44 throw new RuntimeException("Entity " + entity.getClass() + " has no collection field, cannot expand.");
45 }
46 if (collectionFields.size() > 1) {
47 throw new RuntimeException("Entity " + entity.getClass() + " has more than one collection field, cannot determine which collection to expand.");
48 }
49
50 setFieldValue(collectionFields.iterator().next(), entity, entity.getCallback().getItems(context.getEntityExpandParameter().getIndexes(context.getExpandable())));
51
52 entityCrawler.crawl(entity, context.getEntityExpandParameter().getExpandParameter(context.getExpandable()), expanderResolver);
53 return entity;
54 }
55
56 }
57 }