ParamParser implements Function<String, RoutePart<?>> { @Override public RoutePart<?> apply(String part) { if (isPathParam(part)) { String param = getPathParam(part); int paramIndex = param.indexOf(NAME_TYPE_DELIMITER); char[] paramChars = param.toCharArray(); String paramName = paramIndex == -1 ? param : new String(paramChars, 0, paramIndex); if (pathParams.containsKey(paramName)) { throw new InvalidConfigurationException(String.format( "Route '%s' contains more path params with the same name '%s'.", path, paramName)); } VariableType<?> variableType; if (paramIndex == -1) { variableType = StringVariable.INSTANCE; } else { String paramType = new String(paramChars, paramIndex + 1, paramChars.length - paramIndex - 1); Optional<VariableType<?>> optPathType = Optional.ofNullable(PATH_TYPES.get(paramType)); variableType = optPathType.orElseThrow(() -> new InvalidConfigurationException(String.format( "Missing a path type for param '%s' and type '%s' in the route '%s'.", paramName, paramType, path))); } RoutePart<?> routePart = new RoutePart<>(RoutePart.Type.PARAM, paramName, variableType); pathParams.put(paramName, routePart); return routePart; } return new RoutePart<>(RoutePart.Type.PATH, part, StringVariable.INSTANCE); } ParamParser(String path); @Override RoutePart<?> apply(String part); static final String NAME_TYPE_DELIMITER; }
@Test public void parse_path() { ParamParser parser = new ParamParser("/services/joke/single"); RoutePart<?> result = parser.apply("services"); assertEquals("services", result.getValue()); assertEquals("str", result.getVariableType().getName()); assertEquals(RoutePart.Type.PATH, result.getType()); }
@Test public void parse_variable() { ParamParser parser = new ParamParser("/services/joke/{id}"); RoutePart<?> result = parser.apply("{id}"); assertEquals("id", result.getValue()); assertEquals("str", result.getVariableType().getName()); assertEquals(RoutePart.Type.PARAM, result.getType()); }
@Test public void parse_variable_with_type() { ParamParser parser = new ParamParser("/services/joke/{id:int}"); RoutePart<?> result = parser.apply("{id:int}"); assertEquals("id", result.getValue()); assertEquals("int", result.getVariableType().getName()); assertEquals(RoutePart.Type.PARAM, result.getType()); }
@Test(expected = InvalidConfigurationException.class) public void parse_variable_with_unknown_type() { ParamParser parser = new ParamParser("/services/joke/{id:int}"); parser.apply("{id:unknown}"); }
@Test(expected = InvalidConfigurationException.class) public void parse_duplicate_variable() { ParamParser parser = new ParamParser("/services/{id}/joke/{id}"); parser.apply("{id}"); parser.apply("{id}"); }