import java.net.HttpURLConnection;
import java.lang.StringBuffer;
import java.util.List;
-import java.util.LinkedList;
import java.util.Iterator;
import java.util.Map;
import java.util.HashMap;
public class GatewayRequest extends HttpRequest {
- private List responseList;
+ private boolean readComplete;
public GatewayRequest(HttpConnection conn, String service, Method method) {
super(conn, service, method);
- responseList = new LinkedList(); // TODO
+ readComplete = false;
}
public GatewayRequest send() {
try {
+
String postData = compilePostData(service, method);
urlConn = (HttpURLConnection) httpConn.url.openConnection();
wr.flush();
wr.close();
- } catch (Exception ex) { // TODO inspect more closely
- ex.printStackTrace();
+ } catch (java.io.IOException ex) {
+ failed = true;
+ failure = ex;
}
return this;
public Object recv() {
- if (complete) return null;
-
- Object payload = null;
- StringBuffer readBuf = new StringBuffer();
+ if (readComplete)
+ return nextResponse();
try {
+
InputStream netStream = new BufferedInputStream(urlConn.getInputStream());
+ StringBuffer readBuf = new StringBuffer();
int bytesRead = 0;
byte[] buffer = new byte[1024];
String status = result.get("status").toString();
if (!"200".equals(status)) {
- // throw exception
+ failed = true;
+ // failure = <some new exception>
}
- payload = result.get("payload");
-
+ // gateway always returns a wrapper array with the full results set
+ responseList = (List) result.get("payload");
- } catch (Exception ex) { // TODO inspect more closely
- ex.printStackTrace();
+ } catch (java.io.IOException ex) {
+ failed = true;
+ failure = ex;
}
- complete = true;
- return payload;
+ readComplete = true;
+ return nextResponse();
}
private String compilePostData(String service, Method method) {
protected HttpURLConnection urlConn;
protected HttpConnection httpConn;
protected HttpRequestHandler handler;
- private List<Object> responseList;
- protected boolean complete = false;
+ protected List<Object> responseList;
+ protected Exception failure;
+ protected boolean failed;
+ protected boolean complete;
public HttpRequest() {
+ failed = false;
+ complete = false;
+ handler = null;
+ urlConn = null;
}
public HttpRequest(HttpConnection conn, String service, Method method) {
- this.handler = null;
- this.urlConn = null;
+ this();
this.httpConn = conn;
this.service = service;
this.method = method;
protected List responses() {
return responseList;
}
+
+ protected Object nextResponse() {
+ if (complete || failed) return null;
+ if (responseList.size() > 0)
+ return responseList.remove(0);
+ return null;
+ }
+
+ public Exception getFailure() {
+ return failure;
+ }
public abstract HttpRequest send();