Map<String,String> requestHeaders = new HashMap();
Map responseHeaders = new HashMap();
@Override
public Object get(String name, Scriptable start) {
if("open".equals(name)){
return new PersevereNativeFunction(){
@Override
public Object call(Context cx, Scriptable scope, Scriptable thisObj, Object[] args) {
methodName = (String) args[0];
targetUrl = (String) args[1];
if(!targetUrl.matches("\\w+tps?:/.*"))
targetUrl = localURI + (targetUrl.startsWith("/") ? targetUrl.substring(1) : targetUrl);
requestHeaders.put("Accept", "*/*");
responseText = null;
return null;
}
};
}
if("send".equals(name)){
return new PersevereNativeFunction(){
@Override
public Object call(Context cx, Scriptable scope, Scriptable thisObj, Object[] args) {
responseText = null;
HttpMethod method = null;
if("GET".equals(methodName)){
method = new GetMethod(targetUrl);
}
else if("PUT".equals(methodName)){
method = new PutMethod(targetUrl);
((PutMethod)method).setRequestBody((String) args[0]);
}
else if("POST".equals(methodName)){
method = new PostMethod(targetUrl);
((PostMethod)method).setRequestBody((String) args[0]);
}
else if("DELETE".equals(methodName)){
method = new DeleteMethod(targetUrl);
}
else
throw new RuntimeException("Unknown method for XMLHttpRequest");
try {
for(Map.Entry<String,String> header : requestHeaders.entrySet())
method.setRequestHeader(header.getKey(), header.getValue());
status = httpClient.executeMethod(method);
for(Header header : method.getResponseHeaders()){
responseHeaders.put(header.getName(), header.getValue());
}
responseText = slurp(method.getResponseBodyAsStream());
} catch (HttpException e) {
throw ScriptRuntime.constructError("Error", e.getMessage());
} catch (IOException e) {
throw ScriptRuntime.constructError("Error", e.getMessage());
}
finally {
method.releaseConnection();
}
readyState = 4;
Object readyStateChangeHandler = XMLHttpRequest.this.get("onreadystatechange",XMLHttpRequest.this);
if(readyStateChangeHandler instanceof Function){
((Function)readyStateChangeHandler).call(cx, scope, thisObj, new Object[0]);
}
return null;
}
};
}
if("readyState".equals(name))
return readyState;
if("status".equals(name))
return status;
if("getResponseHeader".equals(name)){
return new PersevereNativeFunction(){
@Override
public Object call(Context cx, Scriptable scope, Scriptable thisObj, Object[] args) {
return responseHeaders.get(args[0]);
}
};
}
if("setRequestHeader".equals(name)){
return new PersevereNativeFunction(){
@Override
public Object call(Context cx, Scriptable scope, Scriptable thisObj, Object[] args) {
return requestHeaders.put(args[0].toString(),ScriptRuntime.toString(args[1]));
}
};
}
if("abort".equals(name)){
// it's always synchronous, not sure we need to do anything here
return new PersevereNativeFunction(){
@Override
public Object call(Context cx, Scriptable scope, Scriptable thisObj, Object[] args) {
return null;
}