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 com.sun.jersey.api.core.HttpContext;
022import com.sun.jersey.core.spi.component.ComponentContext;
023import com.sun.jersey.core.spi.component.ComponentScope;
024import com.sun.jersey.server.impl.inject.AbstractHttpContextInjectable;
025import com.sun.jersey.spi.inject.Injectable;
026import com.sun.jersey.spi.inject.InjectableProvider;
027import org.slf4j.MDC;
028
029import javax.ws.rs.core.Context;
030import javax.ws.rs.ext.Provider;
031import java.lang.reflect.Type;
032import java.security.Principal;
033import java.util.regex.Pattern;
034
035@Provider
036public class UserProvider extends AbstractHttpContextInjectable<Principal> implements
037  InjectableProvider<Context, Type> {
038
039  public static final String USER_NAME_PARAM = "user.name";
040
041  public static final Pattern USER_PATTERN = Pattern.compile("[_a-zA-Z0-9]+");
042
043  private static class UserParam extends StringParam {
044
045    public UserParam(String user) {
046      super(USER_NAME_PARAM, user, USER_PATTERN);
047    }
048  }
049
050  @Override
051  public Principal getValue(HttpContext httpContext) {
052    Principal principal = httpContext.getRequest().getUserPrincipal();
053    if (principal == null) {
054      final String user = httpContext.getRequest().getQueryParameters().getFirst(USER_NAME_PARAM);
055      if (user != null) {
056        principal = new Principal() {
057          @Override
058          public String getName() {
059            return new UserParam(user).value();
060          }
061        };
062      }
063    }
064    if (principal != null) {
065      MDC.put("user", principal.getName());
066    }
067    return principal;
068  }
069
070  @Override
071  public ComponentScope getScope() {
072    return ComponentScope.PerRequest;
073  }
074
075  @Override
076  public Injectable getInjectable(ComponentContext componentContext, Context context, Type type) {
077    return (type.equals(Principal.class)) ? this : null;
078  }
079}