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 org.apache.hadoop.classification.InterfaceAudience;
021    
022    import java.text.MessageFormat;
023    import java.util.regex.Pattern;
024    
025    @InterfaceAudience.Private
026    public abstract class StringParam extends Param<String> {
027      private Pattern pattern;
028    
029      public StringParam(String name, String defaultValue) {
030        this(name, defaultValue, null);
031      }
032    
033      public StringParam(String name, String defaultValue, Pattern pattern) {
034        super(name, defaultValue);
035        this.pattern = pattern;
036        parseParam(defaultValue);
037      }
038    
039      public String parseParam(String str) {
040        try {
041          if (str != null) {
042            str = str.trim();
043            if (str.length() > 0) {
044              value = parse(str);
045            }
046          }
047        } catch (Exception ex) {
048          throw new IllegalArgumentException(
049            MessageFormat.format("Parameter [{0}], invalid value [{1}], value must be [{2}]",
050                                 getName(), str, getDomain()));
051        }
052        return value;
053      }
054    
055      protected String parse(String str) throws Exception {
056        if (pattern != null) {
057          if (!pattern.matcher(str).matches()) {
058            throw new IllegalArgumentException("Invalid value");
059          }
060        }
061        return str;
062      }
063    
064      @Override
065      protected String getDomain() {
066        return (pattern == null) ? "a string" : pattern.pattern();
067      }
068    }