JAX-RS路径匹配

时间:2018-06-14 21:03:20

标签: java regex jax-rs

我想验证REST API的URL。例如,我有这个JAX-RS路径:

/users/{id : \\d+} 

现在我将在不启动服务器的情况下测试不同的URL

/users/1 - >有效

/users/a - >无效

有人知道现有的解决方案或可能吗?

更新
我创建了一种从Path Annotation获取Regex的方法。但是当字符{}:处于意外位置时可能会出现问题。

private String GetRegex(String patternPath) {
    int indexOfOpen = patternPath.indexOf("{", 0);
    if (indexOfOpen < 0) {
        return patternPath;
    } else {
        int indexOfClose = patternPath.indexOf("}");
        int indexOfRegexStart = patternPath.indexOf(":");
        if (indexOfRegexStart < 0 || indexOfRegexStart > indexOfClose) {
            patternPath = patternPath.substring(0, indexOfOpen) + ".*"
                    + patternPath.substring(indexOfClose + 1, patternPath.length());
        } else {
            patternPath = patternPath.substring(0, indexOfOpen)
                    + patternPath.substring(indexOfRegexStart + 1, indexOfClose).trim()
                    + patternPath.substring(indexOfClose + 1, patternPath.length());
        }

        return GetRegex(patternPath);
    }
}

测试:

String patternPath = "/users/{userid}/{userId2 : \\d+$}";
String methodPath = "/users/435345/435435";

String getRegex = GetRegex(patternPath);

Assert.assertEquals("/users/.*/\\d+$", getRegex);

Matcher matcher = Pattern.compile(getRegex).matcher(methodPath);
Assert.assertEquals(true, matcher.matches());

2 个答案:

答案 0 :(得分:0)

正则表达式\d+$匹配1到N位数字,字符串以此结尾。例如,它与特征a不匹配。

您可以使用类似的代码:

Matcher matcher = Pattern.compile("/users/\\d+$").matcher(string);
if (matcher.find()) {
    ...
}

答案 1 :(得分:0)

我改进了我的方法。我现在正在搜索带有"/{"的模板表达式,以及带有"}/"的模板表达式的结尾。

public String GetRegex(String patternPath) {

    int indexOfOpen = patternPath.indexOf("/{");
    if (indexOfOpen < 0) {
        return patternPath;
    } else {
        int indexOfClose = patternPath.indexOf("}/");
        if(indexOfClose < 0){
            if(patternPath.substring(patternPath.length() - 1).equals("}")){
                indexOfClose = patternPath.length() - 1;
            }
            else{
                return patternPath;
            }
        }

        int indexOfRegexStart = patternPath.indexOf(":", indexOfOpen);
        if (indexOfRegexStart < 0 || indexOfRegexStart > indexOfClose) {
            patternPath = patternPath.substring(0, indexOfOpen + 1) + ".*" + patternPath.substring(indexOfClose + 1, patternPath.length());
        } else {
            patternPath = patternPath.substring(0, indexOfOpen + 1)
                    + patternPath.substring(indexOfRegexStart + 1, indexOfClose).trim()
                    + patternPath.substring(indexOfClose + 1, patternPath.length());
        }

        return GetRegex(patternPath);
    }
}

测试:

String itemPath = "/users/{userid}/{userId2 : \\d+:{$}/{userid3}/{userid4 : [:]}/{userId5}/{userId6 : [8]}";
String getRegex = GetRegex(itemPath);
Assert.assertEquals( "/users/.*/\\d+:{$/.*/[:]/.*/[8]", getRegex);