List of usage examples for com.google.gwt.http.client RequestBuilder sendRequest
public Request sendRequest(String requestData, RequestCallback callback) throws RequestException
From source file:com.ephesoft.gxt.rv.client.layout.ReviewValidateLayout.java
License:Open Source License
public void onWindowClose() { final String batchInstanceIdentifier = ReviewValidateNavigator.getCurrentBatchInstanceIdentifier(); if (!StringUtil.isNullOrEmpty(batchInstanceIdentifier)) { // following code was inserted to call a webservice to do cleanup and updateTime on RV screen close. RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, StringUtil.concatenate(CoreCommonConstant.WINDOW_CLOSE_SERVICE_URL, batchInstanceIdentifier)); final String postData = CoreCommonConstants.EMPTY_STRING; builder.setHeader(CoreCommonConstant.CONTENT_TYPE, CoreCommonConstant.MIME_TYPE); try {//from w ww .j a va2 s . c o m builder.sendRequest(postData, new RequestCallback() { public void onError(Request request, Throwable exception) { // code will never reach here, before that window will be closed. } public void onResponseReceived(Request request, Response response) { // code will never reach here, before that window will be closed. } }); } catch (com.google.gwt.http.client.RequestException e) { // UNReachable Code.. } } }
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 a va2 s .c o 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.extjs.gxt.ui.client.widget.HtmlContainer.java
License:sencha.com license
protected void requestData() { RequestBuilder rb = requestBuilder == null ? new RequestBuilder(httpMethod, url) : requestBuilder; if (callback == null) { callback = new RequestCallback() { public void onError(Request request, Throwable exception) { handleError(request, exception); }/*from w ww . jav a 2s.c o m*/ public void onResponseReceived(Request request, Response response) { handleResponseReceived(request, response); } }; } try { rb.sendRequest(requestData, callback); } catch (RequestException e) { handleError(null, e); } }
From source file:com.feller.picup.client.PickUp.java
License:Open Source License
protected void getBucketURL() { RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode(getBacketURL)); try {// ww w. j a va2 s . com Request request = builder.sendRequest(null, new RequestCallback() { public void onError(Request request, Throwable exception) { displayError("Couldn't retrieve JSON ::" + exception.getMessage()); } public void onResponseReceived(Request request, Response response) { if (200 == response.getStatusCode()) { urlToQR(response.getText()); } else { displayError("couldn't retrieve JSON (" + response.getStatusCode() + ")"); } } }); } catch (RequestException e) { displayError("exception: Couldn't retrieve JSON" + 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,//ww w . j a va 2s . c om * 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. *//* ww w . j a va 2s . c o 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)); } }
From source file:com.goodow.wind.channel.rpc.impl.AjaxRpc.java
License:Apache License
@Override public RpcHandle makeRequest(Method method, String serviceName, MapFromStringToString params, final Rpc.RpcCallback rpcCallback) { final int requestId = nextRequestId; nextRequestId++;//from w w w .j a v a 2s .co m // See the javadoc for HARD_RELOAD. if (connectionState == ConnectionState.HARD_RELOAD) { return new Handle(requestId); } final String requestData; final RequestBuilder.Method httpMethod; StringBuilder urlBuilder = new StringBuilder(rpcRoot + "/" + serviceName + "?"); // NOTE: For some reason, IE6 seems not to perform some requests // it's already made, resulting in... no data. Inserting some // unique value into the request seems to fix that. if (!Browser.getInfo().isWebKit() && !Browser.getInfo().isGecko()) { urlBuilder.append("_no_cache=" + requestId + "" + Duration.currentTimeMillis() + "&"); } if (method == Method.GET) { httpMethod = RequestBuilder.GET; addParams(urlBuilder, params); requestData = ""; } else { httpMethod = RequestBuilder.POST; requestData = addParams(new StringBuilder(), params).toString(); } final String url = urlBuilder.toString(); RequestBuilder r = new RequestBuilder(httpMethod, url); if (method == Method.POST) { r.setHeader("Content-Type", "application/x-www-form-urlencoded"); r.setHeader("X-Same-Domain", "true"); } log.log(Level.INFO, "RPC Request, id=" + requestId + " method=" + httpMethod + " urlSize=" + url.length() + " bodySize=" + requestData.length()); class RpcRequestCallback implements RequestCallback { @Override public void onError(Request request, Throwable exception) { if (!handles.hasKey(requestId)) { log.log(Level.INFO, "RPC FailureDrop, id=" + requestId + " " + exception.getMessage()); return; } removeHandle(); error(exception); } @Override public void onResponseReceived(Request request, Response response) { RpcHandle handle = handles.get(requestId); if (handle == null) { // It's been dropped log.log(Level.INFO, "RPC SuccessDrop, id=" + requestId); return; } // Clear it now, before callbacks removeHandle(); int statusCode = response.getStatusCode(); String data = response.getText(); Result result; if (statusCode < 100) { result = Result.RETRYABLE_FAILURE; maybeSetConnectionState(ConnectionState.OFFLINE); } else if (statusCode == 200) { result = Result.OK; maybeSetConnectionState(ConnectionState.CONNECTED); consecutiveFailures = 0; } else if (statusCode >= 500) { result = Result.RETRYABLE_FAILURE; consecutiveFailures++; if (consecutiveFailures > MAX_CONSECUTIVE_FAILURES) { maybeSetConnectionState(ConnectionState.OFFLINE); } else { maybeSetConnectionState(ConnectionState.CONNECTED); } } else { result = Result.PERMANENT_FAILURE; maybeSetConnectionState(ConnectionState.SOFT_RELOAD); } switch (result) { case OK: log.log(Level.INFO, "RPC Success, id=" + requestId); try { rpcCallback.onSuccess(data); } catch (JsonException e) { // Semi-HACK: Treat parse errors as login problems // due to loading a login or authorization page. (It's unlikely // we'd otherwise get a parse error from a 200 OK result). // The simpler solution of detecting redirects is not possible // with XmlHttpRequest, the web is unfortunately broken. // TODO Possible alternatives: // either change our server side to not require // login through web.xml but to check if UserService says currentUser==null (or // whatever it does if not logged in) and return a well-defined "not logged in" // response instead, or to prefix all responses from the server with a fixed string // (like we do with "OK" elsewhere) and assume not logged in if that prefix is // missing. We could strip off that prefix here and make it transparent to the // callbacks. maybeSetConnectionState(ConnectionState.LOGGED_OUT); error(new Exception("RPC failed due to message exception, treating as auth failure" + ", status code: " + statusCode + ", data: " + data)); } break; case RETRYABLE_FAILURE: error(new Exception("RPC failed, status code: " + statusCode + ", data: " + data)); break; case PERMANENT_FAILURE: fatal(new Exception("RPC bad request, status code: " + statusCode + ", data: " + data)); break; default: throw new AssertionError("Unknown result " + result); } } private void error(Throwable e) { log.log(Level.WARNING, "RPC Failure, id=" + requestId + " " + e.getMessage() + " Request url:" + url, e); rpcCallback.onConnectionError(e); } private void fatal(Throwable e) { log.log(Level.WARNING, "RPC Bad Request, id=" + requestId + " " + e.getMessage() + " Request url:" + url, e); rpcCallback.onFatalError(e); } private void removeHandle() { handles.remove(requestId); } } RpcRequestCallback innerCallback = new RpcRequestCallback(); try { // TODO: store the Request object somewhere so we can e.g. cancel it r.sendRequest(requestData, innerCallback); Handle handle = new Handle(requestId); handles.put(handle.getId(), handle); return handle; } catch (RequestException e) { // TODO: Decide if this should be a badRequest. innerCallback.error(e); return null; } }
From source file:com.google.appinventor.client.wizards.TemplateUploadWizard.java
License:Open Source License
/** * Creates a new project from a Zip file and lists it in the ProjectView. * * @param projectName project name/* w w w.j a v a2s . c o m*/ * @param onSuccessCommand command to be executed after process creation * succeeds (can be {@code null}) */ public void createProjectFromExistingZip(final String projectName, final NewProjectCommand onSuccessCommand) { // Callback for updating the project explorer after the project is created on the back-end final Ode ode = Ode.getInstance(); final OdeAsyncCallback<UserProject> callback = new OdeAsyncCallback<UserProject>( // failure message MESSAGES.createProjectError()) { @Override public void onSuccess(UserProject projectInfo) { // Update project explorer -- i.e., display in project view if (projectInfo == null) { Window.alert( "This template has no aia file. Creating a new project with name = " + projectName); ode.getProjectService().newProject(YoungAndroidProjectNode.YOUNG_ANDROID_PROJECT_TYPE, projectName, new NewYoungAndroidProjectParameters(projectName), this); return; } Project project = ode.getProjectManager().addProject(projectInfo); if (onSuccessCommand != null) { onSuccessCommand.execute(project); } } }; // Use project RPC service to create the project on back end using String pathToZip = ""; if (usingExternalTemplate) { String zipUrl = templateHostUrl + TEMPLATES_ROOT_DIRECTORY + projectName + "/" + projectName + PROJECT_ARCHIVE_ENCODED_EXTENSION; RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, zipUrl); try { Request response = builder.sendRequest(null, new RequestCallback() { @Override public void onError(Request request, Throwable exception) { Window.alert("Unable to load Project Template Data"); } @Override public void onResponseReceived(Request request, Response response) { ode.getProjectService().newProjectFromExternalTemplate(projectName, response.getText(), callback); } }); } catch (RequestException e) { Window.alert("Error fetching project zip file template."); } } else { pathToZip = TEMPLATES_ROOT_DIRECTORY + projectName + "/" + projectName + PROJECT_ARCHIVE_EXTENSION; ode.getProjectService().newProjectFromTemplate(projectName, pathToZip, callback); } }
From source file:com.google.appinventor.client.wizards.TemplateUploadWizard.java
License:Open Source License
/** * Helper method for opening a project given its Url * @param url A string of the form "http://... .asc * @param onSuccessCommand//from ww w . j a v a 2 s. co m */ private static void openTemplateProject(String url, final NewProjectCommand onSuccessCommand) { final Ode ode = Ode.getInstance(); // This Async callback is called after the project is input and created final OdeAsyncCallback<UserProject> callback = new OdeAsyncCallback<UserProject>( // failure message MESSAGES.createProjectError()) { @Override public void onSuccess(UserProject projectInfo) { // This just adds the new project to the project manager, not to AppEngine Project project = ode.getProjectManager().addProject(projectInfo); // And this opens the project if (onSuccessCommand != null) { onSuccessCommand.execute(project); } } }; final String projectName; if (url.endsWith(".asc")) { projectName = url.substring(1 + url.lastIndexOf("/"), url.lastIndexOf(".")); } else { return; } // If project of the same name already exists, just open it if (!TextValidators.checkNewProjectName(projectName)) { Project project = ode.getProjectManager().getProject(projectName); if (onSuccessCommand != null) { onSuccessCommand.execute(project); } return; // Don't retrieve the template if the project is a duplicate } // Here's where we retrieve the template data // Do a GET to retrieve data at url RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url); try { Request response = builder.sendRequest(null, new RequestCallback() { @Override public void onError(Request request, Throwable exception) { Window.alert("Unable to load Project Template Data"); } // Response received from the GET @Override public void onResponseReceived(Request request, Response response) { // The response.getText is the zip data used to create a new project. // The callback opens the project ode.getProjectService().newProjectFromExternalTemplate(projectName, response.getText(), callback); } }); } catch (RequestException e) { Window.alert("Error fetching template file."); } }
From source file:com.google.appinventor.client.wizards.TemplateUploadWizard.java
License:Open Source License
/** * Called from ProjectToolbar when user selects a set of external templates. It uses * JsonP to retrieve a json file from an external server. * * @param hostUrl, Url of the host -- e.g., http://localhost:85/ *//* ww w . j av a 2s . co m*/ public static void retrieveExternalTemplateData(final String hostUrl) { String url = hostUrl + TEMPLATES_ROOT_DIRECTORY + EXTERNAL_JSON_FILE; RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url); try { Request response = builder.sendRequest(null, new RequestCallback() { @Override public void onError(Request request, Throwable exception) { Window.alert("Unable to load Project Template Data."); if (instance != null) { instance.populateTemplateDialog(null); } } @Override public void onResponseReceived(Request request, Response response) { if (response.getStatusCode() != Response.SC_OK) { Window.alert("Unable to load Project Template Data."); return; } ArrayList<TemplateInfo> externalTemplates = new ArrayList<TemplateInfo>(); JSONValue jsonVal = JSONParser.parseLenient(response.getText()); JSONArray jsonArr = jsonVal.isArray(); for (int i = 0; i < jsonArr.size(); i++) { JSONValue entry1 = jsonArr.get(i); JSONObject entry = entry1.isObject(); externalTemplates.add(new TemplateInfo(entry.get("name").isString().stringValue(), entry.get("subtitle").isString().stringValue(), entry.get("description").isString().stringValue(), entry.get("screenshot").isString().stringValue(), entry.get("thumbnail").isString().stringValue())); } if (externalTemplates.size() == 0) { Window.alert("Unable to retrieve templates for host = " + hostUrl + "."); return; } addNewTemplateHost(hostUrl, externalTemplates); } }); } catch (RequestException e) { Window.alert("Error fetching external template."); } }