View Javadoc

1   //========================================================================
2   //$Id: RewriteRegexRule.java 966 2008-04-17 13:53:44Z gregw $
3   //Copyright 2004-2005 Mort Bay Consulting Pty. Ltd.
4   //------------------------------------------------------------------------
5   //Licensed under the Apache License, Version 2.0 (the "License");
6   //you may not use this file except in compliance with the License.
7   //You may obtain a copy of the License at 
8   //http://www.apache.org/licenses/LICENSE-2.0
9   //Unless required by applicable law or agreed to in writing, software
10  //distributed under the License is distributed on an "AS IS" BASIS,
11  //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  //See the License for the specific language governing permissions and
13  //limitations under the License.
14  //========================================================================
15  package org.mortbay.jetty.handler.rewrite;
16  
17  import java.io.IOException;
18  import java.util.regex.Matcher;
19  
20  import javax.servlet.http.HttpServletRequest;
21  import javax.servlet.http.HttpServletResponse;
22  
23  /**
24   * Rewrite the URI by matching with a regular expression. 
25   * The replacement string may use $n" to replace the nth capture group.
26   */
27  public class RewriteRegexRule extends RegexRule
28  {
29      private String _replacement;
30  
31      /* ------------------------------------------------------------ */
32      public RewriteRegexRule()
33      {
34          _handling = false;
35          _terminating = false;
36      }
37  
38      /* ------------------------------------------------------------ */
39      /**
40       * Whenever a match is found, it replaces with this value.
41       * 
42       * @param replacement the replacement string.
43       */
44      public void setReplacement(String replacement)
45      {
46          _replacement = replacement;
47      }
48  
49  
50      /* ------------------------------------------------------------ */
51      /* (non-Javadoc)
52       * @see org.mortbay.jetty.handler.rules.RegexRule#apply(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.util.regex.Matcher)
53       */
54      public String apply(String target, HttpServletRequest request, HttpServletResponse response, Matcher matcher) throws IOException
55      {
56          target=_replacement;
57          for (int g=1;g<=matcher.groupCount();g++)
58          {
59              String group = matcher.group(g);
60              target=target.replaceAll("\\$"+g,group);
61          }
62  
63          return target;
64      }
65  
66      /* ------------------------------------------------------------ */
67      /**
68       * Returns the replacement string.
69       */
70      public String toString()
71      {
72          return super.toString()+"["+_replacement+"]";
73      }
74  }