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.hdfs.web.resources;
019    
020    import org.apache.hadoop.security.UserGroupInformation;
021    
022    import java.text.MessageFormat;
023    import java.util.regex.Pattern;
024    
025    /** User parameter. */
026    public class UserParam extends StringParam {
027      /** Parameter name. */
028      public static final String NAME = "user.name";
029      /** Default parameter value. */
030      public static final String DEFAULT = "";
031    
032      private static final Domain DOMAIN = new Domain(NAME,
033        Pattern.compile("^[A-Za-z_][A-Za-z0-9._-]*[$]?$"));
034    
035      private static String validateLength(String str) {
036        if (str == null) {
037          throw new IllegalArgumentException(
038            MessageFormat.format("Parameter [{0}], cannot be NULL", NAME));
039        }
040        int len = str.length();
041        if (len < 1) {
042          throw new IllegalArgumentException(MessageFormat.format(
043            "Parameter [{0}], it's length must be at least 1", NAME));
044        }
045        return str;
046      }
047    
048      /**
049       * Constructor.
050       * @param str a string representation of the parameter value.
051       */
052      public UserParam(final String str) {
053        super(DOMAIN, str == null || str.equals(DEFAULT)? null : validateLength(str));
054      }
055    
056      /**
057       * Construct an object from a UGI.
058       */
059      public UserParam(final UserGroupInformation ugi) {
060        this(ugi.getShortUserName());
061      }
062    
063      @Override
064      public String getName() {
065        return NAME;
066      }
067    }