[Bug 395380] add ValidUrlRule to jetty-rewrite

This commit is contained in:
Jesse McConnell 2012-11-29 10:53:50 -06:00
parent 2723c415bf
commit 90b8f60e7b
2 changed files with 132 additions and 0 deletions

View File

@ -0,0 +1,81 @@
package org.eclipse.jetty.rewrite.handler;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ValidUrlRule extends Rule
{
String _code = "400";
String _reason = "Illegal Url";
public ValidUrlRule()
{
_handling = true;
_terminating = true;
}
/* ------------------------------------------------------------ */
/**
* Sets the response status code.
*
* @param code
* response code
*/
public void setCode(String code)
{
_code = code;
}
/* ------------------------------------------------------------ */
/**
* Sets the reason for the response status code. Reasons will only reflect if the code value is greater or equal to 400.
*
* @param reason
*/
public void setReason(String reason)
{
_reason = reason;
}
@Override
public String matchAndApply(String target, HttpServletRequest request, HttpServletResponse response) throws IOException
{
String uri = request.getRequestURI();
for (int i = 0; i < uri.length(); ++i)
{
if (!isPrintableChar(uri.charAt(i)))
{
int code = Integer.parseInt(_code);
// status code 400 and up are error codes so include a reason
if (code >= 400)
{
response.sendError(code,_reason);
}
else
{
response.setStatus(code);
}
return target;
}
}
return null;
}
protected boolean isPrintableChar(char c)
{
Character.UnicodeBlock block = Character.UnicodeBlock.of(c);
return (!Character.isISOControl(c)) && block != null && block != Character.UnicodeBlock.SPECIALS;
}
public String toString()
{
return super.toString() + "[" + _code + ":" + _reason + "]";
}
}

View File

@ -0,0 +1,51 @@
package org.eclipse.jetty.rewrite.handler;
import static org.junit.Assert.assertEquals;
import junit.framework.Assert;
import org.junit.Before;
import org.junit.Test;
public class ValidUrlRuleTest extends AbstractRuleTestCase
{
private ValidUrlRule _rule;
@Before
public void init() throws Exception
{
start(true);
_rule = new ValidUrlRule();
}
@Test
public void testValidUrl() throws Exception
{
_rule.setCode("404");
_request.setRequestURI("/valid/uri.html");
String result = _rule.matchAndApply(_request.getRequestURI(), _request, _response);
assertEquals(200,_response.getStatus());
}
@Test
public void testInvalidUrl() throws Exception
{
_rule.setCode("404");
_request.setRequestURI("/invalid\u000c/uri.html");
String result = _rule.matchAndApply(_request.getRequestURI(), _request, _response);
assertEquals(404,_response.getStatus());
}
@Test
public void testCharacters() throws Exception
{
// space
Assert.assertTrue( _rule.isPrintableChar("\u0020".charAt(0)));
// form feed
Assert.assertFalse( _rule.isPrintableChar("\u000c".charAt(0)));
}
}