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,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.chemistry.opencmis.server.filter;
20  
21  import java.io.IOException;
22  
23  import java.util.regex.Pattern;
24  
25  import javax.servlet.Filter;
26  import javax.servlet.FilterChain;
27  import javax.servlet.FilterConfig;
28  import javax.servlet.ServletException;
29  import javax.servlet.ServletRequest;
30  import javax.servlet.ServletResponse;
31  import javax.servlet.http.HttpServletRequest;
32  
33  
34  /**
35   * A filter that corrects server name, server port and scheme if OpenCMIS is
36   * running behind a proxy or load balancer.
37   */
38  public class ProxyFilter implements Filter
39  {
40      public static final String PARAM_TRUSTED_PROXIES = "trustedProxies";
41      private Pattern trustedProxies;
42  
43      public void init( FilterConfig filterConfig ) throws ServletException
44      {
45          trustedProxies = null;
46  
47          String trustedProxiesString = filterConfig.getInitParameter( PARAM_TRUSTED_PROXIES );
48  
49          if ( trustedProxiesString != null )
50          {
51              try
52              {
53                  trustedProxies = Pattern.compile( trustedProxiesString );
54              }
55              catch ( Exception e )
56              {
57                  throw new ServletException( "Could not compile trustedProxies parameter: " + e, e );
58              }
59          }
60      }
61  
62      public void doFilter( ServletRequest request, ServletResponse response, FilterChain chain )
63          throws IOException, ServletException
64      {
65          // check for trusted proxy
66          if ( ( trustedProxies != null ) && ( request instanceof HttpServletRequest ) &&
67                  trustedProxies.matcher( request.getRemoteAddr(  ) ).matches(  ) )
68          {
69              request = new ProxyHttpServletRequestWrapper( (HttpServletRequest) request );
70          }
71  
72          // call next
73          chain.doFilter( request, response );
74      }
75  
76      public void destroy(  )
77      {
78      }
79  }