001 /**
002 * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
003 */
004 package net.sourceforge.pmd.lang.rule.properties;
005
006 import java.util.Map;
007
008 import net.sourceforge.pmd.util.CollectionUtil;
009
010 /**
011 */
012 public abstract class AbstractEnumeratedProperty<E, T> extends AbstractProperty<T> {
013
014 protected Map<String, E> choicesByLabel;
015 protected Map<E, String> labelsByChoice;
016
017 private String[] orderedLabels;
018 protected Object[][] choices;
019
020 /**
021 *
022 * @param theName
023 * @param theDescription
024 * @param theLabels
025 * @param theChoices
026 * @param choiceIndices
027 * @param theUIOrder
028 * @param isMulti
029 * @throws IllegalArgumentException
030 */
031 @SuppressWarnings("unchecked")
032 public AbstractEnumeratedProperty(String theName, String theDescription, String[] theLabels, E[] theChoices, int[] choiceIndices, float theUIOrder, boolean isMulti) {
033 super(theName, theDescription, (T) selectionsIn(theLabels, choiceIndices, isMulti), theUIOrder);
034
035 choicesByLabel = CollectionUtil.mapFrom(theLabels, theChoices);
036 labelsByChoice = CollectionUtil.invertedMapFrom(choicesByLabel);
037 orderedLabels = theLabels;
038 }
039
040 /**
041 * Method selectionsIn.
042 * @param items String[]
043 * @param selectionIndices int[]
044 * @param isMulti boolean
045 * @return Object
046 */
047 private static Object selectionsIn(String[] items, int[] selectionIndices, boolean isMulti) {
048 String[] selections = new String[selectionIndices.length];
049 final int maxIdx = items.length - 1;
050 for (int i = 0; i < selections.length; i++) {
051 if (i < 0 || i > maxIdx) {
052 throw new IllegalArgumentException("Invalid item index: " + i);
053 }
054 selections[i] = items[selectionIndices[i]];
055 }
056 return isMulti ? selections : selections[0];
057 }
058
059 /**
060 * @return String
061 */
062 protected String defaultAsString() {
063
064 return isMultiValue() ?
065 (String)defaultValue() :
066 asDelimitedString(defaultValue(), '|');
067 }
068
069 /**
070 * Method nonLegalValueMsgFor.
071 * @param value Object
072 * @return String
073 */
074 protected String nonLegalValueMsgFor(Object value) {
075 return value + " is not a legal value";
076 }
077
078 /**
079 * Method choiceFrom.
080 * @param label String
081 * @return E
082 */
083 protected E choiceFrom(String label) {
084 E result = choicesByLabel.get(label);
085 if (result != null) {
086 return result;
087 }
088 throw new IllegalArgumentException(label);
089 }
090
091 /**
092 * @see net.sourceforge.pmd.PropertyDescriptor#choices()
093 */
094 public Object[][] choices() {
095
096 if (choices != null) {
097 return choices;
098 }
099
100 choices = new Object[orderedLabels.length][2];
101
102 for (int i = 0; i < choices.length; i++) {
103 choices[i][0] = orderedLabels[i];
104 choices[i][1] = choicesByLabel.get(orderedLabels[i]);
105 }
106 orderedLabels = null; // no longer needed
107 return choices;
108 }
109 }
|