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
019 package org.apache.hadoop.lib.servlet;
020
021
022 import javax.servlet.Filter;
023 import javax.servlet.FilterChain;
024 import javax.servlet.FilterConfig;
025 import javax.servlet.ServletException;
026 import javax.servlet.ServletRequest;
027 import javax.servlet.ServletResponse;
028 import java.io.IOException;
029 import java.net.InetAddress;
030
031 /**
032 * Filter that resolves the requester hostname.
033 */
034 public class HostnameFilter implements Filter {
035 static final ThreadLocal<String> HOSTNAME_TL = new ThreadLocal<String>();
036
037 /**
038 * Initializes the filter.
039 * <p/>
040 * This implementation is a NOP.
041 *
042 * @param config filter configuration.
043 *
044 * @throws ServletException thrown if the filter could not be initialized.
045 */
046 @Override
047 public void init(FilterConfig config) throws ServletException {
048 }
049
050 /**
051 * Resolves the requester hostname and delegates the request to the chain.
052 * <p/>
053 * The requester hostname is available via the {@link #get} method.
054 *
055 * @param request servlet request.
056 * @param response servlet response.
057 * @param chain filter chain.
058 *
059 * @throws IOException thrown if an IO error occurrs.
060 * @throws ServletException thrown if a servet error occurrs.
061 */
062 @Override
063 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
064 throws IOException, ServletException {
065 try {
066 String hostname = InetAddress.getByName(request.getRemoteAddr()).getCanonicalHostName();
067 HOSTNAME_TL.set(hostname);
068 chain.doFilter(request, response);
069 } finally {
070 HOSTNAME_TL.remove();
071 }
072 }
073
074 /**
075 * Returns the requester hostname.
076 *
077 * @return the requester hostname.
078 */
079 public static String get() {
080 return HOSTNAME_TL.get();
081 }
082
083 /**
084 * Destroys the filter.
085 * <p/>
086 * This implementation is a NOP.
087 */
088 @Override
089 public void destroy() {
090 }
091 }