View Javadoc

1   package com.atlassian.plugins.rest.common.expand.parameter;
2   
3   import com.atlassian.plugins.rest.common.expand.Expandable;
4   import com.google.common.base.Preconditions;
5   import com.google.common.collect.ImmutableList;
6   import com.google.common.collect.Lists;
7   
8   import java.util.Collection;
9   import java.util.LinkedList;
10  
11  class ChainingExpandParameter implements ExpandParameter {
12      private final Collection<ExpandParameter> expandParameters;
13  
14      ChainingExpandParameter(ExpandParameter... expandParameters) {
15          this(Lists.newArrayList(expandParameters));
16      }
17  
18      ChainingExpandParameter(Iterable<ExpandParameter> expandParameters) {
19          this.expandParameters = ImmutableList.copyOf(Preconditions.checkNotNull(expandParameters));
20      }
21  
22      public boolean shouldExpand(Expandable expandable) {
23          for (ExpandParameter expandParameter : expandParameters) {
24              if (expandParameter.shouldExpand(expandable)) {
25                  return true;
26              }
27          }
28          return false;
29      }
30  
31      public Indexes getIndexes(Expandable expandable) {
32          // we do not merge indexes,
33          // so if we find an IndexParser.ALL that's what we return
34          // if we find only one non-empty, that's what we return
35          // else we throw an exception
36  
37          Indexes indexes = null;
38          for (ExpandParameter expandParameter : expandParameters) {
39              final Indexes i = expandParameter.getIndexes(expandable);
40              if (i.equals(IndexParser.ALL)) {
41                  return IndexParser.ALL;
42              }
43              if (!i.equals(IndexParser.EMPTY)) {
44                  if (indexes == null) {
45                      indexes = i;
46                  } else {
47                      throw new IndexException("Cannot merge multiple indexed expand parameters.");
48                  }
49              }
50          }
51          return indexes != null ? indexes : IndexParser.EMPTY;
52      }
53  
54      public ExpandParameter getExpandParameter(Expandable expandable) {
55          final Collection<ExpandParameter> newExpandParameters = new LinkedList<ExpandParameter>();
56          for (ExpandParameter expandParameter : expandParameters) {
57              newExpandParameters.add(expandParameter.getExpandParameter(expandable));
58          }
59          return new ChainingExpandParameter(newExpandParameters);
60      }
61  
62      public boolean isEmpty() {
63          for (ExpandParameter expandParameter : expandParameters) {
64              if (!expandParameter.isEmpty()) {
65                  return false;
66              }
67          }
68          return true;
69      }
70  }