Example usage for com.google.gwt.http.client RequestException RequestException

List of usage examples for com.google.gwt.http.client RequestException RequestException

Introduction

In this page you can find the example usage for com.google.gwt.http.client RequestException RequestException.

Prototype

public RequestException(Throwable cause) 

Source Link

Usage

From source file:com.calclab.emite.base.util.Platform.java

License:Open Source License

/**
 * Send a BOSH HTTP request to a server.
 * //from www.ja va  2s . co  m
 * @param httpBase the base URL to send the request
 * @param request the request contents
 * @param callback a callback to process the response
 */
public static final void sendXML(final String httpBase, final XMLPacket request,
        final AsyncResult<XMLPacket> callback) {
    final RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, httpBase);
    builder.setHeader(HttpHeaders.CONTENT_TYPE, "text/xml; charset=utf-8");
    //builder.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache");
    //builder.setHeader(HttpHeaders.PRAGMA, "no-cache");
    // TODO : Hard coded timeout to 6s, but we should set it to the wait + a delta
    // builder.setTimeoutMillis(6000);
    try {
        final Request req = builder.sendRequest(request.toString(), new RequestCallback() {
            @Override
            public void onResponseReceived(@Nullable final Request req, @Nullable final Response res) {
                requests.remove(req);
                if (res.getStatusCode() != Response.SC_OK) {
                    callback.onError(new RequestException(
                            "Invalid status " + res.getStatusCode() + ": " + res.getStatusText()));
                    return;
                }

                final XMLPacket response = XMLBuilder.fromXML(res.getText());
                if (response == null || !"body".equals(response.getTagName())) {
                    callback.onError(new RequestException("Bad response: " + res.getText()));
                    return;
                }

                callback.onSuccess(response);
            }

            @Override
            public void onError(@Nullable final Request req, @Nullable final Throwable throwable) {
                logger.severe("GWT CONNECTOR ERROR: " + throwable.getMessage());
                requests.remove(req);
                callback.onError(throwable);
            }
        });
        requests.add(req);
    } catch (final RequestException e) {
        callback.onError(e);
    } catch (final Exception e) {
        logger.severe("Some GWT connector exception: " + e.getMessage());
        callback.onError(e);
    }
}

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).
 *//* www.  ja v  a  2 s.co m*/
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.cgxlib.xq.client.plugins.deferred.PromiseReqBuilder.java

License:Apache License

public void onResponseReceived(Request request, Response response) {
    int status = response.getStatusCode();
    if (status <= 0 || status >= 400) {
        String statusText = status <= 0 ? "Bad CORS" : response.getStatusText();
        onError(request,//from   w  ww. j  a v  a  2 s  .  co m
                new RequestException("HTTP ERROR: " + status + " " + statusText + "\n" + response.getText()));
    } else {
        dfd.resolve(response, request);
    }
}

From source file:com.cgxlib.xq.vm.AjaxTransportJre.java

License:Apache License

private Promise getXhr(final Settings settings, final boolean cors) {
    return new PromiseFunction() {
        public void f(Deferred dfd) {
            try {
                Response response = httpClient(settings, cors);
                int status = response.getStatusCode();
                if (status <= 0 || status >= 400) {
                    String statusText = status <= 0 ? "Bad CORS" : response.getStatusText();
                    dfd.reject(//w  ww . java2 s. co m
                            new RequestException(
                                    "HTTP ERROR: " + status + " " + statusText + "\n" + response.getText()),
                            null);
                } else {
                    dfd.resolve(response, null);
                }
            } catch (Exception e) {
                e.printStackTrace();
                dfd.reject(e, null);
            }
        }
    };
}

From source file:com.googlesource.gerrit.plugins.xdocs.client.XDocApi.java

License:Apache License

public static void checkHtml(String url, final AsyncCallback<VoidResult> callback) {
    RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);
    try {/*from   w  w w  .  jav  a2s  . c o  m*/
        builder.sendRequest(null, new RequestCallback() {
            @Override
            public void onResponseReceived(Request request, Response response) {
                int status = response.getStatusCode();
                if (200 <= status && status < 300) {
                    callback.onSuccess(VoidResult.create());
                } else {
                    callback.onFailure(new RequestException(status + " " + response.getStatusText()));
                }
            }

            @Override
            public void onError(Request request, Throwable caught) {
                callback.onFailure(caught);
            }
        });
    } catch (RequestException e) {
        callback.onFailure(e);
    }
}

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  .c  o m
 * 
 * @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:gwt.dojo.showcase.client.Showcase.java

License:Apache License

private void loadAndSwitchView(final ListItem listItem) {

    final RequestCallback requestCallback = new RequestCallback() {
        @Override//w ww . j  a v a  2  s.c o m
        public void onResponseReceived(Request request, Response response) {
            if (200 == response.getStatusCode()) {
                try {
                    // Process the response in response.getText()

                    // fillInDemoSource();
                    DivElement rightPane = Document.get().getElementById("rightPane").cast();
                    DivElement tmpContainer = Document.get().createDivElement();
                    tmpContainer.setInnerHTML(response.getText());
                    rightPane.appendChild(tmpContainer);
                    JsArray ws = MobileParser.parse(tmpContainer);
                    for (int i = 0, n = ws.length(); i < n; i++) {
                        if (ws.getJsObject(i).hasProperty("startup")) {
                            _WidgetBase w = ws.getJsObject(i);
                            w.startup();
                        }
                    }

                    // reparent
                    rightPane.removeChild(tmpContainer);
                    NodeList<Node> children = tmpContainer.getChildNodes();
                    for (int i = 0, n = children.getLength(); i < n; i++) {
                        Element elem = tmpContainer.getChild(i).cast();
                        rightPane.appendChild(elem);
                    }

                    showProgressIndicator(false);
                    Scheduler.get().scheduleDeferred(new ScheduledCommand() {
                        @Override
                        public void execute() {
                            initView(listItem);
                            listItem.transitionTo(listItem.getString("viewId"));
                            // triggreTransition(listItem,
                            // listItem.getString("id"));
                        }
                    });
                } catch (Exception e) {
                    Window.alert("Error: " + e);
                }
            } else {
                // Handle the error. Can get the status text from
                // response.getStatusText()
                onError(request, new RequestException("HTTP Error: " + response.getStatusCode()));
            }
        }

        @Override
        public void onError(Request request, Throwable exception) {
            Window.alert("Failed to load demo.");
            showProgressIndicator(false);
            inTransitionOrLoading = false;
        }
    };

    showProgressIndicator(true);

    String url = listItem.getString("demourl");
    RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode(url));

    Request request = null;
    try {
        request = builder.sendRequest(null, requestCallback);
    } catch (RequestException e) {
        requestCallback.onError(request, e);
    }
}

From source file:net.zschech.gwt.comet.client.impl.HTTPRequestCometTransport.java

License:Apache License

@Override
public void connect(int connectionCount) {
    super.connect(connectionCount);
    read = 0;/*from ww w .  ja va  2s.  c  o  m*/

    xmlHttpRequest = XMLHttpRequest.create();
    try {
        xmlHttpRequest.open("GET", getUrl(connectionCount));
        xmlHttpRequest.setRequestHeader("Accept", "application/comet");
        xmlHttpRequest.setOnReadyStateChange(new ReadyStateChangeHandler() {
            @Override
            public void onReadyStateChange(XMLHttpRequest request) {
                if (!disconnecting) {
                    switch (request.getReadyState()) {
                    case XMLHttpRequest.LOADING:
                        onReceiving(request.getStatus(), request.getResponseText());
                        break;
                    case XMLHttpRequest.DONE:
                        onLoaded(request.getStatus(), request.getResponseText());
                        break;
                    }
                }
            }
        });
        xmlHttpRequest.send();
    } catch (JavaScriptException e) {
        xmlHttpRequest = null;
        listener.onError(new RequestException(e.getMessage()), false);
    }
}

From source file:org.atmosphere.gwt.client.impl.HTTPRequestCometTransport.java

License:Apache License

@Override
public void connect(int connectionCount) {
    init();//from   www  .  j a  va2 s .  c o m
    xmlHttpRequest = XMLHttpRequest.create();
    try {
        xmlHttpRequest.open("GET", getUrl(connectionCount));
        xmlHttpRequest.setRequestHeader("Accept", "application/comet");
        xmlHttpRequest.setOnReadyStateChange(new ReadyStateChangeHandler() {
            @Override
            public void onReadyStateChange(XMLHttpRequest request) {
                if (!aborted) {
                    switch (request.getReadyState()) {
                    case XMLHttpRequest.LOADING:
                        onReceiving(request.getStatus(), request.getResponseText());
                        if (needPolling()) {
                            pollingTimer.scheduleRepeating(POLLING_INTERVAL);
                        }
                        break;
                    case XMLHttpRequest.DONE:
                        onLoaded(request.getStatus(), request.getResponseText());
                        pollingTimer.cancel();
                        break;
                    }
                } else {
                    request.clearOnReadyStateChange();
                    if (request.getReadyState() != XMLHttpRequest.DONE) {
                        request.abort();
                    }
                }
            }
        });
        xmlHttpRequest.send();
    } catch (JavaScriptException e) {
        if (xmlHttpRequest != null) {
            xmlHttpRequest.abort();
            xmlHttpRequest = null;
        }
        listener.onError(new RequestException(e.getMessage()), false);
    }
}

From source file:org.atmosphere.gwt.client.impl.IEXDomainRequestCometTransport.java

License:Apache License

@Override
public void connect(int connectionCount) {
    init();/*from w w  w. ja va2s.c o  m*/
    try {
        transportRequest = XDomainRequest.create();
        transportRequest.setListener(xDomainRequestListener);
        transportRequest.openGET(getUrl(connectionCount));
        transportRequest.send();

    } catch (JavaScriptException ex) {
        if (transportRequest != null) {
            transportRequest.abort();
            transportRequest = null;
        }
        listener.onError(new RequestException(ex.getMessage()), false);
    }
}