Skip to content

Commit

Permalink
Rename Router URL methods to URI methods since they do not contain Lo…
Browse files Browse the repository at this point in the history
…cation
  • Loading branch information
gitblit committed Dec 29, 2014
1 parent fea380e commit 7e8baa7
Show file tree
Hide file tree
Showing 14 changed files with 80 additions and 71 deletions.
Expand Up @@ -203,7 +203,7 @@ void setContextPath(String contextPath) {
}

public void GET(ClasspathResourceHandler resourceHandler) {
if (getRouter().urlPatternFor(resourceHandler.getClass()) != null) {
if (getRouter().uriPatternFor(resourceHandler.getClass()) != null) {
throw new PippoRuntimeException("You may only register one route for {}",
resourceHandler.getClass().getSimpleName());
}
Expand Down
Expand Up @@ -141,7 +141,7 @@ protected void renderDirectly(Request request, Response response) {
content.append("<li>");
content.append(route.getRequestMethod());
content.append(" ");
content.append(route.getUrlPattern());
content.append(route.getUriPattern());
content.append("</li>");
}
content.append("</ul>");
Expand Down
Expand Up @@ -114,10 +114,10 @@ protected void validateRoute(Route route) throws Exception {
throw new Exception("Invalid request method: " + route.getRequestMethod());
}

// validate the url pattern
String urlPattern = route.getUrlPattern();
if (urlPattern == null || urlPattern.isEmpty()) {
throw new Exception("The url pattern cannot be null or empty");
// validate the uri pattern
String uriPattern = route.getUriPattern();
if (uriPattern == null || uriPattern.isEmpty()) {
throw new Exception("The uri pattern cannot be null or empty");
}
}

Expand Down Expand Up @@ -151,7 +151,7 @@ public List<RouteMatch> findRoutes(String requestUri, String requestMethod) {

@Override
public void addRoute(Route route) throws Exception {
log.debug("Add route for '{} {}'", route.getRequestMethod(), route.getUrlPattern());
log.debug("Add route for '{} {}'", route.getRequestMethod(), route.getUriPattern());
validateRoute(route);
routes.add(route);

Expand All @@ -166,24 +166,29 @@ public void addRoute(Route route) throws Exception {
}

@Override
public String urlFor(String urlPattern, Map<String, Object> parameters) {
PatternBinding binding = getPatternBinding(urlPattern);
public String uriFor(String uri) {
return prefixContextPath(uri);
}

@Override
public String uriFor(String uriPattern, Map<String, Object> parameters) {
PatternBinding binding = getPatternBinding(uriPattern);

return (binding != null) ? prefixContextPath(urlFor(binding, parameters)) : null;
return (binding != null) ? prefixContextPath(uriFor(binding, parameters)) : null;
}

@Override
public String urlPatternFor(Class<? extends Controller> controllerClass, String methodName) {
public String uriFor(Class<? extends Controller> controllerClass, String methodName) {
Route route = getRoute(controllerClass, methodName);

return (route != null) ? route.getUrlPattern() : null;
return (route != null) ? route.getUriPattern() : null;
}

@Override
public String urlFor(Class<? extends Controller> controllerClass, String methodName, Map<String, Object> parameters) {
public String uriFor(Class<? extends Controller> controllerClass, String methodName, Map<String, Object> parameters) {
Route route = getRoute(controllerClass, methodName);

return (route != null) ? prefixContextPath(urlFor(route.getUrlPattern(), parameters)) : null;
return (route != null) ? prefixContextPath(uriFor(route.getUriPattern(), parameters)) : null;
}

private Route getRoute(Class<? extends Controller> controllerClass, String methodName) {
Expand All @@ -203,10 +208,10 @@ private Route getRoute(Class<? extends Controller> controllerClass, String metho
}

@Override
public String urlPatternFor(Class<? extends ClasspathResourceHandler> resourceHandlerClass) {
public String uriPatternFor(Class<? extends ClasspathResourceHandler> resourceHandlerClass) {
Route route = getRoute(resourceHandlerClass);

return (route != null) ? route.getUrlPattern() : null;
return (route != null) ? route.getUriPattern() : null;
}

private Route getRoute(Class<? extends ClasspathResourceHandler> resourceHandlerClass) {
Expand All @@ -225,11 +230,11 @@ private Route getRoute(Class<? extends ClasspathResourceHandler> resourceHandler


private void addBinding(Route route) {
String urlPattern = route.getUrlPattern();
String uriPattern = route.getUriPattern();
// TODO improve (it's possible to have the same urlPattern for many routes => same pattern)
String regex = getRegex(urlPattern);
String regex = getRegex(uriPattern);
Pattern pattern = Pattern.compile(regex);
List<String> parameterNames = getParameterNames(urlPattern);
List<String> parameterNames = getParameterNames(uriPattern);
PatternBinding binding = new PatternBinding(pattern, route, parameterNames);
String requestMethod = route.getRequestMethod();
if (!bindingsCache.containsKey(requestMethod)) {
Expand Down Expand Up @@ -320,12 +325,12 @@ private Map<String, String> getParameters(PatternBinding binding, String request
return parameters;
}

private PatternBinding getPatternBinding(String urlPattern) {
private PatternBinding getPatternBinding(String uriPattern) {
Iterator<List<PatternBinding>> iterator = bindingsCache.values().iterator();
while (iterator.hasNext()) {
List<PatternBinding> bindings = iterator.next();
for (PatternBinding binding : bindings) {
if (urlPattern.equals(binding.getRoute().getUrlPattern())) {
if (uriPattern.equals(binding.getRoute().getUriPattern())) {
return binding;
}
}
Expand All @@ -334,8 +339,8 @@ private PatternBinding getPatternBinding(String urlPattern) {
return null;
}

private String urlFor(PatternBinding binding, Map<String, Object> parameters) {
String url = binding.getRoute().getUrlPattern();
private String uriFor(PatternBinding binding, Map<String, Object> parameters) {
String uri = binding.getRoute().getUriPattern();

List<String> parameterNames = binding.getParameterNames();
if (!parameters.keySet().containsAll(parameterNames)) {
Expand All @@ -352,15 +357,15 @@ private String urlFor(PatternBinding binding, Map<String, Object> parameters) {
String buffer = String.format(VARIABLE_PART_PATTERN_WITH_PLACEHOLDER, parameterPair.getKey());

Pattern pattern = Pattern.compile(buffer);
Matcher matcher = pattern.matcher(url);
Matcher matcher = pattern.matcher(uri);
while (matcher.find()) {
String pathValue = parameterPair.getValue().toString();
matcher.appendReplacement(sb, pathValue);
foundAsPathParameter = true;
}

matcher.appendTail(sb);
url = sb.toString();
uri = sb.toString();

if (!foundAsPathParameter) {
queryParameters.put(parameterPair.getKey(), parameterPair.getValue());
Expand All @@ -385,10 +390,10 @@ private String urlFor(PatternBinding binding, Map<String, Object> parameters) {

}

url += "?" + query;
uri += "?" + query;
}

return url;
return uri;
}

private class PatternBinding {
Expand Down
16 changes: 8 additions & 8 deletions pippo-core/src/main/java/ro/fortsoft/pippo/core/route/Route.java
Expand Up @@ -22,18 +22,18 @@
*/
public class Route implements Serializable {

private String urlPattern;
private String uriPattern;
private String requestMethod;
private RouteHandler routeHandler;

public Route(String urlPattern, String requestMethod, RouteHandler routeHandler) {
this.urlPattern = urlPattern;
public Route(String uriPattern, String requestMethod, RouteHandler routeHandler) {
this.uriPattern = uriPattern;
this.requestMethod = requestMethod;
this.routeHandler = routeHandler;
}

public String getUrlPattern() {
return urlPattern;
public String getUriPattern() {
return uriPattern;
}

public String getRequestMethod() {
Expand All @@ -52,14 +52,14 @@ public boolean equals(Object o) {
Route route = (Route) o;

if (!requestMethod.equals(route.requestMethod)) return false;
if (!urlPattern.equals(route.urlPattern)) return false;
if (!uriPattern.equals(route.uriPattern)) return false;

return true;
}

@Override
public int hashCode() {
int result = urlPattern.hashCode();
int result = uriPattern.hashCode();
result = 31 * result + requestMethod.hashCode();
return result;
}
Expand All @@ -68,7 +68,7 @@ public int hashCode() {
public String toString() {
return "Route{" +
"requestMethod='" + requestMethod + '\'' +
", urlPattern='" + urlPattern + '\'' +
", uriPattern='" + uriPattern + '\'' +
'}';
}

Expand Down
Expand Up @@ -49,11 +49,13 @@ public interface Router {

public List<Route> getRoutes();

public String urlFor(String urlPattern, Map<String, Object> parameters);
public String uriFor(String uri);

public String urlFor(Class<? extends Controller> controllerClass, String methodName, Map<String, Object> parameters);
public String uriFor(String urlPattern, Map<String, Object> parameters);

public String urlPatternFor(Class<? extends Controller> controllerClass, String methodName);
public String uriFor(Class<? extends Controller> controllerClass, String methodName, Map<String, Object> parameters);

public String urlPatternFor(Class<? extends ClasspathResourceHandler> resourceHandlerClass);
public String uriFor(Class<? extends Controller> controllerClass, String methodName);

public String uriPatternFor(Class<? extends ClasspathResourceHandler> resourceHandlerClass);
}
Expand Up @@ -54,18 +54,18 @@ public void after() {
}

@Test
public void testNullUrlPatternRoute() throws Exception {
public void testNullUriPatternRoute() throws Exception {
Route route = new Route(null, HttpConstants.Method.GET, new EmptyRouteHandler());
thrown.expect(Exception.class);
thrown.expectMessage("The url pattern cannot be null or empty");
thrown.expectMessage("The uri pattern cannot be null or empty");
router.addRoute(route);
}

@Test
public void testEmptyUrlPatternRoute() throws Exception {
public void testEmptyUriPatternRoute() throws Exception {
Route route = new Route("", HttpConstants.Method.GET, new EmptyRouteHandler());
thrown.expect(Exception.class);
thrown.expectMessage("The url pattern cannot be null or empty");
thrown.expectMessage("The uri pattern cannot be null or empty");
router.addRoute(route);
}

Expand Down Expand Up @@ -168,8 +168,7 @@ public void testIntIdRoute2() throws Exception {
new EmptyRouteHandler());
router.addRoute(route);

List<RouteMatch> routeMatches = router.findRoutes("/contact/3/something/borrowed",
HttpConstants.Method.GET);
List<RouteMatch> routeMatches = router.findRoutes("/contact/3/something/borrowed", HttpConstants.Method.GET);
assertEquals(1, routeMatches.size());

Map<String, String> pathParameters = routeMatches.get(0).getPathParameters();
Expand Down Expand Up @@ -272,8 +271,7 @@ public void testParametersAndRegexInsideVariableParts() throws Exception {
assertEquals("robots.txt", match.getPathParameters().get("path"));

// multiple parameter parsing with regex expressions
router.addRoute(new Route("/{name: .+}/photos/{id: [0-9]+}", HttpConstants.Method.GET,
new EmptyRouteHandler()));
router.addRoute(new Route("/{name: .+}/photos/{id: [0-9]+}", HttpConstants.Method.GET, new EmptyRouteHandler()));

pathUnderTest = "/John/photos/2201";
matches = router.findRoutes(pathUnderTest, HttpConstants.Method.GET);
Expand All @@ -292,8 +290,7 @@ public void testParametersDontCrossSlashes() throws Exception {
new EmptyRouteHandler()));

// this must match
assertEquals(1, router.findRoutes("/blah/id/id2/id3/morestuff/at/the/end", HttpConstants.Method.GET)
.size());
assertEquals(1, router.findRoutes("/blah/id/id2/id3/morestuff/at/the/end", HttpConstants.Method.GET).size());

// this should not match as the last "end" is missing
assertEquals(0, router.findRoutes("/blah/id/id2/id3/morestuff/at/the", HttpConstants.Method.GET).size());
Expand Down Expand Up @@ -405,29 +402,29 @@ public void testRouteWithUrlEncodedSlashGetsChoppedCorrectly() throws Exception
}

@Test
public void testUrlForWithRegex() throws Exception {
public void testUriForWithRegex() throws Exception {
Route route = new Route("/user/{email}/{id: .*}", HttpConstants.Method.GET, new EmptyRouteHandler());
router.addRoute(route);

Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("email", "test@test.com");
parameters.put("id", 5);
String path = router.urlFor(route.getUrlPattern(), parameters);
String path = router.uriFor(route.getUriPattern(), parameters);

assertThat(path, equalTo("/user/test@test.com/5"));

}

@Test
public void testUrlForWithRegexAndQueryParameters() throws Exception {
public void testUriForWithRegexAndQueryParameters() throws Exception {
Route route = new Route("/user/{email}/{id: .*}", HttpConstants.Method.GET, new EmptyRouteHandler());
router.addRoute(route);

Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("email", "test@test.com");
parameters.put("id", 5);
parameters.put("query", "recent_changes");
String path = router.urlFor(route.getUrlPattern(), parameters);
String path = router.uriFor(route.getUriPattern(), parameters);

assertThat(path, equalTo("/user/test@test.com/5?query=recent_changes"));
}
Expand Down
Expand Up @@ -42,13 +42,13 @@ public void index() {
}

@Timed
public void urlFor(@Param("id") int id) {
public void uriFor(@Param("id") int id) {
Map<String, Object> parameters = new HashMap<>();
parameters.put("id", id);
parameters.put("action", "new");
String url = getApplication().getRouter().urlFor(ContactsController.class, "urlFor", parameters);
String uri = getApplication().getRouter().uriFor(ContactsController.class, "uriFor", parameters);

getResponse().send("id = " + id + "; url = " + url);
getResponse().send("id = " + id + "; uri = " + uri);
}

}
Expand Up @@ -29,7 +29,7 @@ public static void main(String[] args) {
pippo.getApplication().GET(new WebjarsResourceHandler());
pippo.getApplication().GET(new PublicResourceHandler());
pippo.getApplication().GET("/", ContactsController.class, "index");
pippo.getApplication().GET("/contact/{id}", ContactsController.class, "urlFor");
pippo.getApplication().GET("/contact/{id}", ContactsController.class, "uriFor");
pippo.start();
}

Expand Down
Expand Up @@ -25,11 +25,16 @@
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
* @author Decebal Suiu
*/
public class CrudApplication extends Application {

private final Logger log = LoggerFactory.getLogger(CrudApplication.class);

private ContactService contactService;

@Override
Expand All @@ -43,7 +48,7 @@ public void init() {

@Override
public void handle(Request request, Response response, RouteHandlerChain chain) {
System.out.println("request.getUri() = " + request.getUri());
log.info("request.getUri() = {}", request.getUri());
chain.next();
}

Expand Down Expand Up @@ -114,8 +119,8 @@ public void handle(Request request, Response response, RouteHandlerChain chain)
editAction.append("&id=");
editAction.append(id);
}
model.put("editAction", editAction);
model.put("backAction", "/contacts");
model.put("editAction", getRouter().uriFor(editAction.toString()));
model.put("backAction", getRouter().uriFor("/contacts"));
response.render("crud/contact", model);
}

Expand Down
Expand Up @@ -56,7 +56,7 @@ public ClasspathResourceMethod(Router router, Class<T> resourceHandlerClass) {
@Override
public TemplateModel exec(List args) throws TemplateModelException {
if (urlPattern.get() == null) {
String pattern = router.urlPatternFor(resourceHandlerClass);
String pattern = router.uriPatternFor(resourceHandlerClass);
if (pattern == null) {
throw new PippoRuntimeException("You must register a route for {}",
resourceHandlerClass.getSimpleName());
Expand All @@ -68,7 +68,7 @@ public TemplateModel exec(List args) throws TemplateModelException {
String path = args.get(0).toString();
Map<String, Object> parameters = new HashMap<>();
parameters.put(ClasspathResourceHandler.PATH_PARAMETER, path);
String url = router.urlFor(urlPattern.get(), parameters);
String url = router.uriFor(urlPattern.get(), parameters);
return new SimpleScalar(url);
}

Expand Down

0 comments on commit 7e8baa7

Please sign in to comment.