001    /**
002     * Licensed to the Apache Software Foundation (ASF) under one
003     * or more contributor license agreements.  See the NOTICE file
004     * distributed with this work for additional information
005     * regarding copyright ownership.  The ASF licenses this file
006     * to you under the Apache License, Version 2.0 (the
007     * "License"); you may not use this file except in compliance
008     * with the License.  You may obtain a copy of the License at
009     *
010     *     http://www.apache.org/licenses/LICENSE-2.0
011     *
012     * Unless required by applicable law or agreed to in writing, software
013     * distributed under the License is distributed on an "AS IS" BASIS,
014     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015     * See the License for the specific language governing permissions and
016     * limitations under the License.
017     */
018    package org.apache.hadoop.lib.wsrs;
019    
020    import java.util.Arrays;
021    import java.util.EnumSet;
022    import java.util.Iterator;
023    
024    import org.apache.hadoop.classification.InterfaceAudience;
025    
026    @InterfaceAudience.Private
027    public abstract class EnumSetParam<E extends Enum<E>> extends Param<EnumSet<E>> {
028      Class<E> klass;
029    
030      public EnumSetParam(String name, Class<E> e, EnumSet<E> defaultValue) {
031        super(name, defaultValue);
032        klass = e;
033      }
034    
035      @Override
036      protected EnumSet<E> parse(String str) throws Exception {
037        final EnumSet<E> set = EnumSet.noneOf(klass);
038        if (!str.isEmpty()) {
039          for (String sub : str.split(",")) {
040            set.add(Enum.valueOf(klass, sub.trim().toUpperCase()));
041          }
042        }
043        return set;
044      }
045    
046      @Override
047      protected String getDomain() {
048        return Arrays.asList(klass.getEnumConstants()).toString();
049      }
050    
051      /** Convert an EnumSet to a string of comma separated values. */
052      public static <E extends Enum<E>> String toString(EnumSet<E> set) {
053        if (set == null || set.isEmpty()) {
054          return "";
055        } else {
056          final StringBuilder b = new StringBuilder();
057          final Iterator<E> i = set.iterator();
058          b.append(i.next());
059          while (i.hasNext()) {
060            b.append(',').append(i.next());
061          }
062          return b.toString();
063        }
064      }
065    
066      @Override
067      public String toString() {
068        return getName() + "=" + toString(value);
069      }
070    }