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,
34 int[] choiceIndices, float theUIOrder, boolean isMulti) {
35 super(theName, theDescription, (T) selectionsIn(theLabels, choiceIndices, isMulti), theUIOrder);
36
37 choicesByLabel = CollectionUtil.mapFrom(theLabels, theChoices);
38 labelsByChoice = CollectionUtil.invertedMapFrom(choicesByLabel);
39 orderedLabels = theLabels;
40 }
41
42
43
44
45
46
47
48
49
50 private static Object selectionsIn(String[] items, int[] selectionIndices, boolean isMulti) {
51 String[] selections = new String[selectionIndices.length];
52 final int maxIdx = items.length - 1;
53 for (int i = 0; i < selections.length; i++) {
54 if (i < 0 || i > maxIdx) {
55 throw new IllegalArgumentException("Invalid item index: " + i);
56 }
57 selections[i] = items[selectionIndices[i]];
58 }
59 return isMulti ? selections : selections[0];
60 }
61
62
63
64
65 protected String defaultAsString() {
66
67 return isMultiValue() ? (String) defaultValue() : asDelimitedString(defaultValue(), '|');
68 }
69
70
71
72
73
74
75
76 protected String nonLegalValueMsgFor(Object value) {
77 return value + " is not a legal value";
78 }
79
80
81
82
83
84
85
86 protected E choiceFrom(String label) {
87 E result = choicesByLabel.get(label);
88 if (result != null) {
89 return result;
90 }
91 throw new IllegalArgumentException(label);
92 }
93
94
95
96
97 public Object[][] choices() {
98
99 if (choices != null) {
100 return choices;
101 }
102
103 choices = new Object[orderedLabels.length][2];
104
105 for (int i = 0; i < choices.length; i++) {
106 choices[i][0] = orderedLabels[i];
107 choices[i][1] = choicesByLabel.get(orderedLabels[i]);
108 }
109 orderedLabels = null;
110 return choices;
111 }
112 }