Example usage for com.google.gwt.xhr.client XMLHttpRequest DONE

List of usage examples for com.google.gwt.xhr.client XMLHttpRequest DONE

Introduction

In this page you can find the example usage for com.google.gwt.xhr.client XMLHttpRequest DONE.

Prototype

int DONE

To view the source code for com.google.gwt.xhr.client XMLHttpRequest DONE.

Click Source Link

Document

The DONE state is the state of the object when either the data transfer has been completed or something went wrong during the transfer (infinite redirects for instance).

Usage

From source file:com.badlogic.gdx.backends.gwt.preloader.AssetDownloader.java

License:Apache License

public void loadText(String url, final AssetLoaderListener<String> listener) {
    XMLHttpRequest request = XMLHttpRequest.create();
    request.setOnReadyStateChange(new ReadyStateChangeHandler() {
        @Override/*w  w w.  jav a  2 s  . co  m*/
        public void onReadyStateChange(XMLHttpRequest xhr) {
            if (xhr.getReadyState() == XMLHttpRequest.DONE) {
                if (xhr.getStatus() != 200) {
                    listener.onFailure();
                } else {
                    listener.onSuccess(xhr.getResponseText());
                }
            }
        }
    });
    setOnProgress(request, listener);
    request.open("GET", url);
    request.setRequestHeader("Content-Type", "text/plain; charset=utf-8");
    request.send();
}

From source file:com.badlogic.gdx.backends.gwt.preloader.AssetDownloader.java

License:Apache License

public void loadBinary(final String url, final AssetLoaderListener<Blob> listener) {
    XMLHttpRequest request = XMLHttpRequest.create();
    request.setOnReadyStateChange(new ReadyStateChangeHandler() {
        @Override//  w w  w  .  j av  a 2s.c  o  m
        public void onReadyStateChange(XMLHttpRequest xhr) {
            if (xhr.getReadyState() == XMLHttpRequest.DONE) {
                if (xhr.getStatus() != 200) {
                    listener.onFailure();
                } else {
                    Int8Array data = TypedArrays.createInt8Array(xhr.getResponseArrayBuffer());
                    listener.onSuccess(new Blob(data));
                }
            }
        }
    });
    setOnProgress(request, listener);
    request.open("GET", url);
    request.setResponseType(ResponseType.ArrayBuffer);
    request.send();
}

From source file:com.cgxlib.xq.client.plugins.deferred.PromiseReqBuilder.java

License:Apache License

/**
 * Using this constructor we access to some things in the xmlHttpRequest
 * which are not available in GWT, like adding progress handles or sending
 * javascript data (like forms in modern html5 file api).
 *//*from ww  w .j a va  2s .  c om*/
public PromiseReqBuilder(Settings settings) {
    String httpMethod = settings.getType();
    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 xq 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);
            }
        }
    });

    try {
        JsUtils.runJavascriptFunction(xmlHttpRequest, "send",
                isFormData ? data.getDataImpl() : settings.getDataString());
    } catch (JavaScriptException e) {
        onError(null, e);
    }
}

From source file:com.codenvy.plugin.contribution.client.steps.GenerateReviewFactoryStep.java

License:Open Source License

private void saveFactory(final FormData formData, final AsyncCallback<Factory> callback) {
    final String requestUrl = apiTemplate.saveFactory();

    final XMLHttpRequest xhr = XMLHttpRequest.create();
    xhr.open(HTTPMethod.POST, requestUrl);
    xhr.setRequestHeader(ACCEPT, APPLICATION_JSON);
    xhr.setOnReadyStateChange(new ReadyStateChangeHandler() {

        @Override/*from  w  w w .  j  a  v  a  2  s. c  o  m*/
        public void onReadyStateChange(final XMLHttpRequest request) {
            if (request.getReadyState() == XMLHttpRequest.DONE) {
                if (request.getStatus() == Response.SC_OK) {
                    request.clearOnReadyStateChange();
                    final String payLoad = request.getResponseText();
                    final Factory createdFactory = dtoFactory.createDtoFromJson(payLoad, Factory.class);

                    if (createdFactory.getId() == null || createdFactory.getId().isEmpty()) {
                        final ServiceError error = dtoFactory.createDtoFromJson(payLoad, ServiceError.class);
                        callback.onFailure(new Exception(error.getMessage()));
                    } else {
                        callback.onSuccess(createdFactory);
                    }
                } else {
                    final Response response = new ResponseImpl(request);
                    callback.onFailure(new ServerException(response));
                }
            }

        }
    });

    if (!sendFormData(xhr, formData)) {
        callback.onFailure(new Exception("Could not call service"));
    }
}

From source file:com.gwtpro.html5.fileapi.client.upload.UploadRequestBuilder.java

License:Apache License

/**
 * Sends a POST request based to upload a file, on the current builder
 * configuration.//from  w  w  w . j  av a  2  s  .com
 * 
 * @return a {@link UploadRequest} object that can be used to track the
 *         request
 * @throws RequestException
 *             if the call fails to initiate
 * @throws NullPointerException
 *             if a request callback has not been set
 */
public UploadRequest sendFile(File file) throws RequestException {
    if (this.callback == null) {
        throw new NullPointerException("callback has not been set");
    }
    XMLHttpRequest2 xmlHttpRequest = XMLHttpRequest2.create();
    final UploadRequest request = new UploadRequest(xmlHttpRequest, this.timeoutMillis, this.callback);
    // progress handler must be set before open!!!
    xmlHttpRequest.setOnUploadProgressHandler(new UploadProgressHandler() {

        @Override
        public void onProgress(int bytesUploaded) {
            UploadRequestBuilder.this.callback.onUploadProgress(request, bytesUploaded);
        }
    });
    try {
        if (this.user != null && this.password != null) {
            xmlHttpRequest.open("POST", this.url, this.user, this.password);
        } else if (this.user != null) {
            xmlHttpRequest.open("POST", this.url, this.user);
        } else {
            xmlHttpRequest.open("POST", this.url);
        }
    } catch (JavaScriptException e) {
        RequestPermissionException requestPermissionException = new RequestPermissionException(this.url);
        requestPermissionException.initCause(new RequestException(e.getMessage()));
        throw requestPermissionException;
    }
    if (this.headers != null) {
        for (Map.Entry<String, String> header : this.headers.entrySet()) {
            try {
                xmlHttpRequest.setRequestHeader(header.getKey(), header.getValue());
            } catch (JavaScriptException e) {
                throw new RequestException(e.getMessage());
            }
        }
    }
    xmlHttpRequest.setOnReadyStateChange(new ReadyStateChangeHandler() {

        public void onReadyStateChange(XMLHttpRequest xhr) {
            if (xhr.getReadyState() == XMLHttpRequest.DONE) {
                xhr.clearOnReadyStateChange();
                request.fireOnResponseReceived(UploadRequestBuilder.this.callback);
            }
        }
    });
    try {
        xmlHttpRequest.sendFile(file);
    } catch (JavaScriptException e) {
        throw new RequestException(e.getMessage());
    }
    return request;
}

From source file:com.vaadin.client.extensions.FileDropTargetConnector.java

License:Apache License

/**
 * Uploads a file from the waiting list in case there are no files being
 * uploaded.//  ww  w  .j  a v  a 2 s . co  m
 */
private void uploadNextFile() {
    Scheduler.get().scheduleDeferred(() -> {
        if (!uploading && uploadUrls.size() > 0) {
            uploading = true;
            String nextId = uploadUrls.keySet().stream().findAny().get();

            String url = uploadUrls.remove(nextId);
            File file = filesToUpload.remove(nextId);

            FileUploadXHR xhr = (FileUploadXHR) FileUploadXHR.create();
            xhr.setOnReadyStateChange(xmlHttpRequest -> {
                if (xmlHttpRequest.getReadyState() == XMLHttpRequest.DONE) {
                    // Poll server for changes
                    getRpcProxy(FileDropTargetRpc.class).poll();
                    uploading = false;
                    uploadNextFile();
                    xmlHttpRequest.clearOnReadyStateChange();
                }
            });
            xhr.open("POST", getConnection().translateVaadinUri(url));
            xhr.postFile(file);
        }
    });
}

From source file:forplay.html.HtmlAssetManager.java

License:Apache License

private void doXhr(final String fullPath, final ResourceCallback<String> callback) {
    XMLHttpRequest xhr = XMLHttpRequest.create();
    xhr.setOnReadyStateChange(new ReadyStateChangeHandler() {
        @Override//from w ww  .jav  a  2s.  c  om
        public void onReadyStateChange(XMLHttpRequest xhr) {
            int readyState = xhr.getReadyState();
            if (readyState == XMLHttpRequest.DONE) {
                int status = xhr.getStatus();
                // status code 0 will be returned for non-http requests, e.g. file://
                if (status != 0 && (status < 200 || status >= 400)) {
                    ForPlay.log().error("xhr::onReadyStateChange[" + fullPath + "](readyState = " + readyState
                            + "; status = " + status + ")");
                    callback.error(
                            new RuntimeException("Error getting " + fullPath + " : " + xhr.getStatusText()));
                } else {
                    if (LOG_XHR_SUCCESS) {
                        ForPlay.log().debug("xhr::onReadyStateChange[" + fullPath + "](readyState = "
                                + readyState + "; status = " + status + ")");
                    }
                    callback.done(xhr.getResponseText());
                }
            }
        }
    });

    if (LOG_XHR_SUCCESS) {
        ForPlay.log().debug("xhr.open('GET', '" + fullPath + "')...");
    }
    xhr.open("GET", fullPath);

    if (LOG_XHR_SUCCESS) {
        ForPlay.log().debug("xhr.send()...");
    }
    xhr.send();
}

From source file:forplay.html.HtmlNet.java

License:Apache License

public void get(String url, final Callback callback) {
    try {/*from  w  ww .  j  ava2 s.c  o  m*/
        XMLHttpRequest xhr = XMLHttpRequest.create();
        xhr.open("GET", url);
        xhr.setOnReadyStateChange(new ReadyStateChangeHandler() {
            @Override
            public void onReadyStateChange(XMLHttpRequest xhr) {
                if (xhr.getReadyState() == XMLHttpRequest.DONE) {
                    if (xhr.getStatus() >= 400) {
                        callback.failure(new RuntimeException("Bad HTTP status code: " + xhr.getStatus()));
                    } else {
                        callback.success(xhr.getResponseText());
                    }
                }
            }
        });
        xhr.send();
    } catch (Exception e) {
        callback.failure(e);
    }
}

From source file:forplay.html.HtmlNet.java

License:Apache License

public void post(String url, String data, final Callback callback) {
    try {/* w ww  .  j  a  v  a  2  s  .  c om*/
        XMLHttpRequest xhr = XMLHttpRequest.create();
        xhr.open("POST", url);
        xhr.setOnReadyStateChange(new ReadyStateChangeHandler() {
            @Override
            public void onReadyStateChange(XMLHttpRequest xhr) {
                if (xhr.getReadyState() == XMLHttpRequest.DONE) {
                    if (xhr.getStatus() >= 400) {
                        callback.failure(new RuntimeException("Bad HTTP status code: " + xhr.getStatus()));
                    } else {
                        callback.success(xhr.getResponseText());
                    }
                }
            }
        });
        xhr.send(data);
    } catch (Exception e) {
        callback.failure(e);
    }
}

From source file:net.npe.gwt.xhr.client.ArrayBufferRequest.java

License:MIT License

public ArrayBufferRequest(String url, final Handler handler) {
    xhr = XMLHttpRequest.create();/*from  w  ww.  j av  a  2  s.c om*/
    xhr.setResponseType(ResponseType.ArrayBuffer);
    xhr.setOnReadyStateChange(new ReadyStateChangeHandler() {
        @Override
        public void onReadyStateChange(XMLHttpRequest xhr) {
            if (xhr.getReadyState() == XMLHttpRequest.DONE) {
                if (xhr.getStatus() >= 400) {
                    if (handler != null)
                        handler.onFailure();
                } else {
                    if (handler != null)
                        handler.onSuccess(xhr.getResponseArrayBuffer());
                }
            }
        }
    });
    xhr.open("GET", url);
}