下面列出了org.json.simple.JSONArray#toArray ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public Map<String, List<Entity>> getEntities(final String question) {
HashMap<String, List<Entity>> tmp = new HashMap<>();
try {
String JSONOutput = doTASK(question);
JSONParser parser = new JSONParser();
JSONObject jsonObject = (JSONObject) parser.parse(JSONOutput);
JSONArray resources = (JSONArray) jsonObject.get("Resources");
if (resources != null) {
ArrayList<Entity> tmpList = new ArrayList<>();
for (Object res : resources.toArray()) {
JSONObject next = (JSONObject) res;
Entity ent = new Entity();
ent.setOffset(Integer.valueOf((String) next.get("@offset")));
ent.setLabel((String) next.get("@surfaceForm"));
String uri = ((String) next.get("@URI")).replaceAll(",", "%2C");
ent.getUris().add(new ResourceImpl(uri));
for (String type : ((String) next.get("@types")).split(",")) {
ent.getPosTypesAndCategories().add(new ResourceImpl(type));
}
tmpList.add(ent);
}
tmp.put("en", tmpList);
}
} catch (IOException | ParseException e) {
log.error("Could not call Spotlight for NER/NED", e);
}
return tmp;
}
@Override
public Map<String, List<Entity>> getEntities(final String question) {
HashMap<String, List<Entity>> tmp = new HashMap<>();
try {
String foxJSONOutput = doTASK(question);
JSONParser parser = new JSONParser();
JSONObject jsonObject = (JSONObject) parser.parse(foxJSONOutput);
JSONArray resources = (JSONArray) jsonObject.get("Resources");
if (resources != null) {
ArrayList<Entity> tmpList = new ArrayList<>();
for (Object res : resources.toArray()) {
JSONObject next = (JSONObject) res;
Entity ent = new Entity();
ent.setOffset(Integer.valueOf((String) next.get("@offset")));
ent.setLabel((String) next.get("@surfaceForm"));
String uri = ((String) next.get("@URI")).replaceAll(",", "%2C");
ent.getUris().add(new ResourceImpl(uri));
for (String type : ((String) next.get("@types")).split(",")) {
ent.getPosTypesAndCategories().add(new ResourceImpl(type));
}
tmpList.add(ent);
}
tmp.put("en", tmpList);
}
} catch (IOException | ParseException e) {
log.error("Could not call Spotlight for NER/NED", e);
}
return tmp;
}
protected static void assertMessagesLessSevereThan(
JSONArray messages, MessageLevel severity) {
for (Object m : messages.toArray()) {
Object level = ((JSONObject) m).get("level");
assertTrue(((Long) level).longValue() < severity.ordinal());
}
}
@SuppressWarnings("unchecked")
private JSONArray skipNullResults(JSONArray source, String propertyName) {
JSONArray result = new JSONArray();
for (Object item : source.toArray()) {
if (((JSONObject) item).get(propertyName) == null) {
continue;
}
result.add(item);
}
return result;
}
@SuppressWarnings("unchecked")
private JSONArray skipNullResults(JSONArray source, String propertyName) {
JSONArray result = new JSONArray();
for (Object item : source.toArray()) {
if (((JSONObject) item).get(propertyName) == null) {
continue;
}
result.add(item);
}
return result;
}
private static Result compareJSONArray(Result result, Object key, JSONArray source, JSONArray toBeCompared) {
if (source == toBeCompared) {
// nullチェック
return result;
}
if (null == toBeCompared) {
result.put(key,
toBeCompared,
String.format("Size of JSONArray [%s] is different. expected[%d], target[null]", key,
source.size()));
}
Object[] expectedArray = source.toArray();
Object[] targetArray = toBeCompared.toArray();
Arrays.sort(expectedArray);
Arrays.sort(targetArray);
if (expectedArray.length != targetArray.length) {
result.put(key,
toBeCompared,
String.format("Size of JSONArray [%s] is different. expected[%d], target[%d]", key,
source.size(),
toBeCompared.size()));
return result;
}
for (int i = 0; i < expectedArray.length; i++) {
Object expected2 = expectedArray[i];
Object target2 = targetArray[i];
if (expected2 instanceof JSONObject && target2 instanceof JSONObject) {
compareJSON(result, key, (JSONObject) expected2, (JSONObject) target2);
} else if (!expected2.equals(target2)) {
result.put(key,
toBeCompared,
String.format("Value of target of key[%s] does "
+ "not have the same value as source JSON. orignal: [%s], target[%s]",
key, source, toBeCompared));
}
}
return result;
}
/**
*
* @param inputText
* with encoded entities,e.g.,
* "<entity> Barack </entity> meets <entity>Angela</entity>"
* @return map of string to disambiguated URL
* @throws ParseException
* @throws IOException
*/
public HashMap<String, String> runDisambiguation(String inputText) throws ParseException, IOException {
String urlParameters = "text=" + URLEncoder.encode(inputText, "UTF-8");
urlParameters += "&type=agdistis";
// change this URL to https://agdistis.demos.dice-research.org/api/zh_cn/ to use
// chinese endpoint
URL url = new URL("https://agdistis.demos.dice-research.org/api/en/");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", String.valueOf(urlParameters.length()));
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
InputStream inputStream = connection.getInputStream();
InputStreamReader in = new InputStreamReader(inputStream);
BufferedReader reader = new BufferedReader(in);
StringBuilder sb = new StringBuilder();
while (reader.ready()) {
sb.append(reader.readLine());
}
wr.close();
reader.close();
connection.disconnect();
String agdistis = sb.toString();
JSONParser parser = new JSONParser();
JSONArray resources = (JSONArray) parser.parse(agdistis);
HashMap<String, String> tmp = new HashMap<String, String>();
for (Object res : resources.toArray()) {
JSONObject next = (JSONObject) res;
String namedEntity = (String) next.get("namedEntity");
String disambiguatedURL = (String) next.get("disambiguatedURL");
tmp.put(namedEntity, disambiguatedURL);
}
return tmp;
}
/**
* This method will retrieve KeyTemplates
*
* @return String object array which contains Blocking conditions.
*/
private String[] retrieveKeyTemplateData() {
try {
String url = getEventHubConfiguration().getServiceUrl() + "/keyTemplates";
byte[] credentials = Base64.encodeBase64(
(getEventHubConfiguration().getUsername() + ":" + getEventHubConfiguration().getPassword())
.getBytes(StandardCharsets.UTF_8));
HttpGet method = new HttpGet(url);
method.setHeader("Authorization", "Basic " + new String(credentials, StandardCharsets.UTF_8));
URL keyMgtURL = new URL(url);
int keyMgtPort = keyMgtURL.getPort();
String keyMgtProtocol = keyMgtURL.getProtocol();
HttpClient httpClient = APIUtil.getHttpClient(keyMgtPort, keyMgtProtocol);
HttpResponse httpResponse = null;
int retryCount = 0;
boolean retry;
do {
try {
httpResponse = httpClient.execute(method);
retry = false;
} catch (IOException ex) {
retryCount++;
if (retryCount < keyTemplateRetrievalRetries) {
retry = true;
log.warn("Failed retrieving throttling data from remote endpoint: " + ex.getMessage()
+ ". Retrying after " + keyTemplateRetrievalTimeoutInSeconds + " seconds...");
Thread.sleep(keyTemplateRetrievalTimeoutInSeconds * 1000);
} else {
throw ex;
}
}
} while(retry);
String responseString = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
if (responseString != null && !responseString.isEmpty()) {
JSONArray jsonArray = (JSONArray) new JSONParser().parse(responseString);
return (String[]) jsonArray.toArray(new String[jsonArray.size()]);
}
} catch (IOException | InterruptedException | ParseException e) {
log.error("Exception when retrieving throttling data from remote endpoint ", e);
}
return null;
}