View Javadoc

1   /**
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  package org.apache.hadoop.hbase.http;
19  
20  import java.io.BufferedReader;
21  import java.io.IOException;
22  import java.io.InputStreamReader;
23  import java.net.URL;
24  import java.net.URLConnection;
25  import java.util.Random;
26  
27  import javax.servlet.Filter;
28  import javax.servlet.FilterChain;
29  import javax.servlet.FilterConfig;
30  import javax.servlet.ServletException;
31  import javax.servlet.ServletRequest;
32  import javax.servlet.ServletResponse;
33  import javax.servlet.http.HttpServletRequest;
34  
35  import org.apache.commons.logging.Log;
36  import org.apache.commons.logging.LogFactory;
37  import org.apache.hadoop.conf.Configuration;
38  import org.apache.hadoop.hbase.GenericTestUtils;
39  import org.apache.hadoop.hbase.testclassification.SmallTests;
40  import org.apache.hadoop.net.NetUtils;
41  import org.junit.Ignore;
42  import org.junit.Test;
43  import org.junit.experimental.categories.Category;
44  
45  @Category(SmallTests.class)
46  public class TestServletFilter extends HttpServerFunctionalTest {
47    private static final Log LOG = LogFactory.getLog(HttpServer.class);
48    static volatile String uri = null; 
49  
50    /** A very simple filter which record the uri filtered. */
51    static public class SimpleFilter implements Filter {
52      private FilterConfig filterConfig = null;
53  
54      @Override
55      public void init(FilterConfig filterConfig) throws ServletException {
56        this.filterConfig = filterConfig;
57      }
58  
59      @Override
60      public void destroy() {
61        this.filterConfig = null;
62      }
63  
64      @Override
65      public void doFilter(ServletRequest request, ServletResponse response,
66          FilterChain chain) throws IOException, ServletException {
67        if (filterConfig == null)
68           return;
69  
70        uri = ((HttpServletRequest)request).getRequestURI();
71        LOG.info("filtering " + uri);
72        chain.doFilter(request, response);
73      }
74  
75      /** Configuration for the filter */
76      static public class Initializer extends FilterInitializer {
77        public Initializer() {}
78  
79        @Override
80        public void initFilter(FilterContainer container, Configuration conf) {
81          container.addFilter("simple", SimpleFilter.class.getName(), null);
82        }
83      }
84    }
85    
86    
87    /** access a url, ignoring some IOException such as the page does not exist */
88    static void access(String urlstring) throws IOException {
89      LOG.warn("access " + urlstring);
90      URL url = new URL(urlstring);
91      URLConnection connection = url.openConnection();
92      connection.connect();
93      
94      try {
95        BufferedReader in = new BufferedReader(new InputStreamReader(
96            connection.getInputStream()));
97        try {
98          for(; in.readLine() != null; );
99        } finally {
100         in.close();
101       }
102     } catch(IOException ioe) {
103       LOG.warn("urlstring=" + urlstring, ioe);
104     }
105   }
106 
107   @Test
108   @Ignore
109   //From stack
110   // Its a 'foreign' test, one that came in from hadoop when we copy/pasted http
111   // It's second class. Could comment it out if only failing test (as per @nkeywal – sort of)
112   public void testServletFilter() throws Exception {
113     Configuration conf = new Configuration();
114     
115     //start a http server with CountingFilter
116     conf.set(HttpServer.FILTER_INITIALIZERS_PROPERTY,
117         SimpleFilter.Initializer.class.getName());
118     HttpServer http = createTestServer(conf);
119     http.start();
120 
121     final String fsckURL = "/fsck";
122     final String stacksURL = "/stacks";
123     final String ajspURL = "/a.jsp";
124     final String logURL = "/logs/a.log";
125     final String hadooplogoURL = "/static/hadoop-logo.jpg";
126     
127     final String[] urls = {fsckURL, stacksURL, ajspURL, logURL, hadooplogoURL};
128     final Random ran = new Random();
129     final int[] sequence = new int[50];
130 
131     //generate a random sequence and update counts 
132     for(int i = 0; i < sequence.length; i++) {
133       sequence[i] = ran.nextInt(urls.length);
134     }
135 
136     //access the urls as the sequence
137     final String prefix = "http://"
138         + NetUtils.getHostPortString(http.getConnectorAddress(0));
139     try {
140       for(int i = 0; i < sequence.length; i++) {
141         access(prefix + urls[sequence[i]]);
142 
143         //make sure everything except fsck get filtered
144         if (sequence[i] == 0) {
145           assertEquals(null, uri);
146         } else {
147           assertEquals(urls[sequence[i]], uri);
148           uri = null;
149         }
150       }
151     } finally {
152       http.stop();
153     }
154   }
155   
156   static public class ErrorFilter extends SimpleFilter {
157     @Override
158     public void init(FilterConfig arg0) throws ServletException {
159       throw new ServletException("Throwing the exception from Filter init");
160     }
161 
162     /** Configuration for the filter */
163     static public class Initializer extends FilterInitializer {
164       public Initializer() {
165       }
166 
167       @Override
168       public void initFilter(FilterContainer container, Configuration conf) {
169         container.addFilter("simple", ErrorFilter.class.getName(), null);
170       }
171     }
172   }
173 
174   @Test
175   public void testServletFilterWhenInitThrowsException() throws Exception {
176     Configuration conf = new Configuration();
177     // start a http server with ErrorFilter
178     conf.set(HttpServer.FILTER_INITIALIZERS_PROPERTY,
179         ErrorFilter.Initializer.class.getName());
180     HttpServer http = createTestServer(conf);
181     try {
182       http.start();
183       fail("expecting exception");
184     } catch (IOException e) {
185       assertTrue( e.getMessage().contains("Problem in starting http server. Server handlers failed"));
186     }
187   }
188   
189   /**
190    * Similar to the above test case, except that it uses a different API to add the
191    * filter. Regression test for HADOOP-8786.
192    */
193   @Test
194   public void testContextSpecificServletFilterWhenInitThrowsException()
195       throws Exception {
196     Configuration conf = new Configuration();
197     HttpServer http = createTestServer(conf);
198     HttpServer.defineFilter(http.webAppContext,
199         "ErrorFilter", ErrorFilter.class.getName(),
200         null, null);
201     try {
202       http.start();
203       fail("expecting exception");
204     } catch (IOException e) {
205       GenericTestUtils.assertExceptionContains("Unable to initialize WebAppContext", e);
206     }
207   }
208 
209 }