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 */
018package org.apache.hadoop.hdfs.web.resources;
019
020import static org.apache.hadoop.hdfs.client.HdfsClientConfigKeys.DFS_WEBHDFS_USER_PATTERN_DEFAULT;
021import org.apache.hadoop.security.UserGroupInformation;
022import com.google.common.annotations.VisibleForTesting;
023
024import java.text.MessageFormat;
025import java.util.regex.Pattern;
026
027/** User parameter. */
028public class UserParam extends StringParam {
029  /** Parameter name. */
030  public static final String NAME = "user.name";
031  /** Default parameter value. */
032  public static final String DEFAULT = "";
033
034  private static Domain domain = new Domain(NAME,
035      Pattern.compile(DFS_WEBHDFS_USER_PATTERN_DEFAULT));
036
037  @VisibleForTesting
038  public static Domain getUserPatternDomain() {
039    return domain;
040  }
041
042  @VisibleForTesting
043  public static void setUserPatternDomain(Domain dm) {
044    domain = dm;
045  }
046
047  public static void setUserPattern(String pattern) {
048    domain = new Domain(NAME, Pattern.compile(pattern));
049  }
050
051  private static String validateLength(String str) {
052    if (str == null) {
053      throw new IllegalArgumentException(
054        MessageFormat.format("Parameter [{0}], cannot be NULL", NAME));
055    }
056    int len = str.length();
057    if (len < 1) {
058      throw new IllegalArgumentException(MessageFormat.format(
059        "Parameter [{0}], it's length must be at least 1", NAME));
060    }
061    return str;
062  }
063
064  /**
065   * Constructor.
066   * @param str a string representation of the parameter value.
067   */
068  public UserParam(final String str) {
069    super(domain, str == null ||
070        str.equals(DEFAULT) ? null : validateLength(str));
071  }
072
073  /**
074   * Construct an object from a UGI.
075   */
076  public UserParam(final UserGroupInformation ugi) {
077    this(ugi.getShortUserName());
078  }
079
080  @Override
081  public String getName() {
082    return NAME;
083  }
084}