View Javadoc

1   // ========================================================================
2   // Copyright (c) Webtide LLC
3   // ------------------------------------------------------------------------
4   // All rights reserved. This program and the accompanying materials
5   // are made available under the terms of the Eclipse Public License v1.0
6   // and Apache License v2.0 which accompanies this distribution.
7   //
8   // The Eclipse Public License is available at 
9   // http://www.eclipse.org/legal/epl-v10.html
10  //
11  // The Apache License v2.0 is available at
12  // http://www.apache.org/licenses/LICENSE-2.0.txt
13  //
14  // You may elect to redistribute this code under either of these licenses. 
15  // ========================================================================
16  
17  package org.eclipse.jetty.rewrite.handler;
18  
19  import java.io.IOException;
20  import java.util.regex.Matcher;
21  
22  import javax.servlet.http.HttpServletRequest;
23  import javax.servlet.http.HttpServletResponse;
24  
25  /**
26   * Redirects the response by matching with a regular expression.
27   * The replacement string may use $n" to replace the nth capture group.
28   */
29  public class RedirectRegexRule extends RegexRule
30  {
31      private String _replacement;
32      
33      public RedirectRegexRule()
34      {
35          _handling = true;
36          _terminating = true;
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      @Override
50      protected String apply(String target, HttpServletRequest request, HttpServletResponse response, Matcher matcher)
51              throws IOException
52      {
53          target=_replacement;
54          for (int g=1;g<=matcher.groupCount();g++)
55          {
56              String group = matcher.group(g);
57              target=target.replaceAll("\\$"+g,group);
58          }
59  
60          response.sendRedirect(response.encodeRedirectURL(target));
61          return target;
62      }
63  }