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

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

Introduction

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

Prototype

public abstract String getResponseText();

Source Link

Document

Gets the response text.

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  .j a va2  s .  c o 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.BinaryLoader.java

License:Apache License

public BinaryLoader(String url, LoaderCallback<Blob> callback) {
    this.callback = callback;
    XMLHttpRequest request = XMLHttpRequest.create();
    request.setOnReadyStateChange(new ReadyStateChangeHandler() {
        @Override//from  ww w  .j a  va 2 s. co  m
        public void onReadyStateChange(XMLHttpRequest xhr) {
            if (xhr.getReadyState() == 4) {
                int status = xhr.getStatus();
                if (status != 200) {
                    BinaryLoader.this.callback.error();
                } else {
                    BinaryLoader.this.callback.success(new Blob(xhr.getResponseText()));
                }
            }
        }
    });
    overrideMimeType(request, "text/plain; charset=x-user-defined");
    request.open("GET", url);
    request.send();
}

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/*w w w  .  j ava 2  s. c om*/
        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.google.speedtracer.client.SymbolServerController.java

License:Apache License

private void init() {
    Xhr.get(symbolManifestUrl.getUrl(), new XhrCallback() {

        public void onFail(XMLHttpRequest xhr) {
            // Let pending requests know that the manifest failed to load.
            for (PendingRequest request : pendingRequests) {
                request.callback.onSymbolsFetchFailed(ERROR_MANIFEST_NOT_LOADED);
            }/*from w w  w  .  j  a  va 2 s  .c o m*/
            cancelPendingRequests();
            SymbolServerService.unregisterSymbolServerController(mainResourceUrl);
            if (ClientConfig.isDebugMode()) {
                Logging.getLogger().logText("Fetching manifest " + symbolManifestUrl.getUrl() + " failed.");
            }
        }

        public void onSuccess(XMLHttpRequest xhr) {
            // TODO (jaimeyap): This needs to be validated... and we should handle
            // any parsing errors as well.
            try {
                SymbolServerController.this.symbolServerManifest = JSON.parse(xhr.getResponseText()).cast();
            } catch (JSONParseException jpe) {
                if (ClientConfig.isDebugMode()) {
                    Logging.getLogger().logText("Unable to parse manifest for " + symbolManifestUrl.getUrl());
                }
                onFail(xhr); // Treat an invalid manifest like a network failure.
                return;
            }

            SymbolServerController.this.manifestLoaded = true;
            // Now service all the pending requests.
            while (!pendingRequests.isEmpty()) {
                serviceRequest(pendingRequests.remove(0));
            }
            if (ClientConfig.isDebugMode()) {
                Logging.getLogger().logText("Manifest " + symbolManifestUrl.getUrl() + " loaded.");
            }
        }
    });
}

From source file:com.google.speedtracer.client.SymbolServerController.java

License:Apache License

private void serviceRequest(PendingRequest request) {
    assert manifestLoaded : "Manifest should be loaded";

    final ResourceSymbolInfo resourceSymbolInfo = lookupEntryInManifest(request.resourceUrl);
    final Callback callback = request.callback;
    if (resourceSymbolInfo == null) {
        if (ClientConfig.isDebugMode()) {
            Logging.getLogger().logText("Resymbolization failed: No symbol info for " + request.resourceUrl);
        }//www.j  a  va 2s  .  c o m
        callback.onSymbolsFetchFailed(ERROR_SYMBOL_FETCH_FAIL);
        return;
    }

    final String symbolMapUrl = resourceSymbolInfo.getSymbolMapUrl();
    JsSymbolMap symbolMap = get(symbolMapUrl);
    // We only want to request and parse for symbolMaps we havn't already
    // parsed.
    if (symbolMap == null) {
        // Create the XhrCallback to service this request.
        XhrCallback xhrCallback = new XhrCallback() {

            public void onFail(XMLHttpRequest xhr) {
                callback.onSymbolsFetchFailed(ERROR_SYMBOL_FETCH_FAIL);
                dequeuePendingXhrs(symbolMapUrl, xhr, false);
                if (ClientConfig.isDebugMode()) {
                    Logging.getLogger().logText("Fetching symbol map: " + symbolMapUrl + " failed.");
                }
            }

            public void onSuccess(XMLHttpRequest xhr) {
                // Double check that another XHR didnt pull it down and parse it.
                JsSymbolMap fetchedSymbolMap = get(symbolMapUrl);
                if (fetchedSymbolMap == null) {
                    fetchedSymbolMap = JsSymbolMap.parse(resourceSymbolInfo.getSourceServer(),
                            resourceSymbolInfo.getSourceViewerServer(), resourceSymbolInfo.getType(),
                            xhr.getResponseText());
                    put(symbolMapUrl, fetchedSymbolMap);
                }
                callback.onSymbolsReady(fetchedSymbolMap);
                dequeuePendingXhrs(symbolMapUrl, xhr, true);
                if (ClientConfig.isDebugMode()) {
                    Logging.getLogger().logText("Fetched symbol map: " + symbolMapUrl);
                }
            }

            private void dequeuePendingXhrs(String symbolMapUrl, XMLHttpRequest xhr, boolean success) {
                List<XhrCallback> callbacks = queuedSymbolMapRequests.get(symbolMapUrl);
                if (callbacks != null) {
                    while (!callbacks.isEmpty()) {
                        XhrCallback callback = callbacks.remove(0);
                        if (success) {
                            callback.onSuccess(xhr);
                        } else {
                            callback.onFail(xhr);
                        }
                    }
                }
            }
        };

        // Check to see if we have a request in flight.
        List<XhrCallback> requestCallbacks = queuedSymbolMapRequests.get(symbolMapUrl);
        if (requestCallbacks == null) {
            // Make an entry indicating a request is in flight.
            queuedSymbolMapRequests.put(symbolMapUrl, new ArrayList<XhrCallback>());
            if (ClientConfig.isDebugMode()) {
                Logging.getLogger().logText(
                        "Fetching symbol map URL: " + symbolManifestUrl.getResourceBase() + symbolMapUrl);
            }
            Xhr.get(symbolManifestUrl.getResourceBase() + symbolMapUrl, xhrCallback);
        } else {
            // There are pending XHRs out. Which means that we should just queue
            // this request.
            requestCallbacks.add(xhrCallback);
        }
    } else {
        // We have already fetched this and parsed it before. Send it to the
        // callback.
        callback.onSymbolsReady(symbolMap);
    }
}

From source file:com.googlecode.gwtquake.client.GwtResourceLoaderImpl.java

License:Open Source License

public void loadResourceAsync(final String path, final ResourceLoader.Callback callback) {
    XMLHttpRequest req = XMLHttpRequest.create();

    final Exception e = new Exception();
    final int mySequenceNumber = freeSequenceNumber++;

    req.setOnReadyStateChange(new ReadyStateChangeHandler() {
        boolean receivingMsg;

        public void onReadyStateChange(final XMLHttpRequest xhr) {
            if (xhr.getReadyState() == 3 && !receivingMsg) {
                Com.Printf("Receiving #" + mySequenceNumber + ": " + path + "\n");
                receivingMsg = true;/*from  ww w  .jav a2 s .com*/
            } else if (xhr.getReadyState() == 4) {
                if (mySequenceNumber < ignoreSequenceNumbersBelow) {
                    Com.Printf("Ignoring outdated response #" + mySequenceNumber + ": " + path + "\n");
                } else {
                    String response;
                    if (xhr.getStatus() != 200) {
                        Com.Printf("Failed to load file #" + mySequenceNumber + ": " + path + " status: "
                                + xhr.getStatus() + "/" + xhr.getStatusText() + "\n");
                        ResourceLoader.fail(new IOException("status = " + xhr.getStatus()));
                        response = null;
                    } else {
                        response = xhr.getResponseText();
                        Com.Printf("Received response #" + mySequenceNumber + ": " + path + "\r");
                    }
                    readyList.add(0, new ResponseHandler(mySequenceNumber, callback, response));
                    if (mySequenceNumber == currentSequenceNumber) {
                        processReadyList();
                    }
                }
            }
        }
    });

    Com.Printf("Requesting: " + path + "\n");

    overrideMimeType(req, "text/plain; charset=x-user-defined");
    req.open("GET", "/baseq2/" + path);
    req.send();
}

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 ww w  .j  ava  2 s  .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  av a2  s .co 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 {//from   w w  w .  j av a  2  s. c o  m
        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:io.reinert.requestor.RequestDispatcherImpl.java

License:Apache License

private <D> RequestCallback getRequestCallback(final Request request, final XMLHttpRequest xhr,
        final Deferred<D> deferred, final Class<D> resolveType, final Class<?> parametrizedType) {
    return new RequestCallback() {
        public void onResponseReceived(com.google.gwt.http.client.Request gwtRequest,
                com.google.gwt.http.client.Response gwtResponse) {
            final String responseType = xhr.getResponseType();

            final Payload payload = responseType.isEmpty() || responseType.equalsIgnoreCase("text")
                    ? new Payload(xhr.getResponseText())
                    : new Payload(xhr.getResponse());

            final RawResponseImpl response = new RawResponseImpl(gwtResponse.getStatusCode(),
                    gwtResponse.getStatusText(), new Headers(gwtResponse.getHeaders()),
                    ResponseType.of(responseType), payload);

            evalResponse(request, deferred, resolveType, parametrizedType, response);
        }/*w ww  . j ava  2s  . c o m*/

        public void onError(com.google.gwt.http.client.Request gwtRequest, Throwable exception) {
            if (exception instanceof com.google.gwt.http.client.RequestTimeoutException) {
                // reject as timeout
                com.google.gwt.http.client.RequestTimeoutException e = (com.google.gwt.http.client.RequestTimeoutException) exception;
                deferred.reject(new RequestTimeoutException(request, e.getTimeoutMillis()));
            } else {
                // reject as generic request exception
                deferred.reject(new RequestException(exception));
            }
        }
    };
}