List of usage examples for com.google.gwt.http.client RequestBuilder send
public Request send() throws RequestException
From source file:org.ow2.proactive_grid_cloud_portal.rm.client.nodesource.serialization.load.catalog.ImportFromCatalogPanel.java
License:Open Source License
private void requestNodeSourceConfiguration() { String selectedNodeSourceInList = this.nodeSourceListBox.getSelectedValue(); if (!selectedNodeSourceInList.equals(this.selectItemGenericEntry)) { String nodeSourceConfigurationRequestUrl = new CatalogUrlBuilder().getCatalogUrl() + "/buckets/" + this.importFromCatalogPanelFeeder.getBucketNameForNodeSource(selectedNodeSourceInList) + "/resources/" + selectedNodeSourceInList + "/raw"; RequestBuilder nodeSourceConfigurationRequest = new RequestBuilder(RequestBuilder.GET, nodeSourceConfigurationRequestUrl); nodeSourceConfigurationRequest.setHeader(CatalogConstants.SESSION_ID_PARAM, LoginModel.getInstance().getSessionId()); nodeSourceConfigurationRequest.setCallback(nodeSourceConfigurationRequestCallback); try {/*from w ww . jav a 2s. c o m*/ nodeSourceConfigurationRequest.send(); } catch (RequestException e) { throw new IllegalStateException("GET " + nodeSourceConfigurationRequestUrl + " failed", e); } } }
From source file:org.ow2.proactive_grid_cloud_portal.scheduler.client.CalendarInfoWindow.java
License:Open Source License
private void loadWindowsContent(RequestBuilder.Method method) { String host = com.google.gwt.user.client.Window.Location.getHostName(); String user = LoginModel.getInstance().getLogin(); StringBuilder requestUrl = new StringBuilder(); if ("http".equals(SchedulerConfig.get().getCalendarServerProtocol())) { requestUrl.append("http://" + host + ":" + SchedulerConfig.get().getCalendarServerHttpPort()); } else {/*from w w w. j a v a 2 s . c o m*/ requestUrl.append("https://" + host + ":" + SchedulerConfig.get().getCalendarServerHttpsPort()); } requestUrl.append("/calendar-service/private-urls/" + user + "/"); RequestBuilder rb = new RequestBuilder(method, requestUrl.toString()); rb.setCallback(new RequestCallback() { @Override public void onResponseReceived(Request request, Response response) { if (200 == response.getStatusCode()) { text.setContents(contentBuilder.buildContentString(response.getText())); } else { text.setContents("Error : status code " + response.getStatusCode()); } refreshWindow(text); } private void refreshWindow(HTMLPane text) { pane.clear(); root.clear(); window.clear(); pane.addMember(img); pane.addMember(text); root.addMember(pane); root.addMember(buttons); window.addItem(root); window.show(); } @Override public void onError(Request request, Throwable exception) { text.setContents("Exception : " + exception.getMessage()); refreshWindow(text); } }); try { rb.send(); } catch (RequestException e) { com.google.gwt.user.client.Window.alert("error = " + e.getMessage()); } }
From source file:org.pentaho.reporting.platform.plugin.gwt.client.ParameterControllerPanel.java
License:Open Source License
public void fetchParameters(final ParameterSubmitMode submitMode) { boolean paginate = false; container.showBlank();//w ww .ja va 2s. co m if (submitMode == ParameterSubmitMode.INITIAL) { paginate = false; } else if (submitMode == ParameterSubmitMode.USERINPUT) { if (parameterDefinition == null || parameterDefinition.isAllowAutosubmit() == false) { // only parameter without pagination of content .. paginate = false; } else { // user enabled auto-submit, so lets give him the full package.. paginate = true; } } else { // manual requests always get the full treatment .. paginate = true; } final RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.GET, ReportViewerUtil.buildParameterUrl(paginate, parameterMap, parameterDefinition)); parameterRequestCallback.setSubmitMode(submitMode); requestBuilder.setCallback(parameterRequestCallback); try { setEnabled(false); requestBuilder.send(); } catch (RequestException re) { Window.alert(messages.getString("couldNotFetchParameters", //$NON-NLS-1$ "Could not fetch parameter metadata from server.")); //$NON-NLS-1$ setEnabled(true); } }
From source file:org.qipki.clients.web.client.ui.widgets.ExternalResourcePanel.java
License:Open Source License
public void load(final String url, final RequestCallback callback) { RequestBuilder rb = new RequestBuilder(RequestBuilder.GET, url); rb.setCallback(new RequestCallback() { @Override/*from w w w. j a v a 2s.c om*/ public void onResponseReceived(final Request request, final Response response) { new Timer() { @Override public void run() { panel.clear(); panel.add(new HTMLPanel(response.getText())); ExternalResourcePanel.this.url = url; callback.onResponseReceived(request, response); } }.schedule(2000); } @Override public void onError(Request request, Throwable exception) { panel.clear(); panel.add(new Label("Request ERROR: " + exception.getMessage())); callback.onError(request, exception); } }); panel.clear(); if (loadingPanel != null) { panel.setWidget(loadingPanel); } try { rb.send(); } catch (RequestException ex) { panel.add(new Label("Request EXCEPTION: " + ex.getMessage())); } }
From source file:org.rapla.rest.gwtjsonrpc.client.impl.JsonCall.java
License:Apache License
protected void send(RequestBuilder rb) { try {// ww w .ja v a 2 s . com if (token != null) { rb.setHeader("Authorization", "Bearer " + token); } attempts++; rb.send(); } catch (RequestException e) { callback.onFailure(e); return; } if (attempts == 1) { RpcStartEvent.fire(this); } }
From source file:org.rhq.coregui.client.LoginView.java
License:Open Source License
private void login(final String username, final String password) { loginButton.setDisabled(true);/*from w ww. ja v a 2 s . c om*/ try { RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.POST, "/portal/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(); fakeForm.setVisible(false); loginShowing = false; UserSessionManager.login(username, password); setLoginError(null); } else { handleError(statusCode); } } public void onError(Request request, Throwable exception) { handleError(0); } }); requestBuilder.send(); } catch (Exception e) { handleError(0); } }
From source file:org.rhq.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 . com b.setCallback(new RequestCallback() { public void onResponseReceived(final Request request, final Response response) { Log.info("response text = " + response.getText()); String sessionIdString = response.getText(); if (sessionIdString.startsWith("booting")) { // "booting" is the string we get back from SessionAccessServlet if StartupBean hasn't finished new LoginView().showLoginDialog(MSG.view_core_serverInitializing()); return; } // If a session is active it will return valid session strings if (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().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: " + sessionTimeout); coreGuiSessionTimer.schedule(sessionTimeout); } else { // existing sessions should expire SESSION_TIMEOUT minutes from the previous access time long expiryTime = lastAccess + sessionTimeout; 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 > sessionTimeout) { expiryMillis = sessionTimeout; // 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().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().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().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().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().showLoginDialog(); return; } } public void onError(Request request, Throwable exception) { callback.onFailure(exception); } }); b.send(); } catch (RequestException e) { callback.onFailure(e); } }
From source file:org.rhq.coregui.client.UserSessionManager.java
License:Open Source License
/** Takes an updated Subject and signals SessionAccessServlet in portal.war to update the associated WebUser * because for this specific authenticated user. Currently assumes Subject instances returned from SubjectManagerBean.processSubjectForLdap. * This should only ever be called by UI logic in LDAP logins(case insensitive/new registration) after RHQ sessions have been renewed server side * correctly.//from w ww. j a v a 2 s . c om * * @param loggedInSubject Subject with updated session */ private static void scheduleWebUserUpdate(final Subject loggedInSubject) { final RequestBuilder b = createSessionAccessRequestBuilder(); //add header to signal SessionAccessServlet to update the WebUser for the successfully logged in user b.setHeader(HEADER_WEB_USER_UPDATE, String.valueOf(loggedInSubject.getSessionId())); try { b.setCallback(new RequestCallback() { public void onResponseReceived(final Request request, final Response response) { Log.trace("Successfully submitted request to update server side WebUser for subject '" + loggedInSubject.getName() + "'."); } @Override public void onError(Request request, Throwable exception) { Log.trace("Failed to submit request to update server side WebUser for subject '" + loggedInSubject.getName() + "'." + ((exception != null ? exception.getMessage() : " Exception ref null."))); } }); b.send(); } catch (RequestException e) { Log.trace("Failure submitting update request for WebUser '" + loggedInSubject.getName() + "'." + (e != null ? e.getMessage() : "RequestException reference is null.")); } }
From source file:org.rhq.coregui.client.UserSessionManager.java
License:Open Source License
private static void refreshHttpSession() { final RequestBuilder b = createSessionAccessRequestBuilder(); // add header to signal SessionAccessServlet to refresh the http lastAccess time (basically a no-op as the // request will make that happen). b.setHeader(HEADER_LAST_ACCESS_UPDATE, "dummy"); try {/*from w w w. j a v a2 s .c o m*/ b.setCallback(new RequestCallback() { public void onResponseReceived(final Request request, final Response response) { Log.trace("Successfully submitted request to update HTTP accessTime"); } @Override public void onError(Request request, Throwable t) { Log.trace("Error updating HTTP accessTime", t); } }); b.send(); } catch (RequestException e) { Log.trace("Error requesting update of HTTP accessTime", e); } finally { httpSessionTimer.schedule(SESSION_ACCESS_REFRESH); } }
From source file:org.rhq.enterprise.gui.coregui.client.inventory.groups.detail.ResourceGroupContextMenu.java
License:Open Source License
private MenuItem buildMetricsMenu(final ResourceType type) { 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_loadFail_dashboards(), caught); }/*from w w w . j ava 2 s . com*/ public void onSuccess(PageList<Dashboard> result) { if (type.getMetricDefinitions() != null) { //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_groupGraph(), ResourceGroupGraphPortlet.KEY, 250); p.getConfiguration() .put(new PropertySimple( ResourceGroupGraphPortlet.CFG_RESOURCE_GROUP_ID, group.getId())); p.getConfiguration().put(new PropertySimple( ResourceGroupGraphPortlet.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) { String msg = MSG .view_tree_common_contextMenu_saveChartToDashboardSuccessful( result.getName()); CoreGUI.getMessageCenter().notify( new Message(msg, Message.Severity.Info)); } }); } }); //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}') String grpGraphElements = ""; if (isAutoGroup) { grpGraphElements += "ag,"; } else { grpGraphElements += "cg,"; } grpGraphElements += group.getId() + "," + def.getId(); if (isAutoGroup) {//need to postpend the resource type as third element grpGraphElements += "," + group.getResourceType().getId(); } //construct portal.war url to access String baseUrl = "/resource/common/monitor/visibility/IndicatorCharts.do"; //No need to rebuild the autogroup url as everything handled as a compatible group now // if (isAutoGroup) { // //Ex. ?parent=10001&ctype=1013&view=Default // baseUrl += "?parent=" + group.getAutoGroupParentResource().getId() // + "&ctype=" // + group.getResourceType().getId(); // jsCode = "ag," + group.getAutoGroupParentResource().getId() + "," // + def.getId() + "," // + group.getResourceType().getId(); // } else { //Ex. ?groupId=10001&view=Default baseUrl += "?groupId=" + group.getId(); baseUrl += "&view=Default"; baseUrl += "&action=addChart&metric=" + grpGraphElements; 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 of onClick definition });//end of onClick Handler definition } //end of Monitoring/Graphs view check } //end of dashabord iteration } //end of check for Measurement } //end of metric definition iteration } } }); measurements.setSubmenu(measurementsSubMenu); return measurements; }