1 // ======================================================================== 2 // Copyright (c) 2004-2009 Mort Bay Consulting Pty. Ltd. 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 // The Eclipse Public License is available at 8 // http://www.eclipse.org/legal/epl-v10.html 9 // The Apache License v2.0 is available at 10 // http://www.opensource.org/licenses/apache2.0.php 11 // You may elect to redistribute this code under either of these licenses. 12 // ======================================================================== 13 package org.eclipse.jetty.rewrite.handler; 14 15 import java.io.IOException; 16 import java.util.regex.Matcher; 17 18 import javax.servlet.http.HttpServletRequest; 19 import javax.servlet.http.HttpServletResponse; 20 21 /** 22 * Rewrite the URI by matching with a regular expression. 23 * The replacement string may use $n" to replace the nth capture group. 24 */ 25 public class RewriteRegexRule extends RegexRule 26 { 27 private String _replacement; 28 29 /* ------------------------------------------------------------ */ 30 public RewriteRegexRule() 31 { 32 _handling = false; 33 _terminating = false; 34 } 35 36 /* ------------------------------------------------------------ */ 37 /** 38 * Whenever a match is found, it replaces with this value. 39 * 40 * @param replacement the replacement string. 41 */ 42 public void setReplacement(String replacement) 43 { 44 _replacement = replacement; 45 } 46 47 48 /* ------------------------------------------------------------ */ 49 /* (non-Javadoc) 50 * @see org.eclipse.jetty.server.handler.rules.RegexRule#apply(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.util.regex.Matcher) 51 */ 52 public String apply(String target, HttpServletRequest request, HttpServletResponse response, Matcher matcher) throws IOException 53 { 54 target=_replacement; 55 for (int g=1;g<=matcher.groupCount();g++) 56 { 57 String group = matcher.group(g); 58 target=target.replaceAll("\\$"+g,group); 59 } 60 61 return target; 62 } 63 64 /* ------------------------------------------------------------ */ 65 /** 66 * Returns the replacement string. 67 */ 68 public String toString() 69 { 70 return super.toString()+"["+_replacement+"]"; 71 } 72 }