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
019package org.apache.hadoop.lib.wsrs;
020
021import org.apache.hadoop.lib.util.Check;
022
023import java.text.MessageFormat;
024import java.util.regex.Pattern;
025
026public abstract class StringParam extends Param<String> {
027  private Pattern pattern;
028
029  public StringParam(String name, String str) {
030    this(name, str, null);
031  }
032
033  public StringParam(String name, String str, Pattern pattern) {
034    this.pattern = pattern;
035    value = parseParam(name, str);
036  }
037
038  public String parseParam(String name, String str) {
039    String ret = null;
040    Check.notNull(name, "name");
041    try {
042      if (str != null) {
043        str = str.trim();
044        if (str.length() > 0) {
045          return 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                             name, str, getDomain()));
052    }
053    return ret;
054  }
055
056  protected String parse(String str) throws Exception {
057    if (pattern != null) {
058      if (!pattern.matcher(str).matches()) {
059        throw new IllegalArgumentException("Invalid value");
060      }
061    }
062    return str;
063  }
064
065  @Override
066  protected String getDomain() {
067    return (pattern == null) ? "a string" : pattern.pattern();
068  }
069}