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 */
018package org.apache.hadoop.lib.wsrs;
019
020import java.util.Arrays;
021import java.util.EnumSet;
022import java.util.Iterator;
023
024import org.apache.hadoop.classification.InterfaceAudience;
025import org.apache.hadoop.util.StringUtils;
026
027@InterfaceAudience.Private
028public abstract class EnumSetParam<E extends Enum<E>> extends Param<EnumSet<E>> {
029  Class<E> klass;
030
031  public EnumSetParam(String name, Class<E> e, EnumSet<E> defaultValue) {
032    super(name, defaultValue);
033    klass = e;
034  }
035
036  @Override
037  protected EnumSet<E> parse(String str) throws Exception {
038    final EnumSet<E> set = EnumSet.noneOf(klass);
039    if (!str.isEmpty()) {
040      for (String sub : str.split(",")) {
041        set.add(Enum.valueOf(klass, StringUtils.toUpperCase(sub.trim())));
042      }
043    }
044    return set;
045  }
046
047  @Override
048  protected String getDomain() {
049    return Arrays.asList(klass.getEnumConstants()).toString();
050  }
051
052  /** Convert an EnumSet to a string of comma separated values. */
053  public static <E extends Enum<E>> String toString(EnumSet<E> set) {
054    if (set == null || set.isEmpty()) {
055      return "";
056    } else {
057      final StringBuilder b = new StringBuilder();
058      final Iterator<E> i = set.iterator();
059      b.append(i.next());
060      while (i.hasNext()) {
061        b.append(',').append(i.next());
062      }
063      return b.toString();
064    }
065  }
066
067  @Override
068  public String toString() {
069    return getName() + "=" + toString(value);
070  }
071}