A comprehensive utility library for Light-4J microservices framework providing string manipulation, networking, I/O, security, and configuration utilities.
—
Fast path template matching system for REST API routing with parameter extraction. Optimized for high-performance microservices with stem-based matching algorithms that provide efficient path resolution and parameter binding for HTTP request routing.
Generic path template matcher that provides fast routing and parameter extraction for REST APIs.
/**
* Fast path matching utility for path templates with stem-based optimization
*/
public class PathTemplateMatcher<T> {
// Constructor (default - no explicit public constructors)
// Template management
public PathTemplateMatcher<T> add(PathTemplate template, T value);
public PathTemplateMatcher<T> add(String pathTemplate, T value);
public PathTemplateMatcher<T> addAll(PathTemplateMatcher<T> pathTemplateMatcher);
public PathTemplateMatcher<T> remove(String pathTemplate);
// Matching operations
public PathMatchResult<T> match(String path);
public T get(String template);
public Set<PathTemplate> getPathTemplates();
}
/**
* Result of path template matching with associated value
*/
public interface PathMatchResult<T> extends PathTemplateMatch {
T getValue();
}Usage Examples:
import com.networknt.utility.PathTemplateMatcher;
import com.networknt.utility.PathTemplate;
// Create matcher for API endpoints
PathTemplateMatcher<String> apiMatcher = new PathTemplateMatcher<>();
// Add route patterns with associated handlers
apiMatcher.add("/api/users/{id}", "getUserById");
apiMatcher.add("/api/users", "getUsers");
apiMatcher.add("/api/users/{id}/posts/{postId}", "getUserPost");
apiMatcher.add("/api/orders/{orderId}/items", "getOrderItems");
// Match incoming requests
PathMatchResult<String> result = apiMatcher.match("/api/users/123");
if (result != null) {
String handlerName = result.getValue(); // "getUserById"
Map<String, String> params = result.getParameters(); // {id=123}
String template = result.getMatchedTemplate(); // "/api/users/{id}"
}
// Complex path matching
PathMatchResult<String> complexResult = apiMatcher.match("/api/users/456/posts/789");
if (complexResult != null) {
String handler = complexResult.getValue(); // "getUserPost"
Map<String, String> params = complexResult.getParameters();
// {id=456, postId=789}
}
// Check registered templates
Set<PathTemplate> templates = apiMatcher.getPathTemplates();
for (PathTemplate template : templates) {
System.out.println("Registered: " + template.getTemplateString());
}Individual path template representation with parameter parsing and matching capabilities.
/**
* Represents a parsed web socket path template with parameter support
*/
public class PathTemplate implements Comparable<PathTemplate> {
// Factory method
public static PathTemplate create(String inputPath);
// Matching operations
public boolean matches(String path, Map<String, String> pathParameters);
// Template information
public String getBase();
public String getTemplateString();
public Set<String> getParameterNames();
// Comparison for priority ordering
public int compareTo(PathTemplate other);
}Usage Examples:
import com.networknt.utility.PathTemplate;
import java.util.HashMap;
import java.util.Map;
// Create path templates
PathTemplate userTemplate = PathTemplate.create("/api/users/{id}");
PathTemplate postTemplate = PathTemplate.create("/api/users/{userId}/posts/{postId}");
// Get template information
String templateString = userTemplate.getTemplateString(); // "/api/users/{id}"
String base = userTemplate.getBase(); // "/api/users/"
Set<String> params = userTemplate.getParameterNames(); // ["id"]
// Match paths and extract parameters
Map<String, String> pathParams = new HashMap<>();
boolean matches = userTemplate.matches("/api/users/123", pathParams);
// matches = true, pathParams = {id=123}
// Complex template matching
Map<String, String> complexParams = new HashMap<>();
boolean complexMatches = postTemplate.matches("/api/users/456/posts/789", complexParams);
// complexMatches = true, complexParams = {userId=456, postId=789}
// Template comparison (for priority ordering)
List<PathTemplate> templates = Arrays.asList(
PathTemplate.create("/api/users"),
PathTemplate.create("/api/users/{id}"),
PathTemplate.create("/api/users/{id}/posts/{postId}")
);
Collections.sort(templates); // Sorts by specificityResult container for path template matches containing the matched template and extracted parameters.
/**
* Result container for path template matches
*/
public class PathTemplateMatch {
// Constructor
public PathTemplateMatch(String matchedTemplate, Map<String, String> parameters);
// Accessors
public String getMatchedTemplate();
public Map<String, String> getParameters();
}Usage Examples:
import com.networknt.utility.PathTemplateMatch;
import java.util.Map;
// Create match result
Map<String, String> params = Map.of("id", "123", "action", "edit");
PathTemplateMatch match = new PathTemplateMatch("/api/users/{id}/{action}", params);
// Access match information
String template = match.getMatchedTemplate(); // "/api/users/{id}/{action}"
Map<String, String> extractedParams = match.getParameters(); // {id=123, action=edit}
// Use in request processing
public void handleRequest(PathTemplateMatch match) {
String template = match.getMatchedTemplate();
Map<String, String> params = match.getParameters();
switch (template) {
case "/api/users/{id}":
handleUserRequest(params.get("id"));
break;
case "/api/users/{id}/posts/{postId}":
handleUserPostRequest(params.get("id"), params.get("postId"));
break;
}
}REST API Router Implementation:
public class ApiRouter {
private final PathTemplateMatcher<RequestHandler> handlers = new PathTemplateMatcher<>();
public void addRoute(String template, RequestHandler handler) {
handlers.add(template, handler);
}
public void handleRequest(String path, HttpRequest request, HttpResponse response) {
PathMatchResult<RequestHandler> result = handlers.match(path);
if (result != null) {
RequestHandler handler = result.getValue();
Map<String, String> pathParams = result.getParameters();
handler.handle(request, response, pathParams);
} else {
response.setStatus(404);
}
}
}
// Usage
ApiRouter router = new ApiRouter();
router.addRoute("/api/users/{id}", new UserHandler());
router.addRoute("/api/orders/{orderId}/items", new OrderItemsHandler());
router.handleRequest("/api/users/123", request, response);WebSocket Path Matching:
public class WebSocketPathMatcher {
private final PathTemplateMatcher<WebSocketHandler> wsHandlers = new PathTemplateMatcher<>();
public void addWebSocketHandler(String pathTemplate, WebSocketHandler handler) {
wsHandlers.add(pathTemplate, handler);
}
public WebSocketHandler findHandler(String wsPath) {
PathMatchResult<WebSocketHandler> result = wsHandlers.match(wsPath);
return result != null ? result.getValue() : null;
}
public Map<String, String> extractPathParameters(String wsPath) {
PathMatchResult<WebSocketHandler> result = wsHandlers.match(wsPath);
return result != null ? result.getParameters() : Collections.emptyMap();
}
}Multi-Version API Support:
PathTemplateMatcher<ApiHandler> versionedMatcher = new PathTemplateMatcher<>();
// Add versioned endpoints
versionedMatcher.add("/v1/api/users/{id}", new V1UserHandler());
versionedMatcher.add("/v2/api/users/{id}", new V2UserHandler());
versionedMatcher.add("/api/users/{id}", new LatestUserHandler()); // Default to latest
// Route based on version
PathMatchResult<ApiHandler> result = versionedMatcher.match(requestPath);
if (result != null) {
ApiHandler handler = result.getValue();
handler.processRequest(result.getParameters());
}Performance Optimization:
// Pre-compile templates for better performance
public class OptimizedRouter {
private final PathTemplateMatcher<String> matcher;
public OptimizedRouter(Map<String, String> routes) {
matcher = new PathTemplateMatcher<>();
// Add all routes at once for optimal internal structure
for (Map.Entry<String, String> route : routes.entrySet()) {
matcher.add(route.getKey(), route.getValue());
}
}
public String route(String path) {
PathMatchResult<String> result = matcher.match(path);
return result != null ? result.getValue() : null;
}
}Install with Tessl CLI
npx tessl i tessl/maven-com-networknt--utility