com.scarabsoft.endeavour.DefaultRouter Maven / Gradle / Ivy
The newest version!
package com.scarabsoft.endeavour;
import com.scarabsoft.endeavour.exception.ResourceNotFoundException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public final class DefaultRouter implements Router {
private static final Pattern pathVariablePattern = Pattern.compile("\\{\\w+\\}");
private final Map resourceMapping = new HashMap<>();
@Override
public void add(String uri, Resource> resource) {
final boolean matchAll = uri.contains("*");
final String uriPart[] = uri.replace("*","").split("/");
final StringBuilder builder = new StringBuilder();
final List names = new LinkedList<>();
for (int i = 0; i < uriPart.length; i++) {
if (uriPart[i].trim().isEmpty()) {
continue;
}
builder.append("/");
final Matcher matcher = pathVariablePattern.matcher(uriPart[i]);
if (matcher.matches()) {
builder.append("(\\w+)");
final String rawName = matcher.group(0);
names.add(rawName.substring(1, rawName.length() - 1));
} else {
builder.append(uriPart[i]);
}
}
builder.append("/?");
if (matchAll) {
builder.append(".*");
}
resourceMapping.put(Pattern.compile(builder.toString()), Route.newBuilder()
.uri(uri)
.pathVariableNames(names)
.resource(resource)
.build());
}
@Override
public Resource> getResource(Request request) throws ResourceNotFoundException {
final String uri = request.uri();
for (Pattern key : resourceMapping.keySet()) {
final Matcher matcher = key.matcher(uri);
if (matcher.matches()) {
final Route route = resourceMapping.get(key);
for (int i = 0; i < matcher.groupCount(); i++) {
request.addPathVariable(route.getPathVariableNames().get(i), matcher.group(i + 1));
}
return route.getResource();
}
}
throw new ResourceNotFoundException();
}
}