List of usage examples for com.vaadin.server VaadinService getCurrentRequest
public static VaadinRequest getCurrentRequest()
From source file:org.opencms.ui.dialogs.CmsNewDialog.java
License:Open Source License
/** * Initializes the view selector, using the given view id as an initial value.<p> * * @param startId the start view/*from w ww. ja v a2s. c om*/ * * @return the start view */ private CmsElementView initViews(CmsUUID startId) { Map<CmsUUID, CmsElementView> viewMap = OpenCms.getADEManager().getElementViews(A_CmsUI.getCmsObject()); List<CmsElementView> viewList = new ArrayList<CmsElementView>(viewMap.values()); Collections.sort(viewList, new Comparator<CmsElementView>() { public int compare(CmsElementView arg0, CmsElementView arg1) { return ComparisonChain.start().compare(arg0.getOrder(), arg1.getOrder()).result(); } }); m_viewSelector.setItemCaptionMode(ItemCaptionMode.EXPLICIT); m_typeHelper = createTypeHelper(); m_typeHelper.precomputeTypeLists(A_CmsUI.getCmsObject(), m_folderResource.getRootPath(), A_CmsUI.getCmsObject().getRequestContext().removeSiteRoot(m_folderResource.getRootPath()), viewList, null); // also collect types in LinkedHashMap to preserve order and ensure uniqueness LinkedHashMap<String, CmsResourceTypeBean> allTypes = Maps.newLinkedHashMap(); for (CmsElementView view : viewList) { if (view.hasPermission(A_CmsUI.getCmsObject(), m_folderResource)) { List<CmsResourceTypeBean> typeBeans = m_typeHelper.getPrecomputedTypes(view); if (typeBeans.isEmpty()) { continue; } for (CmsResourceTypeBean typeBean : typeBeans) { allTypes.put(typeBean.getType(), typeBean); } m_viewSelector.addItem(view.getId()); m_viewSelector.setItemCaption(view.getId(), view.getTitle(A_CmsUI.getCmsObject(), A_CmsUI.get().getLocale())); } } m_viewSelector.addItem(VIEW_ALL.getId()); m_viewSelector.setItemCaption(VIEW_ALL.getId(), CmsVaadinUtils.getMessageText(Messages.GUI_VIEW_ALL_0)); m_allTypes = Lists.newArrayList(allTypes.values()); if (allTypes.size() <= 8) { startId = ID_VIEW_ALL; } if (m_viewSelector.getItem(startId) == null) { startId = (CmsUUID) (m_viewSelector.getItemIds().iterator().next()); } m_viewSelector.addValueChangeListener(new ValueChangeListener() { private static final long serialVersionUID = 1L; public void valueChange(ValueChangeEvent event) { CmsUUID viewId = (CmsUUID) (event.getProperty().getValue()); CmsElementView selectedView; if (viewId.equals(ID_VIEW_ALL)) { selectedView = VIEW_ALL; } else { selectedView = OpenCms.getADEManager().getElementViews(A_CmsUI.getCmsObject()) .get(event.getProperty().getValue()); } init(selectedView, m_defaultLocationCheckbox.getValue().booleanValue()); if (selectedView != VIEW_ALL) { VaadinService.getCurrentRequest().getWrappedSession().setAttribute(SETTING_STANDARD_VIEW, (event.getProperty().getValue())); } } }); if (startId.equals(ID_VIEW_ALL)) { return VIEW_ALL; } else { return OpenCms.getADEManager().getElementViews(A_CmsUI.getCmsObject()).get(startId); } }
From source file:org.opencms.ui.login.CmsLoginController.java
License:Open Source License
/** * Logs the current user out by invalidating the session an reloading the current URI.<p> * Important: This works only within vaadin apps.<p> *///from ww w .j a v a2s .c om public static void logout() { CmsObject cms = A_CmsUI.getCmsObject(); if (UI.getCurrent() instanceof CmsAppWorkplaceUi) { ((CmsAppWorkplaceUi) UI.getCurrent()).onWindowClose(); } String loggedInUser = cms.getRequestContext().getCurrentUser().getName(); UI.getCurrent().getSession().close(); String loginLink = OpenCms.getLinkManager().substituteLinkForUnknownTarget(cms, CmsWorkplaceLoginHandler.LOGIN_HANDLER, false); VaadinService.getCurrentRequest().getWrappedSession().invalidate(); Page.getCurrent().setLocation(loginLink); // logout was successful if (LOG.isInfoEnabled()) { LOG.info(org.opencms.jsp.Messages.get().getBundle().key(org.opencms.jsp.Messages.LOG_LOGOUT_SUCCESFUL_3, loggedInUser, "{workplace logout option}", cms.getRequestContext().getRemoteAddress())); } }
From source file:org.opencms.ui.login.CmsLoginController.java
License:Open Source License
/** * Called when the user clicks on the login button.<p> *//*w ww. j a v a 2 s . co m*/ public void onClickLogin() { String user = m_ui.getUser(); String password = m_ui.getPassword(); CmsMessageContainer message = CmsLoginHelper.validateUserAndPasswordNotEmpty(user, password); CmsLoginMessage loginMessage = OpenCms.getLoginManager().getLoginMessage(); String storedMessage = null; if ((loginMessage != null) && !loginMessage.isLoginCurrentlyForbidden() && loginMessage.isActive()) { storedMessage = loginMessage.getMessage(); // If login is forbidden, we will get an error message anyway, so we don't need to store the message here } if (message != null) { String errorMessage = message.key(m_params.getLocale()); // m_ui.displayError(errorMessage); displayError(errorMessage, true); return; } String ou = m_ui.getOrgUnit(); String realUser = CmsStringUtil.joinPaths(ou, user); String pcType = m_ui.getPcType(); CmsObject currentCms = A_CmsUI.getCmsObject(); CmsUser userObj = null; try { try { userObj = currentCms.readUser(realUser, password); } catch (CmsException e) { LOG.warn(e.getLocalizedMessage(), e); message = org.opencms.workplace.Messages.get() .container(org.opencms.workplace.Messages.GUI_LOGIN_FAILED_0); displayError(message.key(m_params.getLocale()), true); return; } if (OpenCms.getLoginManager().canLockBecauseOfInactivity(currentCms, userObj)) { boolean locked = null != userObj.getAdditionalInfo().get(KEY_ACCOUNT_LOCKED); if (locked) { displayError(CmsInactiveUserMessages.getLockoutText(A_CmsUI.get().getLocale()), false); return; } } if (OpenCms.getLoginManager().requiresPasswordChange(currentCms, userObj)) { CmsChangePasswordDialog passwordDialog = new CmsChangePasswordDialog(currentCms, userObj, A_CmsUI.get().getLocale()); passwordDialog.setAdditionalMessage(getPasswordChangeMessage()); A_CmsUI.get().setContentToDialog( Messages.get().getBundle(A_CmsUI.get().getLocale()).key(Messages.GUI_PWCHANGE_HEADER_0) + userObj.getSimpleName(), passwordDialog); return; } currentCms.loginUser(realUser, password); if (LOG.isInfoEnabled()) { CmsRequestContext context = currentCms.getRequestContext(); LOG.info(org.opencms.jsp.Messages.get().getBundle().key( org.opencms.jsp.Messages.LOG_LOGIN_SUCCESSFUL_3, context.getCurrentUser().getName(), "{workplace login dialog}", context.getRemoteAddress())); } OpenCms.getSessionManager().updateSessionInfo(currentCms, (HttpServletRequest) VaadinService.getCurrentRequest()); if ((loginMessage != null) && loginMessage.isLoginCurrentlyForbidden()) { // we are an administrator storedMessage = org.opencms.workplace.Messages.get() .container(org.opencms.workplace.Messages.GUI_LOGIN_SUCCESS_WITH_MESSAGE_2, loginMessage.getMessage(), new Date(loginMessage.getTimeEnd())) .key(A_CmsUI.get().getLocale()); } if (storedMessage != null) { OpenCms.getSessionManager().sendBroadcast(null, storedMessage, currentCms.getRequestContext().getCurrentUser()); } CmsWorkplaceSettings settings = CmsLoginHelper.initSiteAndProject(currentCms); CmsLoginHelper.setCookieData(pcType, user, ou, (VaadinServletRequest) (VaadinService.getCurrentRequest()), (VaadinServletResponse) (VaadinService.getCurrentResponse())); VaadinService.getCurrentRequest().getWrappedSession() .setAttribute(CmsWorkplaceManager.SESSION_WORKPLACE_SETTINGS, settings); final String loginTarget = getLoginTarget(currentCms, settings, m_params.getRequestedResource()); final boolean isPublicPC = CmsLoginForm.PC_TYPE_PUBLIC.equals(pcType); if (OpenCms.getLoginManager().requiresUserDataCheck(currentCms, userObj)) { I_CmsDialogContext context = new A_CmsDialogContext("", ContextType.appToolbar, null) { @Override public void finish(CmsProject project, String siteRoot) { finish(null); } @Override public void finish(Collection<CmsUUID> result) { m_ui.openLoginTarget(loginTarget, isPublicPC); } public void focus(CmsUUID structureId) { // nothing to do } public List<CmsUUID> getAllStructureIdsInView() { return null; } @Override public void start(String title, Component dialog, DialogWidth style) { if (dialog != null) { m_window = CmsBasicDialog.prepareWindow(style); m_window.setCaption(title); m_window.setContent(dialog); UI.getCurrent().addWindow(m_window); if (dialog instanceof CmsBasicDialog) { ((CmsBasicDialog) dialog).initActionHandler(m_window); } } } public void updateUserInfo() { // not supported } }; CmsUser u = currentCms.readUser(userObj.getId()); u.setAdditionalInfo(CmsUserSettings.ADDITIONAL_INFO_LAST_USER_DATA_CHECK, Long.toString(System.currentTimeMillis())); currentCms.writeUser(u); CmsUserDataDialog dialog = new CmsUserDataDialog(context, true); context.start(dialog.getTitle(UI.getCurrent().getLocale()), dialog); } else { m_ui.openLoginTarget(loginTarget, isPublicPC); } } catch (Exception e) { // there was an error during login if (e instanceof CmsException) { CmsMessageContainer exceptionMessage = ((CmsException) e).getMessageContainer(); if (org.opencms.security.Messages.ERR_LOGIN_FAILED_DISABLED_2 == exceptionMessage.getKey()) { // the user account is disabled message = org.opencms.workplace.Messages.get() .container(org.opencms.workplace.Messages.GUI_LOGIN_FAILED_DISABLED_0); } else if (org.opencms.security.Messages.ERR_LOGIN_FAILED_TEMP_DISABLED_4 == exceptionMessage .getKey()) { // the user account is temporarily disabled because of too many login failures message = org.opencms.workplace.Messages.get() .container(org.opencms.workplace.Messages.GUI_LOGIN_FAILED_TEMP_DISABLED_0); } else if (org.opencms.security.Messages.ERR_LOGIN_FAILED_WITH_MESSAGE_1 == exceptionMessage .getKey()) { // all logins have been disabled be the Administration CmsLoginMessage loginMessage2 = OpenCms.getLoginManager().getLoginMessage(); if (loginMessage2 != null) { message = org.opencms.workplace.Messages.get().container( org.opencms.workplace.Messages.GUI_LOGIN_FAILED_WITH_MESSAGE_1, loginMessage2.getMessage()); } } } if (message == null) { if (e instanceof CmsCustomLoginException) { message = ((CmsCustomLoginException) e).getMessageContainer(); } else { // any other error - display default message message = org.opencms.workplace.Messages.get() .container(org.opencms.workplace.Messages.GUI_LOGIN_FAILED_0); } } // m_ui.displayError(message.key(m_params.getLocale())); if (e instanceof CmsException) { CmsJspLoginBean.logLoginException(currentCms.getRequestContext(), user, (CmsException) e); } else { LOG.error(e.getLocalizedMessage(), e); } displayError(message.key(m_params.getLocale()), false); return; } }
From source file:org.opencms.ui.login.CmsLoginUI.java
License:Open Source License
/** * Returns the current users workplace settings.<p> * * @param cms the CMS context/*w ww. j a v a2 s . c o m*/ * @param session the session * * @return the settings */ private static CmsWorkplaceSettings getWorkplaceSettings(CmsObject cms, HttpSession session) { CmsWorkplaceSettings settings = (CmsWorkplaceSettings) session .getAttribute(CmsWorkplaceManager.SESSION_WORKPLACE_SETTINGS); if (settings == null) { settings = CmsLoginHelper.initSiteAndProject(cms); if (VaadinService.getCurrentRequest() != null) { VaadinService.getCurrentRequest().getWrappedSession() .setAttribute(CmsWorkplaceManager.SESSION_WORKPLACE_SETTINGS, settings); } else { session.setAttribute(CmsWorkplaceManager.SESSION_WORKPLACE_SETTINGS, settings); } } return settings; }
From source file:org.opencms.ui.login.CmsLoginUI.java
License:Open Source License
/** * Opens the login target for a logged in user.<p> * * @param loginTarget the login target/*from w w w . j a va 2 s . c om*/ * @param isPublicPC the public PC flag */ public void openLoginTarget(String loginTarget, boolean isPublicPC) { // login was successful, remove login init data from session VaadinService.getCurrentRequest().getWrappedSession().removeAttribute(INIT_DATA_SESSION_ATTR); m_targetOpener.openTarget(loginTarget, isPublicPC); }
From source file:org.ow2.sirocco.cloudmanager.MyUI.java
License:Open Source License
private void logout() { this.getUI().getSession().close(); // UI.getCurrent().close(); // Invalidate underlying session instead if login info is stored there VaadinService.getCurrentRequest().getWrappedSession().invalidate(); // Redirect to avoid keeping the removed UI open in the browser this.getUI().getPage() .setLocation(VaadinServletService.getCurrentServletRequest().getContextPath() + "/logout.jsp"); }
From source file:org.vaadin.addons.sitekit.site.AbstractSiteUI.java
License:Apache License
@Override protected final void init(final VaadinRequest request) { final VaadinServletRequest servletRequest = (VaadinServletRequest) VaadinService.getCurrentRequest(); final StringBuffer urlBuilder = servletRequest.getHttpServletRequest().getRequestURL(); final String queryString = servletRequest.getHttpServletRequest().getQueryString(); if (queryString != null) { urlBuilder.append('?'); urlBuilder.append(queryString);// ww w .j ava 2 s . co m } navigator = new SiteNavigator(this, this); site = constructSite(request); navigator.addViewChangeListener(site); navigator.addProvider(site); site.initialize(); }
From source file:org.vaadin.addons.sitekit.site.DefaultSiteUI.java
License:Apache License
@Override protected Site constructSite(final VaadinRequest request) { final SiteContext siteContext = new SiteContext(); // Construct entity manager for this site context. final EntityManager entityManager = entityManagerFactory.createEntityManager(); siteContext.putObject(EntityManager.class, entityManager); // Choose company for this site context. final VaadinServletRequest servletRequest = (VaadinServletRequest) VaadinService.getCurrentRequest(); final String hostName = servletRequest.getHttpServletRequest().getServerName(); final Company company = CompanyDao.getCompany(entityManager, hostName); if (company == null) { siteContext.putObject(Company.class, CompanyDao.getCompany(entityManager, "*")); } else {//from w w w .ja v a 2 s.c o m siteContext.putObject(Company.class, company); } return new Site(SiteMode.PRODUCTION, contentProvider, localizationProvider, securityProvider, siteContext); }
From source file:org.vaadin.addons.sitekit.viewlet.anonymous.login.ForgotPasswordFlowlet.java
License:Apache License
@Override public void initialize() { pinProperty = new ObjectProperty<String>(null, String.class); emailAddressProperty = new ObjectProperty<String>(null, String.class); final List<FieldDescriptor> fieldDescriptors = new ArrayList<FieldDescriptor>(); fieldDescriptors.add(new FieldDescriptor("pin", getSite().localize("input-password-reset-pin"), TextField.class, null, 150, null, String.class, null, true, true, true)); fieldDescriptors.add(new FieldDescriptor("emailAddress", getSite().localize("input-email-address"), TextField.class, null, 150, null, String.class, null, false, true, true) .addValidator(new EmailValidator("Email address is not valid."))); editor = new ValidatingEditor(fieldDescriptors); final Button resetPasswordButton = new Button(getSite().localize("button-reset-password")); resetPasswordButton.addListener(new ClickListener() { /** The default serial version ID. */ private static final long serialVersionUID = 1L; @Override/* w w w . java 2 s . com*/ public void buttonClick(final ClickEvent event) { editor.commit(); final EntityManager entityManager = getSite().getSiteContext().getObject(EntityManager.class); final Company company = getSite().getSiteContext().getObject(Company.class); final User user = UserDao.getUser(entityManager, company, (String) emailAddressProperty.getValue()); if (user == null) { Notification.show(getSite().localize("message-user-email-address-not-registered"), Notification.Type.WARNING_MESSAGE); return; } final List<EmailPasswordReset> emailPasswordResets = UserDao .getEmailPasswordResetByEmailAddress(entityManager, user); final Date now = new Date(); for (final EmailPasswordReset emailPasswordReset : emailPasswordResets) { if (now.getTime() - emailPasswordReset.getCreated().getTime() < 24 * 60 * 60 * 1000) { Notification.show(getSite().localize("message-password-reset-email-already-sent"), Notification.Type.ERROR_MESSAGE); return; } else { entityManager.getTransaction().begin(); try { entityManager.remove(emailPasswordReset); entityManager.getTransaction().commit(); } catch (final Exception e) { if (entityManager.getTransaction().isActive()) { entityManager.getTransaction().rollback(); } throw new SiteException("Error removing old email password reset.", e); } } } try { final String pin = (String) pinProperty.getValue(); final byte[] pinAndSaltBytes = (user.getEmailAddress() + ":" + pin).getBytes("UTF-8"); final MessageDigest md = MessageDigest.getInstance("SHA-256"); final byte[] pinAndSaltDigest = md.digest(pinAndSaltBytes); final EmailPasswordReset emailPasswordReset = new EmailPasswordReset(); emailPasswordReset.setUser(user); emailPasswordReset.setPinHash(StringUtil.toHexString(pinAndSaltDigest)); emailPasswordReset.setCreated(now); entityManager.getTransaction().begin(); try { entityManager.persist(emailPasswordReset); entityManager.getTransaction().commit(); } catch (final Exception e) { if (entityManager.getTransaction().isActive()) { entityManager.getTransaction().rollback(); } throw new SiteException("Error saving email password reset", e); } final String url = company.getUrl() + "#!reset/" + emailPasswordReset.getEmailPasswordResetId(); final Thread emailThread = new Thread(new Runnable() { @Override public void run() { EmailUtil.send(PropertiesUtil.getProperty("site", "smtp-host"), user.getEmailAddress(), company.getSupportEmailAddress(), "Password Reset Link", "Password reset has been requested for your user account." + "You can perform the reset using the following link: " + url); } }); emailThread.start(); Notification.show( getSite().localize("message-password-reset-email-sent") + getSite().localize("message-your-password-reset-pin-is") + pin, Notification.Type.WARNING_MESSAGE); final HttpServletRequest request = ((VaadinServletRequest) VaadinService.getCurrentRequest()) .getHttpServletRequest(); LOGGER.info("Password reset email sent to " + user.getEmailAddress() + " (IP: " + request.getRemoteHost() + ":" + request.getRemotePort() + ")"); getFlow().back(); } catch (final Exception e) { LOGGER.error("Error preparing password reset.", e); Notification.show(getSite().localize("message-password-reset-prepare-error"), Notification.TYPE_WARNING_MESSAGE); } reset(); } }); editor.addListener(new ValidatingEditorStateListener() { @Override public void editorStateChanged(final ValidatingEditor source) { if (source.isValid()) { resetPasswordButton.setEnabled(true); } else { resetPasswordButton.setEnabled(false); } } }); reset(); final VerticalLayout panel = new VerticalLayout(); panel.addComponent(editor); panel.addComponent(resetPasswordButton); panel.setSpacing(true); final HorizontalLayout mainLayout = new HorizontalLayout(); mainLayout.addComponent(panel); setViewContent(mainLayout); }
From source file:org.vaadin.addons.sitekit.viewlet.anonymous.login.LoginFlowlet.java
License:Apache License
@Override public void onLogin(final LoginEvent event) { if (event.getLoginParameter("username") == null) { Notification.show(getSite().localize("message-login-failed"), Notification.TYPE_WARNING_MESSAGE); return;/* w w w . j av a 2 s . c o m*/ } if (event.getLoginParameter("password") == null) { Notification.show(getSite().localize("message-login-failed"), Notification.TYPE_WARNING_MESSAGE); return; } final HttpServletRequest request = ((VaadinServletRequest) VaadinService.getCurrentRequest()) .getHttpServletRequest(); final String userEmailAddress = event.getLoginParameter("username"); try { final EntityManager entityManager = getSite().getSiteContext().getObject(EntityManager.class); final Company company = getSite().getSiteContext().getObject(Company.class); final User user = UserDao.getUser(entityManager, company, userEmailAddress); if (user == null) { LOGGER.warn("User login failed due to not registered email address: " + userEmailAddress + " (IP: " + request.getRemoteHost() + ":" + request.getRemotePort() + ")"); Notification.show(getSite().localize("message-login-failed"), Notification.TYPE_WARNING_MESSAGE); return; } if (user.isLockedOut()) { LOGGER.warn("User login failed due to user being locked out: " + userEmailAddress + " (IP: " + request.getRemoteHost() + ":" + request.getRemotePort() + ")"); Notification.show(getSite().localize("message-login-failed"), Notification.TYPE_WARNING_MESSAGE); return; } final List<UserDirectory> userDirectories = UserDirectoryDao.getUserDirectories(entityManager, company); final String remoteIpAddress = request.getRemoteAddr(); boolean directoryLoginAttempted = false; for (final UserDirectory userDirectory : userDirectories) { if (!userDirectory.isEnabled()) { continue; } final String[] subnets = userDirectory.getSubNetWhiteList().split(","); for (final String subnet : subnets) { final CidrUtil cidrUtils = new CidrUtil(subnet); if (cidrUtils.isInRange(remoteIpAddress)) { directoryLoginAttempted = attemptDirectoryLogin(event, request, entityManager, company, user, userDirectory); break; } } if (directoryLoginAttempted) { break; } } if (!directoryLoginAttempted) { attemptLocalLogin(event, request, entityManager, company, user); } } catch (final Exception e) { LOGGER.error("Error logging in user: " + userEmailAddress + " (IP: " + request.getRemoteHost() + ":" + request.getRemotePort() + ")", e); Notification.show(getSite().localize("message-login-error"), Notification.TYPE_ERROR_MESSAGE); } }