List of usage examples for com.google.gwt.http.client RequestBuilder setCallback
public void setCallback(RequestCallback callback)
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 ww w. ja v a 2 s . c o 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 (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 www . 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 va2 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 ww w.j a v a 2 s . co m*/ 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; }
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 ww. ja va2 s . co 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);//w ww .j a v a 2 s .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 w ww . j av a 2 s. c o 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/*ww w . j a v a 2 s .co 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 a v a 2 s . co 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). * // w w w. j a v a 2s . c om * @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); } }