List of usage examples for com.google.gwt.http.client Response getStatusText
public abstract String getStatusText();
From source file:cc.kune.embed.client.EmbedHelper.java
License:GNU Affero Public License
/** * Process request./*from w ww .j av a 2s . c om*/ * * @param url * the url * @param callback * the callback */ public static void processRequest(final String url, final Callback<Response, Void> callback) { try { final RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url); // Needed for CORS builder.setIncludeCredentials(true); @SuppressWarnings("unused") final Request request = builder.sendRequest(null, new RequestCallback() { @Override public void onError(final Request request, final Throwable exception) { Log.error("CORS exception: ", exception); callback.onFailure(null); } @Override public void onResponseReceived(final Request request, final Response response) { if (200 == response.getStatusCode()) { callback.onSuccess(response); } else { Log.error("Couldn't retrieve CORS (" + response.getStatusText() + ")"); callback.onFailure(null); } } }); } catch (final RequestException exception) { Log.error("CORS exception: ", exception); callback.onFailure(null); } }
From source file:client.net.sf.saxon.ce.Xslt20ProcessorImpl.java
License:Mozilla Public License
public Node renderXML(JavaScriptObject inSourceDoc, DocumentInfo styleDoc, com.google.gwt.dom.client.Node target) { try {/*from ww w . ja v a 2s. com*/ if (styleDoc == null) { throw new Exception("Stylesheet for transform is null"); } docFetchRequired = inSourceDoc != null; CompilerInfo info = config.getDefaultXsltCompilerInfo(); info.setErrorListener(new StandardErrorListener()); String asyncSourceURI = null; // for now - don't use aync when using the JavaScript API calls that return a result if (docFetchRequired && (localController.getApiCommand() == APIcommand.UPDATE_HTML || (successCallback != null))) { asyncSourceURI = SaxonceApi.getAsyncUri(inSourceDoc); if (asyncSourceURI != null && asyncSourceURI.toLowerCase().startsWith("file:")) { asyncSourceURI = null; // force synchronous fetch if using file-system protocol } } // ----------- Start async code ------------- fetchedSourceDoc = null; transformInvoked = false; if (asyncSourceURI != null) { final String URI = asyncSourceURI; final Node transformTarget = target; logger.log(Level.FINE, "Aynchronous GET for: " + asyncSourceURI); final HTTPHandler hr = new HTTPHandler(); hr.doGet(asyncSourceURI, new RequestCallback() { public void onError(Request request, Throwable exception) { //hr.setErrorMessage(exception.getMessage()); String msg = "HTTP Error " + exception.getMessage() + " for URI " + URI; handleException(new RuntimeException(msg), "onError"); } public void onResponseReceived(Request request, Response response) { int statusCode = response.getStatusCode(); if (statusCode == 200) { Logger.getLogger("ResponseReceived").fine("GET Ok for: " + URI); Node responseNode; try { responseNode = (Node) XMLDOM.parseXML(response.getText()); } catch (Exception e) { handleException(new RuntimeException(e.getMessage()), "onResponseReceived"); return; } DocumentInfo responseDoc = config.wrapXMLDocument(responseNode, URI); // now document is here, we can transform it Node result = invokeTransform(responseDoc, transformTarget); hr.setResultNode(result); // TODO: This isn't used yet // handle OK response from the server } else if (statusCode < 400) { // transient } else { String msg = "HTTP Error " + statusCode + " " + response.getStatusText() + " for URI " + URI; handleException(new RuntimeException(msg), "onResponseReceived"); //hr.setErrorMessage(statusCode + " " + response.getStatusText()); } } // ends inner method }// ends inner class ); // ends doGet method call } // -------------- End async code /// we can compile - even while sourcedoc is being fetched asynchronously if (stylesheet == null) { if (LogConfiguration.loggingIsEnabled()) { LogController.InitializeTraceListener(); } logger.log(Level.FINE, "Compiling Stylesheet..."); PreparedStylesheet sheet = new PreparedStylesheet(config, info); sheet.prepare(styleDoc); stylesheet = sheet; logger.log(Level.FINE, "Stylesheet compiled OK"); } // for async operation - this is called within the callback - so don't call here if (asyncSourceURI == null && inSourceDoc != null) { int nodeType = (Node.is(inSourceDoc)) ? ((Node) inSourceDoc).getNodeType() : 0; if (nodeType > 0 && nodeType != Node.DOCUMENT_NODE) { // add a document node wrapper Node sourceNode = (Node) inSourceDoc; Document sourceDoc = sourceNode.getOwnerDocument(); HTMLDocumentWrapper htmlDoc = new HTMLDocumentWrapper(sourceDoc, sourceDoc.getURL(), config, DocType.UNKNOWN); fetchedSourceDoc = htmlDoc.wrap(sourceNode); } else { fetchedSourceDoc = SaxonceApi.getDocSynchronously(inSourceDoc, config); } } // this method only runs if transformInvoked == false - need to get sourceDoc reference if not invoked return invokeTransform(fetchedSourceDoc, target); //method ends - allowing onResponceReceived handler to call invokeTransform for async operation } catch (Exception e) { handleException(e, "renderXML"); return null; } }
From source file:com.calclab.emite.base.util.Platform.java
License:Open Source License
/** * Send a BOSH HTTP request to a server. * //from ww w . ja v a2 s . com * @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
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 . jav a 2 s.c om*/ 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 .ja v a 2 s . com*/ 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.data2semantics.yasgui.client.helpers.SparqlQuery.java
License:Open Source License
public void doRequest() { if (!view.getConnHelper().isOnline() && !JsMethods.corsEnabled(endpoint)) { //cors disabled and not online: problem! String errorMsg = "YASGUI is current not connected to the YASGUI server. " + "This mean you can only access endpoints on your own computer (e.g. localhost), which are <a href=\"http://enable-cors.org/\" target=\"_blank\">CORS enabled</a>.<br>" + "The endpoint you try to access is either not running on your computer, or not CORS-enabled.<br>" + corsNotification;// w ww.j a va2s. co m view.getErrorHelper().onQueryError(errorMsg, endpoint, queryString, customQueryArgs); return; } view.getElements().onQueryStart(); RequestBuilder builder; HashMultimap<String, String> queryArgs = customQueryArgs; RequestBuilder.Method requestMethod = queryRequestMethod; queryArgs.put("query", queryString); if (JsMethods.corsEnabled(endpoint)) { String params = Helper.getParamsAsString(queryArgs); String url = endpoint; if (queryRequestMethod == RequestBuilder.GET) { url += "?" + params; } builder = new RequestBuilder(queryRequestMethod, url); if (queryRequestMethod == RequestBuilder.POST) { builder.setHeader("Content-Type", "application/x-www-form-urlencoded"); builder.setRequestData(params); } } else { requestMethod = RequestBuilder.POST; queryArgs.put("endpoint", endpoint); queryArgs.put("requestMethod", (queryRequestMethod == RequestBuilder.POST ? "POST" : "GET")); builder = new RequestBuilder(RequestBuilder.POST, GWT.getModuleBaseURL() + "sparql"); //send via proxy builder.setHeader("Content-Type", "application/x-www-form-urlencoded"); } builder.setHeader("Accept", acceptHeader); try { final long startTime = System.currentTimeMillis(); builder.sendRequest((requestMethod == RequestBuilder.POST ? Helper.getParamsAsString(queryArgs) : null), new RequestCallback() { public void onError(Request request, Throwable e) { //e.g. a timeout queryErrorHandler(e); } @Override public void onResponseReceived(Request request, Response response) { view.getElements().onQueryFinish(); if (!response.getStatusText().equals("Abort")) { //if user cancels query, textStatus will be 'abort'. No need to show error window then if (response.getStatusCode() >= 200 && response.getStatusCode() < 300) { if (view.getSettings().useGoogleAnalytics()) { long stopTime = System.currentTimeMillis(); GoogleAnalytics.trackEvent(new GoogleAnalyticsEvent(endpoint, JsMethods.getUncommentedSparql(queryString), Integer.toString((int) (stopTime - startTime)), (int) (stopTime - startTime))); } drawResults(response.getText(), response.getHeader("Content-Type")); } else { queryErrorHandler(response); } } } }); } catch (RequestException e) { queryErrorHandler(e); } }
From source file:com.data2semantics.yasgui.client.helpers.SparqlQuery.java
License:Open Source License
private void queryErrorHandler(Response response) { if (view.getSettings().useGoogleAnalytics()) { GoogleAnalytics.trackEvent(//from w w w.j a v a 2 s . c o m new GoogleAnalyticsEvent(endpoint, JsMethods.getUncommentedSparql(queryString), "-1", -1)); } view.getElements().onQueryFinish(); //clear query result QueryTab tab = (QueryTab) view.getTabs().getTab(tabId); view.getTabs().selectTab(tabId); if (tab != null) { view.getSelectedTab().getResultContainer().resetResultArea(); } String errorMsg; if (response.getStatusCode() == 0 && (response.getStatusText() == null || response.getStatusText().trim().length() == 0)) { view.getConnHelper().checkOnlineStatus(); errorMsg = "Error querying endpoint: empty response returned"; } else { errorMsg = "Error querying endpoint: " + response.getStatusCode() + " - " + response.getStatusText(); } if (!Helper.inDebugMode() && view.getSettings().getEnabledFeatures().endpointSelectionEnabled() && JsMethods.corsEnabled(endpoint) != true && Helper.isLocalhostDomain(endpoint)) { // //we were trying to access a local endpoint via the proxy: this won't work... errorMsg += "<br><br>A possible reason for this error (next to an incorrect endpoint URL) is that you tried to send a query to an endpoint installed on your computer.<br>" + "This only works when the endpoint is <a href=\"http://enable-cors.org/\" target=\"_blank\">CORS enabled</a>.<br>" + corsNotification; } view.getErrorHelper().onQueryError(errorMsg, endpoint, queryString, customQueryArgs); }
From source file:com.example.jumpnote.web.jsonrpc.gwt.JsonRpcGwtClient.java
License:Apache License
public void callBatch(final List<JsonRpcClient.Call> calls, final BatchCallback callback) { RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, mRpcUrl); JSONObject requestJson = new JSONObject(); JSONArray callsJson = new JSONArray(); for (int i = 0; i < calls.size(); i++) { JsonRpcClient.Call call = calls.get(i); JSONObject callJson = new JSONObject(); callJson.put("method", new JSONString(call.getMethodName())); if (call.getParams() != null) { JSONObject callParams = (JSONObject) call.getParams(); for (String key : callParams.keySet()) { callJson.put(key, callParams.get(key)); }//from w w w.j av a 2s . co m } callsJson.set(i, callJson); } requestJson.put("calls", callsJson); try { builder.sendRequest(requestJson.toString(), new RequestCallback() { public void onError(Request request, Throwable e) { callback.onError(-1, new JsonRpcException(-1, e.getMessage())); } public void onResponseReceived(Request request, Response response) { if (200 == response.getStatusCode()) { JSONObject responseJson = JSONParser.parse(response.getText()).isObject(); JSONArray resultsJson = responseJson.get("results").isArray(); Object[] resultData = new Object[calls.size()]; for (int i = 0; i < calls.size(); i++) { JSONObject result = resultsJson.get(i).isObject(); if (result.containsKey("error")) { callback.onError(i, new JsonRpcException((int) result.get("error").isNumber().doubleValue(), calls.get(i).getMethodName(), result.get("message").isString().stringValue(), null)); resultData[i] = null; } else { resultData[i] = result.get("data"); } } callback.onData(resultData); } else { callback.onError(-1, new JsonRpcException(-1, "Received HTTP status code other than 200: " + response.getStatusText())); } } }); } catch (RequestException e) { // Couldn't connect to server callback.onError(-1, new JsonRpcException(-1, e.getMessage())); } }
From source file:com.fredhat.gwt.xmlrpc.client.XmlRpcClient.java
License:Open Source License
/** * Executes an asynchronous XMLRPC call to the server with a specified username * and password. If the execution was successful, the callback's {@link AsyncCallback#onSuccess(Object)} * method will be invoked with the return value as the argument. If the * execution failed for any reason, the callback's {@link AsyncCallback#onFailure(Throwable)} method will * be invoked with an instance of {@link XmlRpcException} instance as it's argument. * @param username the username for authentication * @param password the password for authentication * @param methodName the name of the XMLRPC method * @param params the parameters for the XMLRPC method * @param callback the logic implementation for handling the XMLRPC responses. * @deprecated As of XMLRPC-GWT v1.1,// w w w . ja v a 2s . c o m * build an {@link XmlRpcRequest} then call {@link XmlRpcRequest#execute()} */ @SuppressWarnings("unchecked") @Deprecated public void execute(String username, String password, String methodName, Object[] params, final AsyncCallback callback) { if (methodName == null || methodName.equals("")) { callback.onFailure(new XmlRpcException("The method name parameter cannot be null")); return; } if (params == null) params = new Object[0]; Document request = buildRequest(methodName, params); if (debugMessages) System.out.println("** Request **\n" + request + "\n*************"); RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.POST, serverURL); requestBuilder.setHeader("Content-Type", "text/xml"); requestBuilder.setTimeoutMillis(timeout); if (username != null) requestBuilder.setUser(username); if (password != null) requestBuilder.setPassword(password); try { requestBuilder.sendRequest(request.toString(), new RequestCallback() { public void onResponseReceived(Request req, Response res) { if (res.getStatusCode() != 200) { callback.onFailure(new XmlRpcException("Server returned " + "response code " + res.getStatusCode() + " - " + res.getStatusText())); return; } Object responseObj = buildResponse(res.getText()); if (responseObj instanceof XmlRpcException) callback.onFailure((XmlRpcException) responseObj); else callback.onSuccess(responseObj); } public void onError(Request req, Throwable t) { callback.onFailure(t); } }); } catch (RequestException e) { callback.onFailure(new XmlRpcException("Couldn't make server request", e)); } }
From source file:com.fredhat.gwt.xmlrpc.client.XmlRpcRequest.java
License:Open Source License
/** * Invokes the XML-RPC method asynchronously. All success and failure logic will * be in your {@link AsyncCallback} that you defined in the constructor. *//*from w w w . ja v a2 s . co m*/ public void execute() { if (methodName == null || methodName.equals("")) { callback.onFailure(new XmlRpcException("The method name parameter cannot be null")); return; } if (params == null) params = new Object[] {}; Document request = buildRequest(methodName, params); if (client.getDebugMode()) System.out.println("** Request **\n" + request + "\n*************"); RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.POST, client.getServerURL()); requestBuilder.setHeader("Content-Type", "text/xml"); //Ak existuje cookie posli ju v hlavicke if (Cookies.getCookie("sessionID") != null) { requestBuilder.setHeader("sessionID", Cookies.getCookie("sessionID")); } requestBuilder.setTimeoutMillis(client.getTimeoutMillis()); if (client.getUsername() != null) requestBuilder.setUser(client.getUsername()); if (client.getPassword() != null) requestBuilder.setPassword(client.getPassword()); try { requestBuilder.sendRequest(request.toString(), new RequestCallback() { public void onResponseReceived(Request req, Response res) { if (res.getStatusCode() != 200) { callback.onFailure(new XmlRpcException("Server returned " + "response code " + res.getStatusCode() + " - " + res.getStatusText())); return; } try { T responseObj = buildResponse(res.getText()); callback.onSuccess(responseObj); } catch (XmlRpcException e) { callback.onFailure(e); } catch (ClassCastException e) { callback.onFailure(e); } } public void onError(Request req, Throwable t) { callback.onFailure(t); } }); } catch (RequestException e) { callback.onFailure(new XmlRpcException("Couldn't make server request. Are you violating the " + "Same Origin Policy? Error: " + e.getMessage(), e)); } }