Следующий метод получает «Маршрут» (имя класса и метод класса):
public Route getRoute(final String method, final String request) {
if (hasRoutes) {
for (Map.Entry<Pattern, HashMap<String, String>> entry : routes) {
Matcher match = entry.getKey().matcher(request);
if (match.find()) {
HashMap<String, String> methods = entry.getValue();
// ISSUE: Returns FALSE after 1st call of Router.getRoute()
if (methods.containsKey(method)) {
return new Route(match.group("interface"), "TRUE (" + method + " - " + match.group("interface") + "): " + methods.get(method));
} else {
return new Route(match.group("interface"), "FALSE (" + method + " - " + match.group("interface") + "): " + methods.values().toString() + ", SIZE: " + entry.getValue().size());
}
//return entry.getValue().containsKey(method) ? new Route(match.group("interface"), entry.getValue().get(method)) : null;
}
}
}
return null;
}
«маршруты» определяются как:
private Set<Entry<Pattern, HashMap<String, String>>> routes;
Это кэшированное представление файла конфигурации JSON, которое определяет поддерживаемые маршруты, например ::
{
"^/?(?<interface>threads)/?$": {
"GET": "list",
"POST": "create"
},
"^/?(?<interface>threads)/(?<id>\\d+)/?$": {
"GET": "get",
"POST": "reply",
"PUT": "edit",
"PATCH": "edit",
"DELETE": "delete"
}
}
РЕДАКТИРОВАТЬ, вот как «маршруты» заполняется из содержимого файла JSON:
try {
JsonParser parser = JSONFactory.createJsonParser(in);
JsonNode root = JSONMapper.readTree(parser);
Iterator base = root.getFieldNames();
Iterator node;
String match, method;
HashMap<Pattern, HashMap<String, String>> routesMap = new HashMap();
while (base.hasNext()) {
match = base.next().toString();
if (match != null) {
node = root.get(match).getFieldNames();
HashMap<String, String> methods = new HashMap();
while (node.hasNext()) {
method = node.next().toString();
if (method != null) {
methods.put(method, root.get(match).get(method).getTextValue());
}
}
if (!methods.isEmpty()) {
routesMap.put(Pattern.compile(match), methods);
}
}
}
if (!routesMap.isEmpty()) {
hasRoutes = true;
routes = routesMap.entrySet();
}
// Help garbage collection
parser = null;
root = null;
base = null;
node = null;
match = null;
method = null;
routesMap = null;
} catch (Exception ex) {
}
РЕДАКТИРОВАТЬ 2, свойства в вопросе и метод init ():
public final static JsonFactory JSONFactory = new JsonFactory();
public final static ObjectMapper JSONMapper = new ObjectMapper();
public static Router router;
private final Class self = getClass();
private final ClassLoader loader = self.getClassLoader();
public void init(ServletConfig config) throws ServletException {
super.init(config);
router = new Router(self.getResourceAsStream("/v1_0/Routes.json"), JSONFactory, JSONMapper);
}
По какой-то причине при доступе к сервлету после первого раза, в HashMap нет значений. X.size () возвращает ноль.
Это переписывание PHP-приложения с нуля, поэтому я заранее прошу прощения, если проблема является чем-то обыденным.
Полный источник:
- Источник маршрутизатора
- Источник маршрута