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      @Override
040      public String parseParam(String str) {
041        try {
042          if (str != null) {
043            str = str.trim();
044            if (str.length() > 0) {
045              value = parse(str);
046            }
047          }
048        } catch (Exception ex) {
049          throw new IllegalArgumentException(
050            MessageFormat.format("Parameter [{0}], invalid value [{1}], value must be [{2}]",
051                                 getName(), str, getDomain()));
052        }
053        return value;
054      }
055    
056      @Override
057      protected String parse(String str) throws Exception {
058        if (pattern != null) {
059          if (!pattern.matcher(str).matches()) {
060            throw new IllegalArgumentException("Invalid value");
061          }
062        }
063        return str;
064      }
065    
066      @Override
067      protected String getDomain() {
068        return (pattern == null) ? "a string" : pattern.pattern();
069      }
070    }