List of usage examples for com.google.gwt.http.client RequestBuilder RequestBuilder
protected RequestBuilder(String httpMethod, String url)
From source file:com.gloopics.g3viewer.client.G3Viewer.java
License:Apache License
public void doJSONRequest(final String a_URL, final HttpSuccessHandler a_Handler, final boolean a_hasParams, final boolean a_IncludeCSRF, String a_Data) { try {/*from w w w . j a v a2 s .c o m*/ String url; if (m_CSRF != null && a_IncludeCSRF) { url = a_URL + (a_hasParams ? "&csrf=" : "?csrf=") + m_CSRF; } else { url = a_URL; } RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.POST, url); requestBuilder.setHeader("Content-Type", "application/x-www-form-urlencoded"); requestBuilder.setHeader("X-Requested-With", "XMLHttpRequest"); requestBuilder.setCallback(new JSONResponseTextHandler(new JSONResponseCallback() { @Override public void onResponse(JSONValue aValue) { a_Handler.success(aValue); } @Override public void onError(Throwable aThrowable) { if (aThrowable.getCause() != null) { StringBuffer stack = new StringBuffer(); StackTraceElement[] stes = aThrowable.getCause().getStackTrace(); for (StackTraceElement ste : stes) { stack.append(ste.toString()); stack.append(" \n "); } displayError("a Unexpected Error ", aThrowable.toString() + " - " + a_URL + "\n " + stack.toString()); } else { displayError("a Unexpected Error ", aThrowable.toString() + " - " + a_URL); } } })); requestBuilder.setRequestData(a_Data); requestBuilder.send(); } catch (RequestException ex) { displayError("Request Exception", ex.toString() + " - " + a_URL); } }
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 ww.j a va 2s.c o 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/*from w w w.j a va 2s . c om*/ * @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/* www . j a v a 2s . 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/ *///from ww w . jav a2 s . c o 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."); } }
From source file:com.google.gerrit.client.account.NewAgreementScreen.java
License:Apache License
private void showCLA(final ContributorAgreement cla) { current = cla;/*from w w w . ja va2 s . c om*/ String url = cla.getAgreementUrl(); if (url != null && url.length() > 0) { agreementGroup.setVisible(true); agreementHtml.setText(Gerrit.C.rpcStatusWorking()); if (!url.startsWith("http:") && !url.startsWith("https:")) { url = GWT.getHostPageBaseURL() + url; } final RequestBuilder rb = new RequestBuilder(RequestBuilder.GET, url); rb.setCallback(new RequestCallback() { public void onError(Request request, Throwable exception) { new ErrorDialog(exception).center(); } public void onResponseReceived(Request request, Response response) { final String ct = response.getHeader("Content-Type"); if (response.getStatusCode() == 200 && ct != null && (ct.equals("text/html") || ct.startsWith("text/html;"))) { agreementHtml.setHTML(response.getText()); } else { new ErrorDialog(response.getStatusText()).center(); } } }); try { rb.send(); } catch (RequestException e) { new ErrorDialog(e).show(); } } else { agreementGroup.setVisible(false); } if (contactPanel == null && cla.isRequireContactInformation()) { contactPanel = new ContactPanelFull(); contactGroup.add(contactPanel); contactPanel.hideSaveButton(); } contactGroup.setVisible(cla.isRequireContactInformation() && cla.getAutoVerify() != null); finalGroup.setVisible(cla.getAutoVerify() != null); yesIAgreeBox.setText(""); submit.setEnabled(false); }
From source file:com.google.gerrit.client.rpc.RestApi.java
License:Apache License
private RequestBuilder request(Method method) { RequestBuilder req = new RequestBuilder(method, url()); if (ifNoneMatch != null) { req.setHeader("If-None-Match", ifNoneMatch); }//from w ww . jav a2s . c o m req.setHeader("Accept", JSON_TYPE); if (Gerrit.getXGerritAuth() != null) { req.setHeader("X-Gerrit-Auth", Gerrit.getXGerritAuth()); } return req; }
From source file:com.google.gwt.examples.http.client.GetExample.java
public static void doGet(String url) { RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url); try {/*from w w w.j av a2 s .com*/ Request response = builder.sendRequest(null, new RequestCallback() { public void onError(Request request, Throwable exception) { // Code omitted for clarity } public void onResponseReceived(Request request, Response response) { // Code omitted for clarity } }); } catch (RequestException e) { // Code omitted for clarity } }
From source file:com.google.gwt.examples.http.client.PostExample.java
public static void doPost(String url, String postData) { RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, url); try {//ww w. j a va 2 s . c o m builder.setHeader("Content-Type", "application/x-www-form-urlencoded"); Request response = builder.sendRequest(postData, new RequestCallback() { public void onError(Request request, Throwable exception) { // code omitted for clarity } public void onResponseReceived(Request request, Response response) { // code omitted for clarity } }); } catch (RequestException e) { Window.alert("Failed to send the request: " + e.getMessage()); } }
From source file:com.google.gwt.examples.http.client.TimeoutExample.java
public static void doGetWithTimeout(String url) { RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url); try {/* w w w . j a v a2 s . c o m*/ /* * wait 2000 milliseconds for the request to complete */ builder.setTimeoutMillis(2000); Request response = builder.sendRequest(null, new RequestCallback() { public void onError(Request request, Throwable exception) { if (exception instanceof RequestTimeoutException) { // handle a request timeout } else { // handle other request errors } } public void onResponseReceived(Request request, Response response) { // code omitted for clarity } }); } catch (RequestException e) { Window.alert("Failed to send the request: " + e.getMessage()); } }