/**Query the API and returns the list of expansions. Update the cache.
* @param abbrev lowercase abbreviation.
* @throws Exception
*/
private synchronized String[] queryApi(String abbrev, int retryLeft)
throws Exception {
if (retryLeft < MAX_RETRY)
Thread.sleep(1000);
URL url = new URL(String.format("%s?uid=%s&tokenid=%s&term=%s",
API_URL, uid, tokenId, URLEncoder.encode(abbrev, "utf8")));
boolean cached = abbrToExpansion.containsKey(abbrev);
LOG.info("{} {}", cached ? "<cached>" : "Querying", url);
if (cached) return abbrToExpansion.get(abbrev);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setConnectTimeout(0);
connection.setRequestProperty("Accept", "*/*");
connection
.setRequestProperty("Content-Type", "multipart/form-data");
connection.setUseCaches(false);
if (connection.getResponseCode() != 200) {
Scanner s = new Scanner(connection.getErrorStream())
.useDelimiter("\\A");
LOG.error("Got HTTP error {}. Message is: {}",
connection.getResponseCode(), s.next());
s.close();
throw new RuntimeException("Got response code:"
+ connection.getResponseCode());
}
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc;
try {
doc = builder.parse(connection.getInputStream());
} catch (IOException e) {
LOG.error("Got error while querying: {}", url);
throw e;
}
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression resourceExpr = xpath.compile("//definition/text()");
NodeList resources = (NodeList) resourceExpr.evaluate(doc,
XPathConstants.NODESET);
Vector<String> resVect = new Vector<>();
for (int i=0; i<resources.getLength(); i++){
String expansion = resources.item(i).getTextContent().replace(String.valueOf((char) 160), " ").trim();
if (!resVect.contains(expansion))
resVect.add(expansion);
}
String[] res = resVect.toArray(new String[]{});
abbrToExpansion.put(abbrev, res);
increaseFlushCounter();
return res;
}
Stands4AbbreviationExpansion.java 文件源码
java
阅读 20
收藏 0
点赞 0
评论 0
项目:smaph
作者:
评论列表
文章目录