package com.yourcompany.invoicing.validators;
import javax.validation.*;
import javax.ws.rs.client.*; // 使用 JAX-RS
import com.yourcompany.invoicing.annotations.*;
import org.apache.commons.logging.*; // 使用日志
import org.openxava.util.*;
public class ISBNValidator
implements ConstraintValidator<ISBN, Object> {
private static Log log = LogFactory.getLog(ISBNValidator.class); // 将日志实例化
private static org.apache.commons.validator.routines.ISBNValidator
validator =
new org.apache.commons.validator.routines.ISBNValidator();
public void initialize(ISBN isbn) {
}
public boolean isValid(Object value, ConstraintValidatorContext context) {
if (Is.empty(value)) return true;
if (!validator.isValid(value.toString())) return false;
return isbnExists(value); // 在这里调用 REST
}
private boolean isbnExists(Object isbn) {
try {
// 这里我们使用 JAX-RS 调用 REST 服务
String response = ClientBuilder.newClient()
.target("http://openlibrary.org/") // 站点
.path("/api/books") // 服务的路径
.queryParam("jscmd", "data") // 参数
.queryParam("format", "json")
.queryParam("bibkeys", "ISBN:" + isbn) // ISBN 是一个参数
.request()
.get(String.class); // 带有 JSON 的字符串
return !response.equals("{}"); // JSON 是空的吗?对于我们的情况来说已经足够了。
}
catch (Exception ex) {
log.warn("无法连线至 openlibrary.org " +
"验证 ISBN. 验证失败", ex);
return false; // 如果有错误,验证则失败
}
}
}
我们只需打开附有 ISBN 作为请求参数的网址。如果生成的 JSON 是空的,也就是说 {},搜索将失败,相反的话我们则找到这本书。对于这种情况,将 JSON 作为字符串进行简单比较是最简单的方法,不过 JAX-RS 可以将 JSON 解析为您自己的类(例如 Book)的 Java 对象,并填充相应的属性,只需使用 .get (Book.class) 而不是 .get(String.class) 这是在调用的最后一行。