【发布时间】:2013-03-24 18:23:14
【问题描述】:
我想知道是否有任何不错的简单方法可以使用 Java 验证 Diameter URI(如下所述)?
Note, a Diameter URI must have one of the forms:
aaa://FQDN[:PORT][;transport=TRANS][;protocol=PROT]
aaas://FQDN[:PORT][;transport=TRANS][;protocol=PROT]
The FQDN (mandatory) has to be replaced with the fully qualified host name (or IP), the PORT (optional, default is 3868) with the port number, TRANS (optional) with the transport protocol (can be TCP or SCTP) and PROT (optional) with diameter.
Some examples of the acceptable forms are:
aaa://server.com
aaa://127.0.0.1
aaa://server.com:1234
aaas://server.com:1234;transport=tcp
aaas://[::1]
aaas://[::1]:1234
aaas://[::1]:1234;transport=tcp;protocol=diameter
Note, as shown above, if using an IPv6 address, the address must be placed in box brackets, whereas the port number (if specified), with its colon separator, should be outside of the brackets.
我认为使用正则表达式执行此操作会非常混乱且难以理解,而且我见过的其他不使用正则表达式的示例看起来也很尴尬(例如https://code.google.com/p/cipango/source/browse/trunk/cipango-diameter/src/main/java/org/cipango/diameter/util/AAAUri.java?r=763)。
所以想知道是否有更好的方法来做到这一点,例如类似于 URI 验证器库,它采用一些规则(例如上面的 Diameter URI 规则),然后将它们应用于某些输入以验证它?
我也查看了 Google Guava 库,看看是否有任何帮助,但我看不到任何东西。
非常感谢!
【问题讨论】:
-
您是否尝试过简单地使用
java.net.URI构造函数,如果URI 无效,它将抛出URISyntaxException? -
是的,java.net.URI 的规则与我的用例略有不同。例如,接受新的 URI("127.0.0.1"),但这不是有效的直径 URI(开始时没有方案部分)
-
为什么不用正则表达式解析出 FQDN:
#aaas?://([^;]+)(;transport=\w+)?(;protocol=\w+)?#,然后在新的 URI 构造函数中使用子组 1 将其验证为 FQDN? -
java.net.URI仍然可以提供帮助:您只需要检查该方案是否为非空。这很方便,因为您已经想检查方案是“aaa”还是“aaas”。也就是说,您最终可能需要回退到正则表达式:Diameter URL 语法是一种奇怪的语法,不符合我所知道的任何 four URL 规范,所以标准 URL 类不太可能按照您需要的方式对其进行拆分。
标签: java regex uri guava diameter-protocol