001    /*
002     * Copyright (c) 2011, Cloudera, Inc. All Rights Reserved.
003     *
004     * Cloudera, Inc. licenses this file to you under the Apache License,
005     * Version 2.0 (the "License"). You may not use this file except in
006     * compliance with the License. You may obtain a copy of the License at
007     *
008     *     http://www.apache.org/licenses/LICENSE-2.0
009     *
010     * This software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
011     * CONDITIONS OF ANY KIND, either express or implied. See the License for
012     * the specific language governing permissions and limitations under the
013     * License.
014     */
015    package com.cloudera.lib.wsrs;
016    
017    import com.cloudera.lib.util.Check;
018    
019    import java.text.MessageFormat;
020    import java.util.regex.Pattern;
021    
022    public abstract class StringParam extends Param<String> {
023      private Pattern pattern;
024    
025      public StringParam(String name, String str) {
026        this(name, str, null);
027      }
028    
029      public StringParam(String name, String str, Pattern pattern) {
030        this.pattern = pattern;
031        value = parseParam(name, str);
032      }
033    
034      public String parseParam(String name, String str) {
035        String ret = null;
036        Check.notNull(name, "name");
037        try {
038          if (str != null) {
039            str = str.trim();
040            if (str.length() > 0) {
041              return parse(str);
042            }
043          }
044        }
045        catch (Exception ex) {
046          throw new IllegalArgumentException(
047            MessageFormat.format("Parameter [{0}], invalid value [{1}], value must be [{2}]",
048                                 name, str, getDomain()));
049        }
050        return ret;
051      }
052    
053      protected String parse(String str) throws Exception {
054        if (pattern != null) {
055          if (!pattern.matcher(str).matches()) {
056            throw new IllegalArgumentException("Invalid value");
057          }
058        }
059        return str;
060      }
061    
062      @Override
063      protected String getDomain() {
064        return (pattern == null) ? "a string" : pattern.pattern();
065      }
066    }