1
2
3
4 package net.sourceforge.pmd.lang.rule.properties;
5
6 import java.util.Map;
7
8 import net.sourceforge.pmd.util.CollectionUtil;
9
10
11
12
13
14 public abstract class AbstractEnumeratedProperty<E, T> extends AbstractProperty<T> {
15
16 protected Map<String, E> choicesByLabel;
17 protected Map<E, String> labelsByChoice;
18
19 private String[] orderedLabels;
20 protected Object[][] choices;
21
22
23
24
25
26
27
28
29
30
31
32 @SuppressWarnings("unchecked")
33 public AbstractEnumeratedProperty(String theName, String theDescription, String[] theLabels, E[] theChoices, int[] choiceIndices, float theUIOrder, boolean isMulti) {
34 super(theName, theDescription, (T) selectionsIn(theLabels, choiceIndices, isMulti), theUIOrder);
35
36 choicesByLabel = CollectionUtil.mapFrom(theLabels, theChoices);
37 labelsByChoice = CollectionUtil.invertedMapFrom(choicesByLabel);
38 orderedLabels = theLabels;
39 }
40
41
42
43
44
45
46
47
48 private static Object selectionsIn(String[] items, int[] selectionIndices, boolean isMulti) {
49 String[] selections = new String[selectionIndices.length];
50 final int maxIdx = items.length - 1;
51 for (int i = 0; i < selections.length; i++) {
52 if (i < 0 || i > maxIdx) {
53 throw new IllegalArgumentException("Invalid item index: " + i);
54 }
55 selections[i] = items[selectionIndices[i]];
56 }
57 return isMulti ? selections : selections[0];
58 }
59
60
61
62
63 protected String defaultAsString() {
64
65 return isMultiValue() ?
66 (String)defaultValue() :
67 asDelimitedString(defaultValue(), '|');
68 }
69
70
71
72
73
74
75 protected String nonLegalValueMsgFor(Object value) {
76 return value + " is not a legal value";
77 }
78
79
80
81
82
83
84 protected E choiceFrom(String label) {
85 E result = choicesByLabel.get(label);
86 if (result != null) {
87 return result;
88 }
89 throw new IllegalArgumentException(label);
90 }
91
92
93
94
95 public Object[][] choices() {
96
97 if (choices != null) {
98 return choices;
99 }
100
101 choices = new Object[orderedLabels.length][2];
102
103 for (int i = 0; i < choices.length; i++) {
104 choices[i][0] = orderedLabels[i];
105 choices[i][1] = choicesByLabel.get(orderedLabels[i]);
106 }
107 orderedLabels = null;
108 return choices;
109 }
110 }