String url = settings.getUrl();
IsProperties data = settings.getData();
String ctype = settings.getContentType();
Boolean isFormData = data != null && data.getDataImpl() instanceof JavaScriptObject && JsUtils.isFormData(data.<JavaScriptObject>getDataImpl());
XMLHttpRequest xmlHttpRequest = XMLHttpRequest.create();
try {
if (settings.getUsername() != null && settings.getPassword() != null) {
xmlHttpRequest.open(httpMethod, url, settings.getUsername(), settings.getPassword());
} else if (settings.getUsername() != null) {
xmlHttpRequest.open(httpMethod, url, settings.getUsername());
} else {
xmlHttpRequest.open(httpMethod, url);
}
} catch (JavaScriptException e) {
RequestPermissionException requestPermissionException = new RequestPermissionException(url);
requestPermissionException.initCause(new RequestException(e.getMessage()));
onError(null, e);
return;
}
JsUtils.prop(xmlHttpRequest, "onprogress", JsUtils.wrapFunction(new Function() {
public void f() {
JsCache p = arguments(0);
double total = p.getDouble("total");
double loaded = p.getDouble("loaded");
double percent = loaded == 0 ? 0 : total == 0 ? 100 : (100 * loaded / total);
dfd.notify(total, loaded, percent, "download");
}
}));
JavaScriptObject upload = JsUtils.prop(xmlHttpRequest, "upload");
JsUtils.prop(upload, "onprogress", JsUtils.wrapFunction(new Function() {
public void f() {
JsCache p = arguments(0);
double total = p.getDouble("total");
double loaded = p.getDouble("loaded");
double percent = 100 * loaded / total;
dfd.notify(total, loaded, percent, "upload");
}
}));
IsProperties headers = settings.getHeaders();
if (headers != null) {
for (String headerKey : headers.getFieldNames()) {
xmlHttpRequest.setRequestHeader(headerKey, String.valueOf(headers.get(headerKey)));
}
}
if (data != null && !isFormData && !"GET".equalsIgnoreCase(httpMethod)) {
xmlHttpRequest.setRequestHeader("Content-Type", ctype);
}
// Using gQuery to set credentials since this method was added in 2.5.1
// xmlHttpRequest.setWithCredentials(true);
JsUtils.prop(xmlHttpRequest, "withCredentials", settings.getWithCredentials());
final Request request = createRequestVltr(xmlHttpRequest, settings.getTimeout(), this);
xmlHttpRequest.setOnReadyStateChange(new ReadyStateChangeHandler() {
public void onReadyStateChange(XMLHttpRequest xhr) {
if (xhr.getReadyState() == XMLHttpRequest.DONE) {
xhr.clearOnReadyStateChange();
fireOnResponseReceivedVltr(request, PromiseReqBuilder.this);
}