/** * 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; }
@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()); }
public void processExternalLink(VaadinRequest request) { WrappedSession wrappedSession = request.getWrappedSession(); String action = (String) wrappedSession.getAttribute(LAST_REQUEST_ACTION_ATTR); if (webConfig.getLinkHandlerActions().contains(action)) { //noinspection unchecked Map<String, String> params = (Map<String, String>) wrappedSession.getAttribute(LAST_REQUEST_PARAMS_ATTR); params = params != null ? params : Collections.emptyMap(); try { LinkHandler linkHandler = AppBeans.getPrototype(LinkHandler.NAME, app, action, params); if (app.connection.isConnected() && linkHandler.canHandleLink()) { linkHandler.handle(); } else { app.linkHandler = linkHandler; } } catch (Exception e) { error(new com.vaadin.server.ErrorEvent(e)); } } }
@Override public void init(VaadinRequest request) { final WrappedSession session = request.getWrappedSession(); final VerticalLayout layout = new VerticalLayout(); layout.setMargin(true); parent.setContent(layout); Button button = new Button("Click Me"); button.addClickListener(new Button.ClickListener() { public void buttonClick(ClickEvent event) { Integer counter = (Integer)session.getAttribute("counter"); if (counter == null) { counter = 0; } counter++; session.setAttribute("counter", counter); layout.addComponent(new Label("Thank you for clicking, counter:" + counter)); } }); layout.addComponent(button); }
private void doDispatch(final List<TenantAwareEvent> events, final WrappedSession wrappedSession) { final SecurityContext userContext = (SecurityContext) wrappedSession .getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY); final SecurityContext oldContext = SecurityContextHolder.getContext(); try { SecurityContextHolder.setContext(userContext); final List<EventContainer<TenantAwareEvent>> groupedEvents = groupEvents(events, userContext, eventProvider); vaadinUI.access(() -> { if (vaadinSession.getState() != State.OPEN) { return; } LOG.debug("UI EventBus aggregator of UI {} got lock on session.", vaadinUI.getUIId()); groupedEvents.forEach(holder -> eventBus.publish(vaadinUI, holder)); LOG.debug("UI EventBus aggregator of UI {} left lock on session.", vaadinUI.getUIId()); }).get(); } catch (InterruptedException | ExecutionException e) { LOG.warn("Wait for Vaadin session for UI {} interrupted!", vaadinUI.getUIId(), e); } finally { SecurityContextHolder.setContext(oldContext); } }
@Override public Authentication getAuthentication() { final SecurityContext securityContext = SecurityContextHolder.getContext(); Authentication authentication = securityContext.getAuthentication(); if (authentication == null) { // The SecurityContextHolder only holds the Authentication when it is // processing the securityFilterChain. After it completes the chain // it clears the context holder. // Therefore, the Authentication object can be retrieved from the // location where the securityFilterChain or VaadinSecurity has left it, // within the HttpSession. LOGGER.debug("No authentication object bound to thread, trying to access the session directly"); WrappedSession session = getSession(); if (session != null) { SecurityContext context = (SecurityContext) session.getAttribute(springSecurityContextKey); authentication = context.getAuthentication(); } else { LOGGER.debug("No session bound to current thread, cannot retrieve the authentication object"); } } return authentication; }
public static void initializeLocale(VaadinRequest request) { WrappedSession session = request.getWrappedSession(); HttpSession httpSession = ((WrappedHttpSession) session).getHttpSession(); ServletContext servletContext = httpSession.getServletContext(); String defaultLanguage = servletContext.getInitParameter(LOCALE_CONFIG_DEFAULT_LANGUAGE); defaultLocale = new Locale(defaultLanguage); String language = request.getParameter(LOCALE_PARAM_LANGUAGE); if (null == language) { currentLocale = defaultLocale; } else { currentLocale = new Locale(language); } Messages.initMessageSource(currentLocale); }
@Override public void processExternalLink(VaadinRequest request) { WrappedSession wrappedSession = request.getWrappedSession(); String action = (String) wrappedSession.getAttribute(LAST_REQUEST_ACTION_ATTR); if (NexbitLinkHandler.RESET_ACTION.equals(action)) { //noinspection unchecked Map<String, String> params = (Map<String, String>) wrappedSession.getAttribute(LAST_REQUEST_PARAMS_ATTR); if (params == null) { log.warn("Unable to process the external link: lastRequestParams not found in session"); return; } try { LinkHandler linkHandler = AppBeans.getPrototype(LinkHandler.NAME, app, action, params); if (((NexbitLinkHandler)linkHandler).canHandleLink(action, params)) { linkHandler.handle(); wrappedSession.setAttribute(LAST_REQUEST_ACTION_ATTR, null); return; } } catch (Exception e) { error(new com.vaadin.server.ErrorEvent(e)); } } super.processExternalLink(request); }
@Override public void run() { LOG.debug("UI EventBus aggregator started for UI {}", vaadinUI.getUIId()); final long timestamp = System.currentTimeMillis(); final int size = queue.size(); if (size <= 0) { LOG.debug("UI EventBus aggregator for UI {} has nothing to do.", vaadinUI.getUIId()); return; } final WrappedSession wrappedSession = vaadinSession.getSession(); if (wrappedSession == null) { return; } final List<TenantAwareEvent> events = new ArrayList<>(size); final int eventsSize = queue.drainTo(events); if (events.isEmpty()) { LOG.debug("UI EventBus aggregator for UI {} has nothing to do.", vaadinUI.getUIId()); return; } LOG.debug("UI EventBus aggregator dispatches {} events for session {} for UI {}", eventsSize, vaadinSession, vaadinUI.getUIId()); doDispatch(events, wrappedSession); LOG.debug("UI EventBus aggregator done with sending {} events in {} ms for UI {}", eventsSize, System.currentTimeMillis() - timestamp, vaadinUI.getUIId()); }
private static WrappedSession getCurrentHttpSession() { VaadinSession s = VaadinSession.getCurrent(); if (s == null) { throw new IllegalStateException( "No session found for current thread"); } return s.getSession(); }
@Override public Authentication login(Authentication authentication, boolean rememberMe) throws Exception { final HttpServletRequest request = new RememberMeRequestWrapper(getCurrentRequest(), rememberMe, getRememberMeParameter()); final HttpServletResponse response = getCurrentResponse(); try { LOGGER.debug("Attempting authentication of {}, rememberMe = {}", authentication, rememberMe); final Authentication fullyAuthenticated = getAuthenticationManager().authenticate(authentication); LOGGER.debug("Invoking session authentication strategy"); sessionAuthenticationStrategy.onAuthentication(fullyAuthenticated, request, response); successfulAuthentication(fullyAuthenticated, request, response); return fullyAuthenticated; } catch (Exception e) { unsuccessfulAuthentication(request, response); throw e; } finally { if (saveContextInSessionAfterLogin) { LOGGER.debug("Saving security context in the session"); WrappedSession session = getSession(); if (session != null) { session.setAttribute(springSecurityContextKey, SecurityContextHolder.getContext()); } else { LOGGER.warn( "Tried to save security context in the session, but no session was bound to the current thread"); } } } }
private static WrappedSession getSession() { VaadinSession vaadinSession = VaadinSession.getCurrent(); if (vaadinSession != null) { return vaadinSession.getSession(); } else { return null; } }
@Override public void onRequestStart(VaadinRequest request, VaadinResponse response) { final WrappedSession wrappedSession = request.getWrappedSession(false); VaadinSession session = null; if (wrappedSession != null) { session = VaadinSession.getForSession(request.getService(), wrappedSession); } SecurityContextHolder.clearContext(); if (session != null) { logger.trace("Loading security context from VaadinSession {}", session); SecurityContext securityContext; session.lock(); try { securityContext = (SecurityContext) session.getAttribute(SECURITY_CONTEXT_SESSION_ATTRIBUTE); } finally { session.unlock(); } if (securityContext == null) { logger.trace("No security context found in VaadinSession {}", session); } else { logger.trace("Setting security context to {}", securityContext); SecurityContextHolder.setContext(securityContext); } } else { logger.trace("No VaadinSession available for retrieving the security context"); } }
private void initializePlugins(VaadinRequest request) { WrappedSession session = request.getWrappedSession(); HttpSession httpSession = ((WrappedHttpSession) session).getHttpSession(); ServletContext servletContext = httpSession.getServletContext(); String configFileName = servletContext.getInitParameter(PluginManager.PLUGIN_CONFIG_LOCATION); if (configFileName != null && configFileName.length() > 0) { configFileName = servletContext.getRealPath(configFileName); File configFile = new File(configFileName); PluginManager.get().initializeFromFile(configFile); } }
@Override public WrappedSession getWrappedSession() { return getWrappedSession(true); }
@Override public WrappedSession getWrappedSession(boolean allowSessionCreation) { return Optional.ofNullable(routingContext.session()) .map(ExtendedSession::adapt) .map(VertxWrappedSession::new).orElse(null); }
private void onSessionExpired(Message<String> message) { Optional.ofNullable(this.getSession()) .filter(ws -> ws.getId().equals(message.body())) .ifPresent(WrappedSession::invalidate); }
@Override public void refreshTransients(WrappedSession wrappedSession, VaadinService vaadinService) { super.refreshTransients(wrappedSession, vaadinService); createSessionExpireConsumer((VertxVaadinService) vaadinService); }
public WrappedSession getMySession() { return session; }
public void exportAsync(OutputFormat exportMethod, Collection<ReportParameter<?>> params, JasperProgressListener progressListener) { if (params == null) { params = new LinkedList<>(); } this.params = params; images = new ConcurrentHashMap<>(); if (UI.getCurrent() != null) { WrappedSession session = UI.getCurrent().getSession().getSession(); session.setAttribute(VaadinJasperPrintServlet.IMAGES_MAP, images); } else { logger.warn("No vaadin UI present"); } stop = false; writerReady = new CountDownLatch(1); completeBarrier = new CountDownLatch(1); readerReady = new CountDownLatch(1); this.progressListener = progressListener; if (progressListener == null) { this.progressListener = new JasperProgressListener() { @Override public void failed(String string) { // noop } @Override public void completed() { // noop } @Override public void outputStreamReady() { // noop } }; } inputStream = null; outputStream = null; queueEntry = new QueueEntry(reportProperties.getReportTitle(), reportProperties.getUsername()); inQueue = true; jobQueue.add(queueEntry); this.exportMethod = exportMethod; thread = new Thread(this, "JasperManager"); thread.start(); }
public WrappedSession getHTTPSession() { return this.httpSession; }