/** * 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("serial") @Override protected VaadinServletRequest buildVaadinRequest(String location) { return new SpringVaadinServletRequest(request, (VaadinServletService) vaadinSession.getService(), false) { /* * (non-Javadoc) * @see javax.servlet.ServletRequestWrapper#getParameter(java.lang.String) */ @Override public String getParameter(String name) { if ("v-loc".equals(name)) { return location; } return super.getParameter(name); } }; }
/** * Build VaadinServletRequest using a location * @param location Page location * @return VaadinServletRequest */ @SuppressWarnings("serial") protected VaadinServletRequest buildVaadinRequest(final String location) { return new VaadinServletRequest(buildHttpServletRequest(), (VaadinServletService) vaadinSession.getService()) { /* * (non-Javadoc) * @see javax.servlet.ServletRequestWrapper#getParameter(java.lang.String) */ @Override public String getParameter(String name) { if ("v-loc".equals(name)) { return location; } return super.getParameter(name); } }; }
@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()); }
@Override public String getStaticFileLocation(VaadinRequest request) { String staticFileLocation; // if property is defined in configurations, use that staticFileLocation = getDeploymentConfiguration().getResourcesPath(); if (staticFileLocation != null) { return staticFileLocation; } VertxVaadinRequest vertxRequest = (VertxVaadinRequest) request; String requestedPath = vertxRequest.getRequest().path() .substring( Optional.ofNullable(vertxRequest.getRoutingContext().mountPoint()) .map(String::length).orElse(0) ); return VaadinServletService.getCancelingRelativePath(requestedPath); }
@Override public boolean validate(String username, String password) { UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password); try { Authentication auth = this.authenticationManager.authenticate(token); if (auth.isAuthenticated()) { // execute session authentication strategy if (this.sessionStrategy != null) this.sessionStrategy.onAuthentication(auth, VaadinServletService.getCurrentServletRequest(), VaadinServletService.getCurrentResponse()); SecurityContextHolder.getContext().setAuthentication(auth); // save request in context session VaadinSession.getCurrent().getSession().setAttribute( HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, SecurityContextHolder.getContext()); return true; } SecurityContextHolder.clearContext(); return false; } catch(AuthenticationException ae) { SecurityContextHolder.clearContext(); return false; } }
@Override protected VaadinServletService createServletService(DeploymentConfiguration deploymentConfiguration) throws ServiceException { JMeterService service = new JMeterService(this, deploymentConfiguration); service.init(); return service; }
private String getLogoutUrl() { if (VaadinServletService.getCurrentRequest() != null) { return VaadinServletService.getCurrentRequest().getContextPath(); } else { return "https://" + this.server.getServerIpAddress() + "/"; } }
private static String getCurrentPageUrl(ServerApi server) { String url; if (Page.getCurrent() != null && Page.getCurrent().getLocation() != null) { url = Page.getCurrent().getLocation().toString(); } else if (VaadinServletService.getCurrentRequest() != null) { url = VaadinServletService.getCurrentRequest().getContextPath(); } else { url = "https://" + server.getServerIpAddress() + "/"; } // Workaround bug in URL generation url = url.replace("#!", "/#!"); url = url.replace("//#!", "/#!"); return url; }
@Override protected VaadinServletService createServletService(DeploymentConfiguration deploymentConfiguration) throws ServiceException { VaadinServletService servletService = super.createServletService(deploymentConfiguration); servletService.addSessionInitListener(e -> e.getSession().addUIProvider(this.uiProvider)); servletService.addSessionInitListener(e -> sessions.add(e.getSession())); servletService.addSessionDestroyListener(e -> sessions.remove(e.getSession())); return servletService; }
@Override protected void servletInitialized() throws ServletException { super.servletInitialized(); // register session init/destroy listeners final VaadinServletService service = getService(); sessionInitListeners.forEach(listener -> service.addSessionInitListener(listener)); sessionDestroyListeners.forEach(listener -> service.addSessionDestroyListener(listener)); }
public void listen(@Observes AnswerSavedEvent event) { RespondentAccount respondent = (RespondentAccount) VaadinServletService.getCurrentServletRequest() .getUserPrincipal(); Integer questionnaireId = respondent.getGrantedquestionnaireIds().iterator().next(); Answer answer = event.getAnswer(); String questionCode = event.getQuestionCode(); logger.debug("Trying to save answer: {} for questionnair identified with id = {} and questionCode = {}", answer, questionnaireId, questionCode); questionnaireResource.saveAnswer(answer, questionnaireId, questionCode); }
@Test public void testServletInitializedMethod() throws Exception { // expect adding session init listener VaadinServletService servletService = createMock(VaadinServletService.class); Whitebox.setInternalState(servlet, "servletService", servletService); servletService.addSessionInitListener(sessionInitListenerMock); replayAll(); try { servlet.servletInitialized(); } finally { verifyAll(); } }
@Override protected VaadinServletService createServletService(DeploymentConfiguration deploymentConfiguration) throws ServiceException { VaadinServletService servletService = super.createServletService(deploymentConfiguration); servletService.addSessionInitListener(new SessionInitListener() { @Override public void sessionInit(SessionInitEvent sessionInitEvent) throws ServiceException { sessionInitEvent.getSession().addUIProvider(provider); } }); return servletService; }
@Override public void modifyBootstrapPage(BootstrapPageResponse response) { ViewPortSettings viewPortSettings2 = selectViewPortSettings(response); if (viewPortSettings2 != null) { viewPortSettings2.modifyBootstrapPage(response); } if (getWebAppSettings() != null) { getWebAppSettings().modifyBootstrapPage(response); } if (getApplicationIcons() != null) { getApplicationIcons().modifyBootstrapPage(response); } if (getApplicationCacheSettings() != null) { OfflineModeEnabled offline = null; CacheManifestEnabled manifest = null; Class<?> clazz = response.getUiClass(); if (clazz != null) { offline = clazz.getAnnotation(OfflineModeEnabled.class); manifest = clazz.getAnnotation(CacheManifestEnabled.class); } if (response.getSession().getService() instanceof VaadinServletService) { clazz = ((VaadinServletService) response.getSession() .getService()).getServlet().getClass(); if (offline == null) { offline = clazz.getAnnotation(OfflineModeEnabled.class); } if (manifest == null) { manifest = clazz.getAnnotation(CacheManifestEnabled.class); } } getApplicationCacheSettings().setCacheManifestEnabled( manifest == null || manifest.value()); getApplicationCacheSettings().setOfflineModeEnabled( offline == null || offline.value()); getApplicationCacheSettings().modifyBootstrapPage(response); } }
@Override protected VaadinServletRequest buildVaadinRequest() { return new SpringVaadinServletRequest(request, (VaadinServletService) vaadinSession.getService(), false); }
@Override public void serviceInit(ServiceInitEvent event) { ValoDependencyFilter dependencyFilter = new ValoDependencyFilter(); if (dependencyFilter.hasValoWebJar()) { event.addDependencyFilter(dependencyFilter); } VaadinServletService service = (VaadinServletService) event.getSource(); WebApplicationContext applicationContext = WebApplicationContextUtils .findWebApplicationContext( service.getServlet().getServletContext()); String apiKey = applicationContext.getEnvironment() .getProperty("map.apikey"); if (apiKey == null) { throw new RuntimeException( "Configure a map.apikey in your application.properties"); } event.addBootstrapListener(new BootstrapListener() { @Override public void modifyBootstrapPage(BootstrapPageResponse response) { Element head = response.getDocument().head(); head.appendElement("meta").attr("name", "viewport") .attr("content", "width=device-width, initial-scale=1"); // Flow sets element properties too late for google-map to get // the right API key. As a temporary workaround, we put our key // in the map's prototype instead. head.appendElement("script").html("window.mapApiKey = '" + apiKey + "';\n" + "customElements.whenDefined('google-map').then(function() {customElements.get('google-map').prototype.apiKey = window.mapApiKey})"); head.appendElement("link").attr("rel", "import").attr("href", response.getUriResolver().resolveVaadinUri( "frontend://bower_components/vaadin-valo-theme/typography.html")); head.appendElement("link").attr("rel", "import").attr("href", response.getUriResolver().resolveVaadinUri( "frontend://bower_components/vaadin-valo-theme/color.html")); head.appendElement("custom-style").appendElement("style") .attr("include", "valo-typography valo-colors"); } }); }
@Override protected void configureVaadinService(VaadinServletService service) { service.addSessionInitListener(new MySessionListener.MapSessionInitListener()); super.configureVaadinService(service); }
@Nullable @Override public DeviceInfo getDeviceInfo() { // per request cache HttpServletRequest currentServletRequest = VaadinServletService.getCurrentServletRequest(); if (currentServletRequest == null) { return null; } DeviceInfo deviceInfo = (DeviceInfo) currentServletRequest.getAttribute(DeviceInfoProvider.NAME); if (deviceInfo != null) { return deviceInfo; } Page page = Page.getCurrent(); if (page == null) { return null; } WebBrowser webBrowser = page.getWebBrowser(); DeviceInfo di = new DeviceInfo(); di.setAddress(webBrowser.getAddress()); di.setBrowserApplication(webBrowser.getBrowserApplication()); di.setBrowserMajorVersion(webBrowser.getBrowserMajorVersion()); di.setBrowserMinorVersion(webBrowser.getBrowserMinorVersion()); di.setChrome(webBrowser.isChrome()); di.setChromeFrame(webBrowser.isChromeFrame()); di.setChromeFrameCapable(webBrowser.isChromeFrameCapable()); di.setEdge(webBrowser.isEdge()); di.setFirefox(webBrowser.isFirefox()); di.setOpera(webBrowser.isOpera()); di.setIE(webBrowser.isIE()); if (webBrowser.isWindows()) { di.setOperatingSystem(OperatingSystem.WINDOWS); } else if (webBrowser.isAndroid()) { di.setOperatingSystem(OperatingSystem.ANDROID); } else if (webBrowser.isIOS()) { di.setOperatingSystem(OperatingSystem.IOS); } else if (webBrowser.isMacOSX()) { di.setOperatingSystem(OperatingSystem.MACOSX); } else if (webBrowser.isLinux()) { di.setOperatingSystem(OperatingSystem.LINUX); } di.setIPad(webBrowser.isIPad()); di.setIPhone(webBrowser.isIPhone()); di.setWindowsPhone(webBrowser.isWindowsPhone()); di.setSecureConnection(webBrowser.isSecureConnection()); di.setLocale(webBrowser.getLocale()); di.setScreenHeight(webBrowser.getScreenHeight()); di.setScreenWidth(webBrowser.getScreenWidth()); currentServletRequest.setAttribute(DeviceInfoProvider.NAME, di); return di; }
/** * * @deprecated use VaadinServletService.getCurrentServletRequest() */ @Deprecated public HttpServletRequest getHttpServletRequest() { return VaadinServletService.getCurrentServletRequest(); }
/** * * @deprecated use VaadinServletService.getCurrentResponse() */ @Deprecated public HttpServletResponse getHttpServletResponse() { return VaadinServletService.getCurrentResponse(); }
@Override public void enter(ViewChangeEvent event) { logger.debug("Entering {} view ", QuestionnaireView.NAME); addStyleName(Reindeer.LAYOUT_BLUE); addStyleName("questionnaires"); WebBrowser webBrowser = Page.getCurrent().getWebBrowser(); Integer screenWidth = webBrowser.getScreenWidth(); Integer heightWidth = webBrowser.getScreenHeight(); logger.debug("Browser screen settings {} x {}", screenWidth, heightWidth); if (heightWidth <= 480) { renderingMode = RenderingMode.QUESTION_BY_QUESTION; } // centralLayout.addStyleName("questionnaires"); // new Responsive(centralLayout); RespondentAccount respondent = (RespondentAccount) VaadinServletService.getCurrentServletRequest() .getUserPrincipal(); if (respondent.hasPreferredLanguage()) { preferredLanguage = Language.fromString(respondent.getPreferredLanguage()); } else { preferredLanguage = Language.fromLocale(webBrowser.getLocale()); } questionnaireId = respondent.getGrantedquestionnaireIds().iterator().next(); logger.debug("Trying to fetch questionnair identified with id = {} ", questionnaireId); QuestionnaireDefinitionDTO definition = questionnaireResource.getDefinition(questionnaireId); sectionInfoVisible = definition.isSectionInfoVisible(); QuestionnairePageDTO page = questionnaireResource.getPage(questionnaireId, renderingMode, preferredLanguage, NavigationAction.ENTERING); logger.debug("Displaying page {}/{} with {} questions", page.getMetadata().getNumber(), page.getMetadata() .getCount(), page.getQuestions().size()); questionsLayout = new VerticalLayout(); update(page); Label questionnaireTitle = new Label(definition.getLanguageSettings().getTitle()); questionnaireTitle.addStyleName(Reindeer.LABEL_H1); VerticalLayout mainLayout = new VerticalLayout(); mainLayout.setSizeFull(); mainLayout.setMargin(true); mainLayout.addComponent(questionnaireTitle); mainLayout.addComponent(questionsLayout); // Add the responsive capabilities to the components Panel centralLayout = new Panel(); centralLayout.setContent(mainLayout); centralLayout.setSizeFull(); centralLayout.getContent().setSizeUndefined(); Responsive.makeResponsive(questionnaireTitle); setCompositionRoot(centralLayout); setSizeFull(); }
@Override public void buttonClick(final ClickEvent event) { // just in case the user goes around a second time. this.sentLabel.setVisible(false); final String emailAddressValue = this.emailAddress.getValue(); final UserDao userDao = new DaoFactory().getUserDao(); final User user = userDao.findByEmail(emailAddressValue); if (user == null) { SMNotification.show("The entered email address does not exist.", Type.WARNING_MESSAGE); } else { final SendEmailWorkingDialog dialog = new SendEmailWorkingDialog("Sending", "Sending a reset link to you via email.<br> It should arrive in a few moments."); final SMTPSettingsDao settingsDao = new DaoFactory().getSMTPSettingsDao(); final SMTPServerSetting settings = settingsDao.findSettings(); dialog.setFrom(settings.getFromEmailAddress()); dialog.setSubject("[Scoutmaster] Password reset request"); final ForgottenPasswordResetDao forgottenPasswordResetDao = new DaoFactory().getForgottenPasswordResetDao(); final ForgottenPasswordReset reset = forgottenPasswordResetDao.createReset(emailAddressValue); forgottenPasswordResetDao.persist(reset); String url = VaadinServletService.getCurrentServletRequest().getRequestURL().toString(); // The click event seems to come from a vaading PUSH service so we // need to remove the /PUSH/ from the path. if (url.contains("/PUSH")) { final int pushStartIndex = url.indexOf("/PUSH/"); final int pushEndIndex = pushStartIndex + 6; url = url.substring(0, pushStartIndex) + url.substring(pushEndIndex); } final StringBuilder sb = new StringBuilder(); sb.append("So you forgot your password, surely not :))\n\n"); sb.append("Use the following link within the next 24 hours to reset your password:\n"); sb.append(url + "/?resetid=" + reset.getResetid() + "#!" + ResetPasswordView.NAME); dialog.setMessage(sb.toString()); dialog.addTo(emailAddressValue); dialog.setCompleteListener(this); dialog.send(); } }
private static String getServer() { HttpServletRequest request = VaadinServletService.getCurrentServletRequest(); return (request.isSecure() ? "https://" : "http://") + request.getServerName(); }
/** * Build VaadinServletRequest * @return VaadinServletRequest */ protected VaadinServletRequest buildVaadinRequest() { return new VaadinServletRequest(buildHttpServletRequest(), (VaadinServletService) vaadinSession.getService()); }