List of usage examples for com.google.gwt.http.client RequestBuilder send
public Request send() throws RequestException
From source file:org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.ResourceTreeView.java
License:Open Source License
private MenuItem buildMetricsMenu(final ResourceType type, final Resource resource) { MenuItem measurements = new MenuItem(MSG.view_tree_common_contextMenu_measurements()); final Menu measurementsSubMenu = new Menu(); DashboardCriteria criteria = new DashboardCriteria(); GWTServiceLookup.getDashboardService().findDashboardsByCriteria(criteria, new AsyncCallback<PageList<Dashboard>>() { public void onFailure(Throwable caught) { CoreGUI.getErrorHandler() .handleError(MSG.view_tree_common_contextMenu_loadFailed_dashboard(), caught); }//from w w w . j a v a 2 s . c o m public void onSuccess(PageList<Dashboard> result) { //sort the display items alphabetically TreeSet<String> ordered = new TreeSet<String>(); Map<String, MeasurementDefinition> definitionMap = new HashMap<String, MeasurementDefinition>(); for (MeasurementDefinition m : type.getMetricDefinitions()) { ordered.add(m.getDisplayName()); definitionMap.put(m.getDisplayName(), m); } for (String displayName : ordered) { final MeasurementDefinition def = definitionMap.get(displayName); //only add menu items for Measurement if (def.getDataType().equals(DataType.MEASUREMENT)) { MenuItem defItem = new MenuItem(def.getDisplayName()); measurementsSubMenu.addItem(defItem); Menu defSubItem = new Menu(); defItem.setSubmenu(defSubItem); for (final Dashboard d : result) { MenuItem addToDBItem = new MenuItem( MSG.view_tree_common_contextMenu_addChartToDashboard(d.getName())); defSubItem.addItem(addToDBItem); addToDBItem.addClickHandler(new ClickHandler() { public void onClick(MenuItemClickEvent menuItemClickEvent) { DashboardPortlet p = new DashboardPortlet( MSG.view_tree_common_contextMenu_resourceGraph(), ResourceGraphPortlet.KEY, 250); p.getConfiguration().put(new PropertySimple( ResourceGraphPortlet.CFG_RESOURCE_ID, resource.getId())); p.getConfiguration().put(new PropertySimple( ResourceGraphPortlet.CFG_DEFINITION_ID, def.getId())); d.addPortlet(p); GWTServiceLookup.getDashboardService().storeDashboard(d, new AsyncCallback<Dashboard>() { public void onFailure(Throwable caught) { CoreGUI.getErrorHandler().handleError(MSG .view_tree_common_contextMenu_saveChartToDashboardFailure(), caught); } public void onSuccess(Dashboard result) { CoreGUI.getMessageCenter().notify(new Message(MSG .view_tree_common_contextMenu_saveChartToDashboardSuccessful( result.getName()), Message.Severity.Info)); } }); } }); } //end dashboard iteration //add new menu item for adding current graphable element to view if on Monitor/Graphs tab String currentViewPath = History.getToken(); if (currentViewPath.indexOf("Monitoring/Graphs") > -1) { MenuItem addGraphItem = new MenuItem(MSG.common_title_add_graph_to_view()); defSubItem.addItem(addGraphItem); addGraphItem.addClickHandler(new ClickHandler() { public void onClick(MenuItemClickEvent menuItemClickEvent) { //generate javascript to call out to. //Ex. menuLayers.hide();addMetric('${metric.resourceId},${metric.scheduleId}') if (getScheduleDefinitionId(resource, def.getName()) > -1) { String resourceGraphElements = resource.getId() + "," + getScheduleDefinitionId(resource, def.getName()); //construct portal.war url to access String baseUrl = "/resource/common/monitor/visibility/IndicatorCharts.do"; baseUrl += "?id=" + resource.getId(); baseUrl += "&view=Default"; baseUrl += "&action=addChart&metric=" + resourceGraphElements; baseUrl += "&view=Default"; final String url = baseUrl; //initiate HTTP request final RequestBuilder b = new RequestBuilder(RequestBuilder.GET, baseUrl); try { b.setCallback(new RequestCallback() { public void onResponseReceived(final Request request, final Response response) { Log.trace( "Successfully submitted request to add graph to view:" + url); //kick off a page reload. String currentViewPath = History.getToken(); CoreGUI.goToView(currentViewPath, true); } @Override public void onError(Request request, Throwable t) { Log.trace("Error adding Metric:" + url, t); } }); b.send(); } catch (RequestException e) { Log.trace("Error adding Metric:" + url, e); } } } }); } // end add the "add to view" menu item } //end trait exclusion } //end measurement def iteration } }); measurements.setSubmenu(measurementsSubMenu); return measurements; }
From source file:org.rhq.enterprise.gui.coregui.client.LoginView.java
License:Open Source License
private void login(final String username, final String password) { loginButton.setDisabled(true);//from w w w.ja va2s . c o m try { RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.POST, "/j_security_check.do"); requestBuilder.setHeader("Content-Type", "application/x-www-form-urlencoded"); // URL-encode the username and password in case they contain URL special characters ('?', '&', '%', '+', // etc.), which would corrupt the request if not encoded. String encodedUsername = URL.encodeQueryString(username); String encodedPassword = URL.encodeQueryString(password); String requestData = "j_username=" + encodedUsername + "&j_password=" + encodedPassword; requestBuilder.setRequestData(requestData); requestBuilder.setCallback(new RequestCallback() { public void onResponseReceived(Request request, Response response) { int statusCode = response.getStatusCode(); if (statusCode == 200) { window.destroy(); loginShowing = false; UserSessionManager.login(username, password); } else { handleError(statusCode); } } public void onError(Request request, Throwable exception) { handleError(0); } }); requestBuilder.send(); } catch (Exception e) { handleError(0); } }
From source file:org.rhq.enterprise.gui.coregui.client.UserSessionManager.java
License:Open Source License
public static void checkLoginStatus(final String user, final String password, final AsyncCallback<Subject> callback) { //initiate request to portal.war(SessionAccessServlet) to retrieve existing session info if exists //session has valid user then <subjectId>:<sessionId>:<lastAccess> else "" final RequestBuilder b = createSessionAccessRequestBuilder(); try {/*from www .j a v a 2 s . co m*/ b.setCallback(new RequestCallback() { public void onResponseReceived(final Request request, final Response response) { Log.info("response text = " + response.getText()); String sessionIdString = response.getText(); // If a session is active it will return valid session strings if (sessionIdString != null && sessionIdString.length() > 0) { String[] parts = sessionIdString.split(":"); final int subjectId = Integer.parseInt(parts[0]); final String sessionId = parts[1]; // not null final long lastAccess = Long.parseLong(parts[2]); Log.info("sessionAccess-subjectId: " + subjectId); Log.info("sessionAccess-sessionId: " + sessionId); Log.info("sessionAccess-lastAccess: " + lastAccess); // There is a window of LOGOUT_DELAY ms where the coreGui session is logged out but the // server session is valid (to allow in-flight requests to process successfully). During // this window prevent a browser refresh (F5) from being able to bypass the // loginView and hijack the still-valid server session. We need to allow: // 1) a browser refresh when coreGui is logged in (no doomedSession) // 2) a valid, quick re-login (sessionState loggedOut, not unknown) // Being careful of these scenarios, catch the bad refresh situation and // redirect back to loginView if (State.IS_UNKNOWN == sessionState && sessionId.equals(getDoomedSessionId())) { // a browser refresh kills any existing logoutTimer. Reschedule the logout. sessionState = State.IS_LOGGED_OUT; scheduleLogoutServerSide(sessionId); new LoginView(LOCATOR_ID).showLoginDialog(); return; } String previousSessionId = getPreviousSessionId(); // may be null Log.info("sessionAccess-previousSessionId: " + previousSessionId); if (previousSessionId == null || previousSessionId.equals(sessionId) == false) { // persist sessionId if different from previously saved sessionId Log.info("sessionAccess-savingSessionId: " + sessionId); saveSessionId(sessionId); // new sessions get the full SESSION_TIMEOUT period prior to expire Log.info("sessionAccess-schedulingSessionTimeout: " + SESSION_TIMEOUT); coreGuiSessionTimer.schedule(SESSION_TIMEOUT); } else { // existing sessions should expire SESSION_TIMEOUT minutes from the previous access time long expiryTime = lastAccess + SESSION_TIMEOUT; long expiryMillis = expiryTime - System.currentTimeMillis(); // can not schedule a time with millis less than or equal to 0 if (expiryMillis < 1) { expiryMillis = 1; // expire VERY quickly } else if (expiryMillis > SESSION_TIMEOUT) { expiryMillis = SESSION_TIMEOUT; // guarantees maximum } Log.info("sessionAccess-reschedulingSessionTimeout: " + expiryMillis); coreGuiSessionTimer.schedule((int) expiryMillis); } // Certain logins may not follow a "LogOut" history item. Specifically, if the session timer // causes a logout the History token will be the user's current view. If the same user // logs in again his view should be maintained, but if the subsequent login is for a // different user we want him to start fresh, so in this case ensure a proper // History token is set. if (!History.getToken().equals("LogOut")) { if (null != sessionSubject && sessionSubject.getId() != subjectId) { // on user change register the logout History.newItem("LogOut", false); } // TODO else { // We don't currently capture enough state info to solve this scenario: // 1) session expires // 2) browser refresh // 3) log in as different user. // In this case the previous user's path will be the initial view for the new user. To // solve this we'd need to somehow flag that a browser refresh has occurred. This may // be doable by looking for state transitions from UNKNOWN to other states. // } } // set the session subject, so the fetch to load the configuration works final Subject subject = new Subject(); subject.setId(subjectId); subject.setSessionId(Integer.valueOf(sessionId)); // populate the username for the subject for isUserWithPrincipal check in ldap processing subject.setName(user); sessionSubject = subject; if (subject.getId() == 0) {//either i)ldap new user registration ii)ldap case sensitive match if ((subject.getName() == null) || (subject.getName().trim().isEmpty())) { //we've lost crucial information, probably in a browser refresh. Send them back through login Log.trace( "Unable to locate information critical to ldap registration/account lookup. Log back in."); sessionState = State.IS_LOGGED_OUT; new LoginView(LOCATOR_ID).showLoginDialog(); return; } Log.trace("Proceeding with case insensitive login of ldap user '" + user + "'."); GWTServiceLookup.getSubjectService().processSubjectForLdap(subject, password, new AsyncCallback<Subject>() { public void onFailure(Throwable caught) { // this means either: a) we mapped the username to a previously registered LDAP // user but login via LDAP failed, or b) we were not able to map the username // to any LDAP users, previously registered or not. Log.debug("Failed to complete ldap processing for subject: " + caught.getMessage()); //TODO: pass message to login dialog. new LoginView(LOCATOR_ID).showLoginDialog(); return; } public void onSuccess(final Subject processedSubject) { //Then found case insensitive and returned that logged in user //Figure out of this is new user registration boolean isNewUser = false; if (processedSubject.getUserConfiguration() != null) { isNewUser = Boolean.valueOf(processedSubject.getUserConfiguration() .getSimpleValue("isNewUser", "false")); } if (!isNewUser) { // otherwise, we successfully logged in as an existing LDAP user case insensitively. Log.trace("Logged in case insensitively as ldap user '" + processedSubject.getName() + "'"); callback.onSuccess(processedSubject); } else {// if account is still active assume new LDAP user registration. Log.trace("Proceeding with registration for ldap user '" + user + "'."); sessionState = State.IS_REGISTERING; sessionSubject = processedSubject; new LoginView(LOCATOR_ID).showRegistrationDialog(subject.getName(), String.valueOf(processedSubject.getSessionId()), password, callback); } return; } });//end processSubjectForLdap call } else {//else send through regular session check SubjectCriteria criteria = new SubjectCriteria(); criteria.fetchConfiguration(true); criteria.addFilterId(subjectId); GWTServiceLookup.getSubjectService().findSubjectsByCriteria(criteria, new AsyncCallback<PageList<Subject>>() { public void onFailure(Throwable caught) { CoreGUI.getErrorHandler() .handleError(MSG.util_userSession_loadFailSubject(), caught); Log.info("Failed to load user's subject"); //TODO: pass message to login ui. new LoginView(LOCATOR_ID).showLoginDialog(); return; } public void onSuccess(PageList<Subject> results) { final Subject validSessionSubject = results.get(0); //update the returned subject with current session id validSessionSubject.setSessionId(Integer.valueOf(sessionId)); Log.trace("Completed session check for subject '" + validSessionSubject + "'."); //initiate ldap check for ldap authz update(wrt roles) of subject with silent update //as the subject.id > 0 then only group authorization updates will occur if ldap configured. GWTServiceLookup.getSubjectService().processSubjectForLdap( validSessionSubject, "", new AsyncCallback<Subject>() { public void onFailure(Throwable caught) { Log.warn("Errors occurred processing subject for LDAP." + caught.getMessage()); //TODO: pass informative message to Login UI. callback.onSuccess(validSessionSubject); return; } public void onSuccess(Subject result) { Log.trace("Successfully processed subject '" + validSessionSubject.getName() + "' for LDAP."); callback.onSuccess(validSessionSubject); return; } }); } }); } //end of server side session check; } else { //invalid client session. Back to login sessionState = State.IS_LOGGED_OUT; new LoginView(LOCATOR_ID).showLoginDialog(); return; } } public void onError(Request request, Throwable exception) { callback.onFailure(exception); } }); b.send(); } catch (RequestException e) { callback.onFailure(e); } }
From source file:org.sigmah.client.page.login.LoginView.java
License:Open Source License
private void doLogin(final String login, final String password, final Button loginButton, final Image loader) { final String query = "email=" + URL.encodeComponent(login) + "&password=" + URL.encodeComponent(password); final RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.POST, "../Login/service"); requestBuilder.setCallback(new RequestCallback() { @Override// w w w . ja v a2s . c o m public void onResponseReceived(Request request, Response response) { if (response.getText().contains("OK")) Window.Location.reload(); else { MessageBox.alert(I18N.CONSTANTS.loginConnectErrorTitle(), I18N.CONSTANTS.loginConnectErrorBadLogin(), null); loginButton.setEnabled(true); loader.getElement().getStyle().setVisibility(Visibility.HIDDEN); } } @Override public void onError(Request request, Throwable exception) { MessageBox.alert(I18N.CONSTANTS.loginConnectErrorTitle(), exception.getMessage(), null); loginButton.setEnabled(true); loader.getElement().getStyle().setVisibility(Visibility.HIDDEN); } }); requestBuilder.setRequestData(query); requestBuilder.setHeader("Content-Type", "application/x-www-form-urlencoded"); loginButton.setEnabled(false); loader.getElement().getStyle().setVisibility(Visibility.VISIBLE); try { requestBuilder.send(); } catch (RequestException ex) { MessageBox.alert(I18N.CONSTANTS.loginConnectErrorTitle(), ex.getMessage(), null); } }
From source file:org.sigmah.shared.servlet.ServletRequestBuilder.java
License:Open Source License
/** * Sends the request with its optional parameter(s) (including {@code POST} parameters). * //from w w w . j ava 2 s .c o m * @param callback * The {@code RequestCallback}. * @throws ServletRequestException * If an error occurs during request call. */ public void send(final RequestCallback callback) throws ServletRequestException { final RequestBuilder requestBuilder = new RequestBuilder(requestMethod, urlBuilder.toString()); requestBuilder.setCallback(callback != null ? callback : Void); final StringBuilder builder = new StringBuilder(); if (ClientUtils.isNotEmpty(requestAttributes)) { final Iterator<String> iterator = requestAttributes.keySet().iterator(); while (iterator.hasNext()) { final String next = iterator.next(); final String attribute = requestAttributes.get(next); if (attribute != null) { builder.append(URL.encodeQueryString(next)); builder.append('='); builder.append(URL.encodeQueryString(attribute)); if (iterator.hasNext()) { builder.append('&'); } } } } if (isPostMethod()) { requestBuilder.setHeader("Content-Type", "application/x-www-form-urlencoded"); requestBuilder.setRequestData(builder.length() > 0 ? builder.toString() : null); } try { requestBuilder.send(); } catch (final RequestException e) { throw new ServletRequestException("Servlet request '" + builder + "' execution fails.", e); } }
From source file:org.sigmah.shared.servlet.URLs.java
License:Open Source License
/** * Checks if the given URL exist (using the HTTP GET method). * // ww w . j av a 2s .c o m * @param url * The URL to test. * @param callback * The callback. * Available results (depending on the response status code): * <ul> * <li><strong>200</strong> : {@code AsyncCallback#onSuccess(true)};</li> * <li><strong>404</strong> : {@code AsyncCallback#onSuccess(false)};</li> * <li><strong>other</strong> : {@link AsyncCallback#onFailure(Throwable)};</li> * </ul> */ public static void checkURL(final String url, final AsyncCallback<Boolean> callback) { // Builds the request. final RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.GET, url); requestBuilder.setCallback(new RequestCallback() { @Override public void onResponseReceived(Request request, Response response) { // The URL exists. if (response.getStatusCode() == Response.SC_OK) { callback.onSuccess(true); } // The URL doesn't exists. else if (response.getStatusCode() == Response.SC_NOT_FOUND) { callback.onSuccess(false); } // Other errors. else { callback.onFailure(null); } } @Override public void onError(Request request, Throwable exception) { callback.onFailure(exception); } }); // Sends the request. try { requestBuilder.send(); } catch (RequestException e) { callback.onFailure(e); } }
From source file:org.silverpeas.mobile.client.common.network.RestAuthenticationDispatcher.java
License:Open Source License
@Override public Request send(final Method method, final RequestBuilder builder) throws RequestException { String credentials = login + "@domain" + domainId + ":" + password; byte[] credentialsEncoded = Base64.encode(credentials.getBytes()); builder.setTimeoutMillis(SpMobileRequestBuilder.TIMEOUT); builder.setHeader("Authorization", "Basic " + convertByteArrayToString(credentialsEncoded)); return builder.send(); }
From source file:org.silverpeas.mobile.client.common.network.RestDispatcher.java
License:Open Source License
@Override public Request send(final Method method, final RequestBuilder builder) throws RequestException { builder.setTimeoutMillis(SpMobileRequestBuilder.TIMEOUT); builder.setHeader("Authorization", "Bearer " + SpMobil.getUser().getToken()); if (AuthentificationManager.getInstance().getHeader(AuthentificationManager.XSTKN) != null) { builder.setHeader(AuthentificationManager.XSTKN, AuthentificationManager.getInstance().getHeader(AuthentificationManager.XSTKN)); }/*from w w w . j a va 2 s .c o m*/ if (AuthentificationManager.getInstance().getHeader(AuthentificationManager.XSilverpeasSession) != null) { builder.setHeader(AuthentificationManager.XSilverpeasSession, AuthentificationManager.getInstance().getHeader(AuthentificationManager.XSilverpeasSession)); builder.setHeader("Cookie", "JSESSIONID=" + AuthentificationManager.getInstance().getHeader(AuthentificationManager.XSilverpeasSession)); } return builder.send(); }
From source file:org.spiffyui.client.rest.RESTility.java
License:Apache License
/** * <p>/*from w w w. ja v a 2 s . c o m*/ * Make an HTTP call and get the results as a JSON object. This method handles * cases like login, error parsing, and configuration requests. * </p> * * @param options the options for the REST request */ public static void callREST(RESTOptions options) { if (hasPotentialXss(options.getDataString())) { options.getCallback().onError(new RESTException(RESTException.XSS_ERROR, "", STRINGS.noServerContact(), new HashMap<String, String>(), -1, options.getURL())); return; } RESTILITY.m_restCalls.put(options.getCallback(), new RESTCallStruct(options.getURL(), options.getDataString(), options.getMethod(), options.shouldReplay(), options.getEtag())); RequestBuilder builder = new RESTRequestBuilder(options.getMethod().getMethod(), options.getURL()); /* Set our headers */ builder.setHeader("Accept", "application/json"); builder.setHeader("Accept-Charset", "UTF-8"); if (options.getHeaders() != null) { for (String k : options.getHeaders().keySet()) { builder.setHeader(k, options.getHeaders().get(k)); } } if (RESTILITY.m_bestLocale != null) { /* * The REST end points use the Accept-Language header to determine * the locale to use for the contents of the REST request. Normally * the browser will fill this in with the browser locale and that * doesn't always match the preferred locale from the Identity Vault * so we need to set this value with the correct preferred locale. */ builder.setHeader("Accept-Language", RESTILITY.m_bestLocale); } if (getUserToken() != null && getTokenServerUrl() != null) { builder.setHeader("Authorization", getFullAuthToken()); builder.setHeader("TS-URL", getTokenServerUrl()); } if (options.getEtag() != null) { builder.setHeader("If-Match", options.getEtag()); } if (options.getDataString() != null) { /* Set our request data */ builder.setRequestData(options.getDataString()); //b/c jaxb/jersey chokes when there is no data when content-type is json builder.setHeader("Content-Type", options.getContentType()); } builder.setCallback(RESTILITY.new RESTRequestCallback(options.getCallback())); try { /* If we are in the process of logging in then all other requests will just return with a 401 until the login is finished. We want to delay those requests until the login is complete when we will replay all of them. */ if (options.isLoginRequest() || !g_inLoginProcess) { builder.send(); } } catch (RequestException e) { MessageUtil.showFatalError(e.getMessage()); } }
From source file:org.swellrt.api.CustomJsoSearchBuilderImpl.java
License:Apache License
@Override public Request search(final Callback callback) { Preconditions.checkArgument(searchRequest != null, "call SearchBuilder.newSearch method to construct a new query"); Preconditions.checkArgument(searchRequest.getQuery() != null, "new query should be set"); String url = getUrl(searchRequest); LOG.trace().log("Performing a search query: [Query: ", searchRequest.getQuery(), ", Index: ", searchRequest.getIndex(), ", NumResults: ", searchRequest.getNumResults(), "]"); RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.GET, host + url); requestBuilder.setCallback(new RequestCallback() { @Override/*ww w.ja va 2s .c o m*/ public void onResponseReceived(Request request, Response response) { LOG.trace().log("Search response received: ", response.getText()); if (response.getStatusCode() != Response.SC_OK) { callback.onFailure("Got back status code " + response.getStatusCode()); } else if (!response.getHeader("Content-Type").startsWith("application/json")) { callback.onFailure("Search service did not return json"); } else { SearchResponseJsoImpl searchResponse; try { searchResponse = JsonMessage.parse(response.getText()); } catch (JsonException e) { callback.onFailure(e.getMessage()); return; } List<DigestSnapshot> digestSnapshots = SearchBuilderUtils .deserializeSearchResponse(searchResponse); callback.onSuccess(searchResponse.getTotalResults(), digestSnapshots); } } @Override public void onError(Request request, Throwable exception) { LOG.error().log("Search error: ", exception); callback.onFailure(exception.getMessage()); } }); try { requestBuilder.setIncludeCredentials(true); return requestBuilder.send(); } catch (RequestException e) { callback.onFailure(e.getMessage()); return null; } }