nlphub/src/main/java/org/gcube/data/analysis/nlphub/legacy/AsyncHttpRequest.java

118 lines
2.8 KiB
Java
Executable File

package org.gcube.data.analysis.nlphub.legacy;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import org.gcube.data.analysis.nlphub.nlp.NlpParameter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class AsyncHttpRequest extends Thread {
private String baseUrl, finalUrl, result, method;
private ArrayList<NlpParameter> parameters;
private static final Logger logger = LoggerFactory.getLogger(AsyncHttpRequest.class);
protected long elapsedTime;
public AsyncHttpRequest() {
this.baseUrl = null;
this.parameters = null;
this.method = "GET";
finalUrl = null;
elapsedTime = 0;
}
public AsyncHttpRequest(String baseUrl, String method, ArrayList<NlpParameter> parameters) {
this.baseUrl = baseUrl;
this.parameters = parameters;
if (method == null)
this.method = "GET";
else
this.method = (method.equalsIgnoreCase("GET") || method.equalsIgnoreCase("POST")) ? method : "GET";
setFinalUrl();
elapsedTime = 0;
}
public void run() {
elapsedTime = System.currentTimeMillis();
if (finalUrl == null)
finalUrl = baseUrl;
HttpURLConnection connection = null;
BufferedReader r = null;
try {
URL url = new URL(finalUrl);
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestMethod(method);
r = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line = "";
result = "";
while (line != null) {
line = r.readLine();
if (line != null)
result += line.trim();
}
asyncHttpRequestCallback();
} catch (Exception e) {
logger.error(e.getLocalizedMessage(),e);
asyncHttpRequestCallback();
} finally {
try {
if (r != null)
r.close();
if (connection != null)
connection.disconnect();
} catch (Exception e) {
logger.error(e.getLocalizedMessage(),e);
}
}
}
public String getResult() {
return result;
}
public void asyncHttpRequestCallback() {
elapsedTime = System.currentTimeMillis() - elapsedTime;
}
public void setBaseUrl(String baseUrl) {
this.baseUrl = baseUrl;
}
public void setMethod(String method) {
this.method = method;
}
public void setParameters(ArrayList<NlpParameter> parameters) {
this.parameters = parameters;
}
private void setFinalUrl() {
finalUrl = baseUrl;
if (parameters != null) {
if (finalUrl.indexOf("?") < 0)
finalUrl += "?";
for (NlpParameter p : parameters) {
try {
finalUrl += p.getName() + "=" + URLEncoder.encode((String) p.getValue(), "UTF-8");
finalUrl += "&";
} catch (Exception e) {
logger.error(e.getLocalizedMessage(),e);
}
}
finalUrl = finalUrl.substring(0, finalUrl.length() - 1);
}
}
}