/** * Create a VaadinSession * @param locale Client locale * @return VaadinSession instance * @throws Exception Failed to create session */ protected VaadinSession createVaadinSession(Locale locale) throws Exception { WrappedSession wrappedSession = mock(WrappedSession.class); VaadinServletService vaadinService = mock(VaadinServletService.class); when(vaadinService.getDeploymentConfiguration()) .thenReturn(new DefaultDeploymentConfiguration(VaadinServletService.class, getDeploymentProperties())); VaadinSession session = mock(VaadinSession.class); when(session.getState()).thenReturn(VaadinSession.State.OPEN); when(session.getSession()).thenReturn(wrappedSession); when(session.getService()).thenReturn(vaadinService); when(session.getSession().getId()).thenReturn(TEST_SESSION_ID); when(session.hasLock()).thenReturn(true); when(session.getLocale()).thenReturn(locale != null ? locale : Locale.US); return session; }
@SuppressWarnings("unchecked") @Override public <T> Optional<T> get(String resourceKey, Class<T> resourceType) throws TypeMismatchException { ObjectUtils.argumentNotNull(resourceKey, "Resource key must be not null"); ObjectUtils.argumentNotNull(resourceType, "Resource type must be not null"); final VaadinSession session = VaadinSession.getCurrent(); if (session != null) { Object value = session.getAttribute(resourceKey); if (value != null) { // check type if (!TypeUtils.isAssignable(value.getClass(), resourceType)) { throw new TypeMismatchException("<" + NAME + "> Actual resource type [" + value.getClass().getName() + "] and required resource type [" + resourceType.getName() + "] mismatch"); } return Optional.of((T) value); } } return Optional.empty(); }
@SuppressWarnings("unchecked") @Override public <T> Optional<T> put(String resourceKey, T value) throws UnsupportedOperationException { ObjectUtils.argumentNotNull(resourceKey, "Resource key must be not null"); final VaadinSession session = VaadinSession.getCurrent(); if (session == null) { throw new IllegalStateException("Current VaadinSession not available"); } Object exist = session.getAttribute(resourceKey); session.setAttribute(resourceKey, value); try { T previous = (T) exist; return Optional.ofNullable(previous); } catch (@SuppressWarnings("unused") Exception e) { // ignore return Optional.empty(); } }
@SuppressWarnings("unchecked") @Override public <T> Optional<T> putIfAbsent(String resourceKey, T value) throws UnsupportedOperationException { ObjectUtils.argumentNotNull(resourceKey, "Resource key must be not null"); final VaadinSession session = VaadinSession.getCurrent(); if (session == null) { throw new IllegalStateException("Current VaadinSession not available"); } if (value != null) { synchronized (session) { Object exist = session.getAttribute(resourceKey); if (exist == null) { session.setAttribute(resourceKey, value); } else { return Optional.of((T) exist); } } } return Optional.empty(); }
@Test public void testFromRequest() { final DeviceInfo di = DeviceInfo.create(VaadinService.getCurrentRequest()); assertNotNull(di); VaadinSession session = mock(VaadinSession.class); when(session.getState()).thenReturn(VaadinSession.State.OPEN); when(session.getSession()).thenReturn(mock(WrappedSession.class)); when(session.getService()).thenReturn(mock(VaadinServletService.class)); when(session.getSession().getId()).thenReturn(TEST_SESSION_ID); when(session.hasLock()).thenReturn(true); when(session.getLocale()).thenReturn(Locale.US); when(session.getAttribute(DeviceInfo.SESSION_ATTRIBUTE_NAME)).thenReturn(di); CurrentInstance.set(VaadinSession.class, session); Optional<DeviceInfo> odi = DeviceInfo.get(); assertTrue(odi.isPresent()); }
/** * Confirme la fermeture d'une session * @param session la session a kill */ public void confirmKillSession(SessionPresentation session) { SessionPresentation user = (SessionPresentation) uisContainer.getParent(session); String userName = applicationContext.getMessage("user.notconnected", null, UI.getCurrent().getLocale()); if (user != null){ userName = user.getId(); } ConfirmWindow confirmWindow = new ConfirmWindow(applicationContext.getMessage("admin.uiList.confirmKillSession", new Object[]{session.getId(), userName}, UI.getCurrent().getLocale())); confirmWindow.addBtnOuiListener(e -> { VaadinSession vaadinSession = uiController.getSession(session); Collection<SessionPresentation> listeUI = null; if (uisContainer.getChildren(session) != null){ listeUI = (Collection<SessionPresentation>) uisContainer.getChildren(session); } if (vaadinSession != null){ uiController.killSession(vaadinSession, listeUI); }else{ Notification.show(applicationContext.getMessage("admin.uiList.confirmKillSession.error", null, UI.getCurrent().getLocale()), Type.WARNING_MESSAGE); } removeElement(session); }); UI.getCurrent().addWindow(confirmWindow); }
/** * @param user * @return un user */ public UserDetails getUser(SessionPresentation user){ for (MainUI ui : getUis()){ try{ VaadinSession session = ui.getSession(); if (session == null || session.getSession()==null){ return null; } SecurityContext securityContext = (SecurityContext) session.getSession().getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY); if (securityContext==null || securityContext.getAuthentication()==null){ return null; }else{ UserDetails details = (UserDetails) securityContext.getAuthentication().getPrincipal(); if (details!=null && details.getUsername().equals(user.getId())){ return details; } } }catch (Exception e){} } return null; }
private void closeUserVaadinSessions(String loginName) { // CopyOnWriteArrayList is thread safe for iteration under update for (HttpSession session : this.sessions) { for (VaadinSession vaadinSession : VaadinSession.getAllSessions(session)) { Object userName = vaadinSession.getAttribute("user"); if (loginName == null || loginName.equals(userName)) { vaadinSession.close(); // Redirect all UIs to force the close for (UI ui : vaadinSession.getUIs()) { ui.access(() -> { ui.getPage().setLocation("/"); }); } } } } }
/** * Every incoming request should set the current user context */ @Override protected VaadinServletRequest createVaadinRequest(HttpServletRequest request) { VaadinServletRequest vaadinRequest = super.createVaadinRequest(request); VaadinSession vaadinSession; try { vaadinSession = getService().findVaadinSession(vaadinRequest); } catch (Exception e) { // This exception will be handled later when we try to service // the request vaadinSession = null; } if(vaadinSession != null) { this.userContext.setUser((String) vaadinSession.getAttribute("user")); } else { this.userContext.setUser(null); } return vaadinRequest; }
@Override protected void init(VaadinRequest vaadinRequest) { VaadinSession.getCurrent().getSession().setMaxInactiveInterval(-1); Page.getCurrent().setTitle("Tiny Pounder (" + VERSION + ")"); setupLayout(); addKitControls(); updateKitControls(); initVoltronConfigLayout(); initVoltronControlLayout(); initRuntimeLayout(); addExitCloseTab(); updateServerGrid(); // refresh consoles if any consoleRefresher = scheduledExecutorService.scheduleWithFixedDelay( () -> access(() -> runningServers.values().forEach(RunningServer::refreshConsole)), 2, 2, TimeUnit.SECONDS); }
@Override public void dashboardNameEdited(final Imot imot) throws Exception { // titleLabel.setValue(name); User user = (User) VaadinSession.getCurrent().getAttribute(User.class.getName()); if (user.role().equals("guest")) { return; } GoogleMapMarker marker = imot.getLocation().marker().googleMarker(); googleMap.addMarker(marker); googleMap.setCenter(centerSofia); user.addImot(imot); new UserVertex(user).saveOrUpdateInNewTX(); }
/** * Updates the correct content for this UI based on the current user status. * If the user is logged in with appropriate privileges, main view is shown. * Otherwise login view is shown. */ private void updateContent() { User user = (User) VaadinSession.getCurrent().getAttribute( User.class.getName()); if (user == null) { user = UserBean.builder() .oauthIdentifier("") .firstName("guest") .lastName("") .role("guest") .build(); VaadinSession.getCurrent().setAttribute(User.class.getName(), user); } setContent(new MainView()); removeStyleName("loginview"); getNavigator().navigateTo(getNavigator().getState()); // } else { // setContent(new LoginView()); // addStyleName("loginview"); // } }
@Override public String getMainDivId(VaadinSession session, VaadinRequest request, Class<? extends UI> uiClass) { String appId = request.getPathInfo(); if (appId == null || "".equals(appId) || "/".equals(appId)) { appId = "ROOT"; } appId = appId.replaceAll("[^a-zA-Z0-9]", ""); // Add hashCode to the end, so that it is still (sort of) // predictable, but indicates that it should not be used in CSS // and // such: int hashCode = appId.hashCode(); if (hashCode < 0) { hashCode = -hashCode; } appId = appId + "-" + hashCode; return appId; }
@SuppressWarnings("deprecation") @Override protected void handleAdditionalDependencies(List<Class<? extends ClientConnector>> newConnectorTypes, List<String> scriptDependencies, List<String> styleDependencies) { LegacyCommunicationManager manager = VaadinSession.getCurrent().getCommunicationManager(); for (Class<? extends ClientConnector> connector : newConnectorTypes) { WebJarResource webJarResource = connector.getAnnotation(WebJarResource.class); if (webJarResource == null) continue; for (String uri : webJarResource.value()) { uri = processResourceUri(uri); if (uri.endsWith(JAVASCRIPT_EXTENSION)) { scriptDependencies.add(manager.registerDependency(uri, connector)); } if (uri.endsWith(CSS_EXTENSION)) { styleDependencies.add(manager.registerDependency(uri, connector)); } } } }
@Override public Enum convertToModel(String value, Class<? extends Enum> targetType, Locale locale) throws ConversionException { if (value == null) { return null; } if (locale == null) { locale = VaadinSession.getCurrent().getLocale(); } if (isTrimming()) { value = StringUtils.trimToEmpty(value); } Object[] enumConstants = enumClass.getEnumConstants(); if (enumConstants != null) { for (Object enumValue : enumConstants) { if (Objects.equals(value, messages.getMessage((Enum) enumValue, locale))) { return (Enum) enumValue; } } } return null; }
@Override public String convertToPresentation(Enum value, Class<? extends String> targetType, Locale locale) throws ConversionException { if (getFormatter() != null) { return getFormatter().format(value); } if (value == null) { return null; } if (locale == null) { locale = VaadinSession.getCurrent().getLocale(); } return messages.getMessage(value, locale); }
@Override public Object convertToModel(String value, Class<?> targetType, Locale locale) throws ConversionException { try { if (locale == null) { locale = VaadinSession.getCurrent().getLocale(); } if (isTrimming()) { value = StringUtils.trimToEmpty(value); } if (locale != null) { return datatype.parse(value, locale); } return datatype.parse(value); } catch (ParseException e) { throw new ConversionException(e); } }
@Override public String convertToPresentation(Object value, Class<? extends String> targetType, Locale locale) throws ConversionException { if (getFormatter() != null) { return getFormatter().format(value); } if (locale == null) { locale = VaadinSession.getCurrent().getLocale(); } if (locale != null) { return datatype.format(value, locale); } return datatype.format(value); }
public void setLocale(Locale locale) { UserSession session = getConnection().getSession(); if (session != null) { session.setLocale(locale); } AppUI currentUi = AppUI.getCurrent(); // it can be null if we handle request in a custom RequestHandler if (currentUi != null) { currentUi.setLocale(locale); currentUi.updateClientSystemMessages(locale); } VaadinSession.getCurrent().setLocale(locale); for (AppUI ui : getAppUIs()) { if (ui != currentUi) { ui.accessSynchronously(() -> { ui.setLocale(locale); ui.updateClientSystemMessages(locale); }); } } }
@Override protected void initExpectations() { super.initExpectations(); new NonStrictExpectations() { { vaadinSession.getLocale(); result = Locale.ENGLISH; VaadinSession.getCurrent(); result = vaadinSession; globalConfig.getAvailableLocales(); result = ImmutableMap.of("en", Locale.ENGLISH); AppContext.getProperty("cuba.mainMessagePack"); result = "com.haulmont.cuba.web"; } }; factory = new WebComponentsFactory(); }
/** * initalize a unique RequestHandler */ private void initRequestHandler() { if (this.requestHandlerUri == null) { this.requestHandlerUri = UUID.randomUUID() .toString(); VaadinSession.getCurrent() .addRequestHandler(new RequestHandler() { @Override public boolean handleRequest(final VaadinSession session, final VaadinRequest request, final VaadinResponse response) throws IOException { if (String.format("/%s", Jcrop.this.requestHandlerUri) .equals(request.getPathInfo())) { Jcrop.this.resource.getStream() .writeResponse(request, response); return true; } else { return false; } } }); } }
@Override protected boolean isStaticResourceRequest(HttpServletRequest request) { // set user and trace ... boolean ret = super.isStaticResourceRequest(request); if (!ret) { try { VaadinServletRequest vs = createVaadinRequest(request); VaadinSession vaadinSession = getService().findVaadinSession(vs); request.setAttribute("__vs", vaadinSession); for (UI ui : vaadinSession.getUIs()) { if (ui instanceof ControlUi) ((ControlUi)ui).requestBegin(request); } } catch (Throwable t) { } } return ret; }
@Override public void onRequestEnd(VaadinRequest request, VaadinResponse response, VaadinSession session) { try { if (session != null) { SecurityContext securityContext = SecurityContextHolder.getContext(); logger.trace("Storing security context {} in VaadinSession {}", securityContext, session); session.lock(); try { session.setAttribute(SECURITY_CONTEXT_SESSION_ATTRIBUTE, securityContext); } finally { session.unlock(); } } else { logger.trace("No VaadinSession available for storing the security context"); } } finally { logger.trace("Clearing security context"); SecurityContextHolder.clearContext(); } }
/** * Setup UI. */ private void initComponents() { List<User> users = UserList.INSTANCE.getUsers(); userSwitchBox = new ComboBox(Messages.getString("UserSwitchPanel.boxCaption")); //$NON-NLS-1$ setUsers(users); User current = (User) VaadinSession.getCurrent().getAttribute(SessionStorageKey.USER.name()); userSwitchBox.setValue(current); userSwitchBox.setDescription( Messages.getString("UserSwitchPanel.boxDescription")); //$NON-NLS-1$ userSwitchBox.setNewItemsAllowed(false); userSwitchBox.setNullSelectionAllowed(false); addComponent(userSwitchBox); btReload = new Button(Messages.getString("UserSwitchPanel.reloadCaption")); //$NON-NLS-1$ btReload.setStyleName(BaseTheme.BUTTON_LINK); btReload.addStyleName("plain-link"); //$NON-NLS-1$ addComponent(btReload); }
/** * Load and display the current papers. */ private void initData() { postDownloadLabel.setVisible(false); paperTable.removeAllItems(); try { List<Paper> papers = PropertyKey.getPaperProviderInstance().getPapers( (User)VaadinSession.getCurrent().getAttribute(SessionStorageKey.USER.name())); for (Paper paper : papers) { paperTable.addItem(new Object[] {paper.getTitle()}, paper); } } catch (IOException e) { e.printStackTrace(); Notification.show( Messages.getString("PaperSelectionPanel.error1Title"), //$NON-NLS-1$ Messages.getString( "PaperSelectionPanel.conftoolerrormsg",//$NON-NLS-1$ e.getLocalizedMessage()), Type.ERROR_MESSAGE); } }
/** * @return the download stream of the {@link ZipResult}-data. */ private InputStream createResultStream() { try { ZipResult result = (ZipResult) VaadinSession.getCurrent().getAttribute( SessionStorageKey.ZIPRESULT.name()); logArea.setValue(""); confToolLabel.setVisible(true); // UI.getCurrent().push(); return new ByteArrayInputStream(result.toZipData()); } catch (IOException e) { e.printStackTrace(); Notification.show( Messages.getString("ConverterPanel.resultCreationErrorTitle"), //$NON-NLS-1$ Messages.getString("ConverterPanel.resultCreationErrorMsg"), //$NON-NLS-1$ Type.ERROR_MESSAGE); return null; } }
/** * Authentication via ConfTool. * * @param username * @param pass */ protected void authenticate(String username, char[] pass) { UserProvider userProvider = PropertyKey.getUserProviderInstance(); try { User user = userProvider.authenticate(username, pass); user = userProvider.getDetailedUser(user); VaadinSession.getCurrent().setAttribute( SessionStorageKey.USER.name(), user); UI.getCurrent().setContent(new LoginResultPanel()); } catch (IOException e) { e.printStackTrace(); UI.getCurrent().setContent(new LoginResultPanel(e.getLocalizedMessage())); } catch (UserProvider.AuthenticationException a) { a.printStackTrace(); UI.getCurrent().setContent(new LoginResultPanel(a.getLocalizedMessage())); } }
/** * Adds a default transaction listener. */ @Override public void init() { final LegacyApplication app = this; VaadinSession.getCurrent().setErrorHandler(new ErrorHandler() { private static final long serialVersionUID = 1L; @Override public void error(ErrorEvent event) { Utils.terminalError(event, app); } }); if(!Db.isInitialized()) { logger.warn("No TransactionListener added: Database is not initialized. You can initialize a database configuring a new 'DefaultTransactionListener' in your web.xml and adding a 'configuration.properties' file to your classpath."); } VaadinSession.getCurrent().setAttribute("application", this); }
public MainScreen() { Label loginLabel = new Label("Welcome " + VaadinSession.getCurrent().getAttribute(String.class)); HorizontalLayout menuBar = new HorizontalLayout(loginLabel); MessageTable table = new MessageTable(); TextArea messageArea = new TextArea(); messageArea.setWidth(100, PERCENTAGE); Button sendButton = new Button("Send"); sendButton.addClickListener(new SendMessageClickListener(table, messageArea)); HorizontalLayout lowerBar = new HorizontalLayout(messageArea, sendButton); lowerBar.setWidth(100, PERCENTAGE); lowerBar.setSpacing(true); VerticalLayout mainLayout = new VerticalLayout(menuBar, table, lowerBar); mainLayout.setSpacing(true); mainLayout.setMargin(true); mainLayout.setSizeFull(); setCompositionRoot(mainLayout); }
@Override public void attach(Component component, HasComponents parent, UI ui, VaadinSession session) { if (component instanceof SlideContainer) { viewportEventManager.setEnabled(true); messageEventManager.setEnabled(true); fireEvent(new ViewportEvent.Init(container)); if (ui instanceof HypothesisUI) { this.ui = (HypothesisUI) ui; addWindows(ui); addTimers(this.ui); addKeyActions(ui); BroadcastService.register(this); } fireEvent(new ViewportEvent.Show(component)); } }
@Override public void detach(Component component, HasComponents parent, UI ui, VaadinSession session) { this.ui = null; viewportEventManager.setEnabled(false); messageEventManager.setEnabled(false); BroadcastService.unregister(this); if (ui instanceof HypothesisUI) { HypothesisUI hui = (HypothesisUI) ui; hui.removeAllTimers(); removeKeyActions(); removeWindows(); } }
/** * All hibernate operations take place within a session. The session for the * current thread is provided here. */ public static Session getSession() throws NullPointerException { SessionMap sessions = VaadinSession.getCurrent().getAttribute(SessionMap.class); if (null == sessions) { sessions = new SessionMap(); VaadinSession.getCurrent().setAttribute(SessionMap.class, sessions); } String threadGroup = Thread.currentThread().getThreadGroup().getName(); Session session = sessions.get(threadGroup); if (null == session) { session = sessionFactory.openSession(); sessions.put(threadGroup, session); } return session; }
@Test public void testOnSessionInit() throws Exception { SessionInitEvent event = createMock(SessionInitEvent.class); // expect adding ui provider VaadinSession sessionMock = createMock(VaadinSession.class); expect(event.getSession()).andReturn(sessionMock); sessionMock.addUIProvider(uiProviderMock); replayAll(); try { listener.sessionInit(event); } finally { verifyAll(); } }
/** * {@inheritDoc} */ public String getConversationId() { Integer uiId = null; UI ui = UI.getCurrent(); if (ui == null) { UIid id = CurrentInstance.get(UIid.class); if (id != null) { uiId = id.getUiId(); } } else if (ui != null) { if (!sessions.containsKey(ui)) { ui.addDetachListener(this); sessions.put(ui, VaadinSession.getCurrent().getSession().getId()); } uiId = ui.getUIId(); } return uiId != null ? getConversationId(uiId) : null; }