@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 protected void init(VaadinRequest request) { VertxVaadinRequest req = (VertxVaadinRequest) request; Cookie cookie = new Cookie("myCookie", "myValue"); cookie.setMaxAge(120); cookie.setPath(req.getContextPath()); VaadinService.getCurrentResponse().addCookie(cookie); Label sessionAttributeLabel = new MLabel().withCaption("Session listener"); String deploymentId = req.getService().getVertx().getOrCreateContext().deploymentID(); setContent(new MVerticalLayout( new Header("Vert.x Vaadin Sample").setHeaderLevel(1), new Label(String.format("Verticle %s deployed on Vert.x", deploymentId)), new Label("Session created at " + Instant.ofEpochMilli(req.getWrappedSession().getCreationTime())), sessionAttributeLabel ).withFullWidth()); }
public SpellChoiceForm(Character character, DSClass dsClass) { super(CharacterClass.class); this.character = character; this.chosenClass = dsClass; String basepath = VaadinService.getCurrent().getBaseDirectory().getAbsolutePath(); FileResource resource = new FileResource(new File(basepath + "/WEB-INF/sound/selectSpell.mp3")); spellSound = new Audio(); spellSound.setSource(resource); spellSound.setShowControls(false); spellSound.setAutoplay(false); setSavedHandler(this); }
private void createRememberMeCookie(final User user) { try { final String rememberMeToken = createRememberMeToken(user); final Cookie rememberMeCookie = new Cookie(COOKIENAME_RememberMe, rememberMeToken); final int maxAge = (int)TimeUnit.SECONDS.convert(cookieMaxAgeDays, TimeUnit.DAYS); rememberMeCookie.setMaxAge(maxAge); final String path = "/"; // (VaadinService.getCurrentRequest().getContextPath()); rememberMeCookie.setPath(path); VaadinService.getCurrentResponse().addCookie(rememberMeCookie); logger.debug("Cookie added for {}: {} (maxAge={}, path={})", user, rememberMeToken, maxAge, path); } catch (final Exception e) { logger.warn("Failed creating cookie for user: {}. Skipped.", user, e); } }
private void removeRememberMeCookie() { try { Cookie cookie = getRememberMeCookie(); if (cookie == null) { return; } cookie = new Cookie(COOKIENAME_RememberMe, null); cookie.setValue(null); cookie.setMaxAge(0); // by setting the cookie maxAge to 0 it will deleted immediately cookie.setPath("/"); VaadinService.getCurrentResponse().addCookie(cookie); logger.debug("Cookie removed"); } catch (final Exception e) { logger.warn("Failed removing the cookie", e); } }
@Nullable protected String getUserRemoteAddress() { VaadinRequest currentRequest = VaadinService.getCurrentRequest(); String userRemoteAddress = null; if (currentRequest != null) { String xForwardedFor = currentRequest.getHeader("X_FORWARDED_FOR"); if (StringUtils.isNotBlank(xForwardedFor)) { String[] strings = xForwardedFor.split(","); String userAddressFromHeader = StringUtils.trimToEmpty(strings[strings.length - 1]); if (StringUtils.isNotEmpty(userAddressFromHeader)) { userRemoteAddress = userAddressFromHeader; } else { userRemoteAddress = currentRequest.getRemoteAddr(); } } else { userRemoteAddress = currentRequest.getRemoteAddr(); } } return userRemoteAddress; }
private void setCookies() { if (multiTenancyIndicator.isMultiTenancySupported()) { final Cookie tenantCookie = new Cookie(SP_LOGIN_TENANT, tenant.getValue().toUpperCase()); tenantCookie.setPath("/"); // 100 days tenantCookie.setMaxAge(HUNDRED_DAYS_IN_SECONDS); tenantCookie.setHttpOnly(true); tenantCookie.setSecure(uiProperties.getLogin().getCookie().isSecure()); VaadinService.getCurrentResponse().addCookie(tenantCookie); } final Cookie usernameCookie = new Cookie(SP_LOGIN_USER, username.getValue()); usernameCookie.setPath("/"); // 100 days usernameCookie.setMaxAge(HUNDRED_DAYS_IN_SECONDS); usernameCookie.setHttpOnly(true); usernameCookie.setSecure(uiProperties.getLogin().getCookie().isSecure()); VaadinService.getCurrentResponse().addCookie(usernameCookie); }
/** * Get Locale for i18n. * * @return String as locales */ private static String[] getLocaleChain() { String[] localeChain = null; // Fetch all cookies from the request final Cookie[] cookies = VaadinService.getCurrentRequest().getCookies(); if (cookies == null) { return localeChain; } for (final Cookie c : cookies) { if (c.getName().equals(SPUIDefinitions.COOKIE_NAME) && !c.getValue().isEmpty()) { localeChain = c.getValue().split("#"); break; } } return localeChain; }
@Override public void buttonClick(final ClickEvent event) { final ServiceResponse response = ApplicationMangerAccess.getApplicationManager().service(logoutRequest); if (ServiceResult.SUCCESS == response.getResult()) { UI.getCurrent().getNavigator().navigateTo(CommonsViews.MAIN_VIEW_NAME); UI.getCurrent().getSession().close(); VaadinService.getCurrentRequest().getWrappedSession().invalidate(); } else { Notification.show(LOGOUT_FAILED, ERROR_MESSAGE, Notification.Type.WARNING_MESSAGE); LOGGER.info(LOG_MSG_LOGOUT_FAILURE,logoutRequest.getSessionId()); } }
private String constructStartUrl(String uid, boolean returnBack) { StringBuilder builder = new StringBuilder(); String contextUrl = ServletUtil.getContextURL((VaadinServletRequest) VaadinService.getCurrentRequest()); builder.append(contextUrl); builder.append("/process/?"); // client debug // builder.append("gwt.codesvr=127.0.0.1:9997&"); builder.append("token="); builder.append(uid); builder.append("&fs"); if (returnBack) { builder.append("&bk=true"); } String lang = ControlledUI.getCurrentLanguage(); if (lang != null) { builder.append("&lang="); builder.append(lang); } return builder.toString(); }
private Image createEmailIcon(EmailContact emailContact) { final String basepath = VaadinService.getCurrent().getBaseDirectory().getAbsolutePath(); final FileResource resource = new FileResource(new File(basepath + "/images/email.png")); Image image = new Image(null, resource); image.setDescription("Click to send an email"); image.setVisible(false); image.addClickListener(new MouseEventLogged.ClickListener() { private static final long serialVersionUID = 1L; @Override public void clicked(final com.vaadin.event.MouseEvents.ClickEvent event) { showMailForm(emailContact); } }); return image; }
/** * Test if current request is an UIDL request * @return true if in UIDL request, false otherwise */ private boolean isUidlRequest() { VaadinRequest request = VaadinService.getCurrentRequest(); if (request == null) return false; String pathInfo = request.getPathInfo(); if (pathInfo == null) { return false; } if (pathInfo.startsWith("/" + ApplicationConstants.UIDL_PATH)) { return true; } return false; }
/** * Check authentication using {@link Authenticate} annotation on given view class or the {@link UI} class to which * navigator is bound. * @param navigationState Navigation state * @param viewConfiguration View configuration * @return <code>true</code> if authentication is not required or if it is required and the current * {@link AuthContext} is authenticated, <code>false</code> otherwise * @throws ViewNavigationException Missing {@link AuthContext} from context or other unexpected error */ protected boolean checkAuthentication(final String navigationState, final ViewConfiguration viewConfiguration) throws ViewNavigationException { if (!suspendAuthenticationCheck) { Authenticate authc = (viewConfiguration != null) ? viewConfiguration.getAuthentication().orElse(uiAuthenticate) : uiAuthenticate; if (authc != null) { // check auth context final AuthContext authContext = AuthContext.getCurrent().orElseThrow(() -> new ViewNavigationException( navigationState, "No AuthContext available as Context resource: failed to process Authenticate annotation on View or UI")); if (!authContext.getAuthentication().isPresent()) { // not authenticated, try to authenticate from request final VaadinRequest request = VaadinService.getCurrentRequest(); if (request != null) { try { authContext.authenticate(VaadinHttpRequest.create(request)); // authentication succeded return true; } catch (@SuppressWarnings("unused") AuthenticationException e) { // failed, ignore } } onAuthenticationFailed(authc, navigationState); return false; } } } return true; }
/** * Ensure that a {@link DeviceInfo} is available from given Vaadin <code>session</code>. For successful * initialization, a {@link VaadinService#getCurrentRequest()} must be available. * @param session Vaadin session (not null) */ static void ensureInited(VaadinSession session) { ObjectUtils.argumentNotNull(session, "VaadinSession must be not null"); session.access(() -> { if (session.getAttribute(SESSION_ATTRIBUTE_NAME) == null && VaadinService.getCurrentRequest() != null) { session.setAttribute(SESSION_ATTRIBUTE_NAME, create(VaadinService.getCurrentRequest())); } }); }
@Override protected void init(VaadinRequest request) { // Root layout final VerticalLayout root = new VerticalLayout(); root.setSizeFull(); root.setSpacing(false); root.setMargin(false); setContent(root); // Main panel springViewDisplay = new Panel(); springViewDisplay.setSizeFull(); root.addComponent(springViewDisplay); root.setExpandRatio(springViewDisplay, 1); // Footer Layout footer = getFooter(); root.addComponent(footer); root.setExpandRatio(footer, 0); // Error handler UI.getCurrent().setErrorHandler(new UIErrorHandler()); // Disable session expired notification, the page will be reloaded on any action VaadinService.getCurrent().setSystemMessagesProvider( systemMessagesInfo -> { CustomizedSystemMessages msgs = new CustomizedSystemMessages(); msgs.setSessionExpiredNotificationEnabled(false); return msgs; }); }
/** * Ensure that a {@link DeviceInfo} is available from given Vaadin <code>session</code>. For successful * initialization, a {@link VaadinService#getCurrentRequest()} must be available. * @param session Vaadin session (not null) */ static void ensureInited(VaadinSession session) { ObjectUtils.argumentNotNull(session, "VaadinSession must be not null"); synchronized (session) { if (session.getAttribute(SESSION_ATTRIBUTE_NAME) == null && VaadinService.getCurrentRequest() != null) { session.setAttribute(SESSION_ATTRIBUTE_NAME, create(VaadinService.getCurrentRequest())); } } }
public static Cookie getCookie(String name) { Cookie[] cookies = VaadinService.getCurrentRequest().getCookies(); for (Cookie cookie : cookies) { if (name.equals(cookie.getName())) { return cookie; } } return null; }
public static Cookie addCookie(String name, String value) { Cookie newCookie = getCookie(name); if (newCookie != null) { newCookie.setValue(value); } else { newCookie = new Cookie(name, value); } newCookie.setPath("/"); newCookie.setMaxAge(60 * 60 * 24 * 365 * 10); VaadinService.getCurrentResponse().addCookie(newCookie); return newCookie; }
private Cookie getRememberMeCookie() { final VaadinRequest vaadinRequest = VaadinService.getCurrentRequest(); if(vaadinRequest == null) { logger.warn("Could not get the VaadinRequest. It might be that we are called from a websocket connection."); return null; } // // Get the remember me cookie final Cookie[] cookies = vaadinRequest.getCookies(); if (cookies == null) { return null; } for (final Cookie cookie : cookies) { if (COOKIENAME_RememberMe.equals(cookie.getName())) { return cookie; } } return null; }
protected WebBrowser getWebBrowserDetails() { // timezone info is passed only on VaadinSession creation WebBrowser webBrowser = VaadinSession.getCurrent().getBrowser(); VaadinRequest currentRequest = VaadinService.getCurrentRequest(); // update web browser instance if current request is not null // it can be null in case of background/async processing of login request if (currentRequest != null) { webBrowser.updateRequestDetails(currentRequest); } return webBrowser; }
@Order(Events.HIGHEST_PLATFORM_PRECEDENCE + 10) @EventListener protected void onAppStarted(AppStartedEvent event) throws LoginException { Connection connection = event.getApp().getConnection(); // can be already authenticated by another event listener if (webIdpConfig.getIdpEnabled() && !connection.isAuthenticated()) { VaadinRequest currentRequest = VaadinService.getCurrentRequest(); if (currentRequest != null) { Principal principal = currentRequest.getUserPrincipal(); if (principal instanceof IdpSessionPrincipal) { IdpSession idpSession = ((IdpSessionPrincipal) principal).getIdpSession(); Locale locale = event.getApp().getLocale(); ExternalUserCredentials credentials = new ExternalUserCredentials(principal.getName(), locale); credentials.setSessionAttributes( ImmutableMap.of( IdpService.IDP_USER_SESSION_ATTRIBUTE, idpSession.getId() )); connection.login(credentials); } } } }
@SuppressWarnings("unchecked") @Override @Nullable public List<String> getUrls(String selectorId) { VaadinRequest vaadinRequest = VaadinService.getCurrentRequest(); if (vaadinRequest != null) return (List) vaadinRequest.getWrappedSession().getAttribute(getAttributeName(selectorId)); else { HttpSession httpSession = getHttpSession(); return httpSession != null ? (List<String>) httpSession.getAttribute(getAttributeName(selectorId)) : null; } }
@Override public void setUrls(String selectorId, List<String> urls) { VaadinRequest vaadinRequest = VaadinService.getCurrentRequest(); if (vaadinRequest != null) vaadinRequest.getWrappedSession().setAttribute(getAttributeName(selectorId), urls); else { HttpSession httpSession = getHttpSession(); if (httpSession != null) { httpSession.setAttribute(getAttributeName(selectorId), urls); } } }
@Override public void userSessionLoggedIn(UserSession session) { VaadinRequest currentRequest = VaadinService.getCurrentRequest(); if (currentRequest != null) { Principal principal = currentRequest.getUserPrincipal(); if (principal instanceof IdpSessionPrincipal) { IdpSession idpSession = ((IdpSessionPrincipal) principal).getIdpSession(); session.setAttribute(IdpService.IDP_USER_SESSION_ATTRIBUTE, idpSession.getId()); } } }
private static void populateWithRandomHierarchicalData() { final Random random = new Random(); int hours = 0; String basePath = VaadinService.getCurrent().getBaseDirectory().getAbsolutePath(); final Object[] allProjects = new Object[] {"All Projects", 0, new Date(), new ThemeResource("images/balloons.png")}; for (final int year : Arrays.asList(2010, 2011, 2012, 2013)) { int yearHours = 0; final Object[] yearId = new Object[] { "Year " + year, yearHours, new Date(), new ThemeResource(getResourceId(year))}; addChild(allProjects, yearId); for (int project = 1; project < random.nextInt(4) + 2; project++) { int projectHours = 0; final Object[] projectId = new Object[] { "Customer Project " + project, projectHours, new Date(), new ThemeResource(getResourceId(year))}; addChild(yearId, projectId); for (final String phase : Arrays.asList("Implementation", "Planning", "Prototype")) { final int phaseHours = random.nextInt(50); final Object[] phaseId = new Object[] { phase, phaseHours, new Date(), new ThemeResource(getResourceId(year))}; leaves.add(phaseId); addChild(projectId, phaseId); projectHours += phaseHours; projectId[1] = projectHours; } yearHours += projectHours; yearId[1] = yearHours; } hours += yearHours; allProjects[1] = hours; } rootNodes.add(allProjects); }
private static VaadinRequest getCurrentRequest() { VaadinRequest request = VaadinService.getCurrentRequest(); if (request == null) { throw new IllegalStateException( "No request bound to current thread"); } return request; }
public static Subject getCurrentSubject() { Subject subject = (Subject) VaadinService.getCurrentRequest() .getAttribute(FrameworkConfig.SECURITY_SUBJECT); return subject==null? SecurityUtils.getSubject():subject; }
public void login(String username, String password, boolean rememberMe) { try { user = AccessAPI.get(null, null).login(username, password); updateContent(); subscribe(); getBpmAPI().notifyTaskList(); if (rememberMe) { CookieManager.setCookie(COOKIENAME_USERNAME, user.getUsername(), VaadinService.getCurrentRequest().getContextPath()); } } catch (Exception ex) { logger.log(Level.SEVERE, ex.getMessage(), ex); Notification.show("Error", ex.getMessage(), Notification.Type.ERROR_MESSAGE); } }
public void logout() { HazelcastServer.removeDashboardNotificationEventTopic(user.getId().toString(), notificationListenerId); HazelcastServer.getDashboardEventTopic().removeMessageListener(dashboardListenerId); user = null; CookieManager.setCookie(COOKIENAME_USERNAME, null, VaadinService.getCurrentRequest().getContextPath()); VaadinSession.getCurrent().close(); getUI().getPage().setLocation(VaadinService.getCurrentRequest().getContextPath()); VaadinService.getCurrentRequest().getWrappedSession().invalidate(); }
private static Cookie getCookieByName(final String name) { // Fetch all cookies from the request final Cookie[] cookies = VaadinService.getCurrentRequest().getCookies(); if (cookies != null) { // Iterate to find cookie by its name for (final Cookie cookie : cookies) { if (name.equals(cookie.getName())) { return cookie; } } } return null; }
@Override public void loginSucceded(Subject subject) { getSession().setAttribute("subject", subject); Subject.setCurrent(subject); VaadinService.getCurrentRequest().getWrappedSession().setAttribute("subject", subject); updateNavigation(); Page page = getPage(route); show(page, true); }
private Image getImage(String imageFilename) { String basePath = VaadinService.getCurrent().getBaseDirectory().getAbsolutePath(); String filePath = basePath + "/" + imageFilename; File imageFile = new File(filePath); BufferedImage bufferedImage; Image image = new Image(null, new FileResource(imageFile)); if (imageFilename == BODY_IMAGE || imageFilename == BODY_IMAGE_FEMALE || imageFilename == BODY_IMAGE_MALE) { image.setHeight(Math.round(scaleFactor*BODY_IMAGE_HEIGHT), Unit.PIXELS); image.setWidth(Math.round(scaleFactor*BODY_IMAGE_WIDTH), Unit.PIXELS); } else if (imageFilename == SELECTION_INDICATOR || imageFilename == WOUND_INDICATOR || imageFilename == WOUND_HEALED_INDICATOR || imageFilename == WOUND_SELECTION_INDICATOR) { image.setHeight(Math.round(scaleFactor*INDICATOR_HEIGHT), Unit.PIXELS); image.setWidth(Math.round(scaleFactor*INDICATOR_WIDTH), Unit.PIXELS); } else { // We need to load the image and get the size since Vaadin Touchkit cannot read the size itself try { bufferedImage = ImageIO.read(imageFile); image.setHeight(Math.round(scaleFactor*bufferedImage.getHeight()), Unit.PIXELS); image.setWidth(Math.round(scaleFactor*bufferedImage.getWidth()), Unit.PIXELS); } catch (IOException e) { // we fail silently and let Vaadin use autosizing } } return image; }
@Override public VaadinService getObject() throws Exception { final VaadinService vaadinService = VaadinService.getCurrent(); if (vaadinService == null) { throw new IllegalStateException("No VaadinService bound to current thread"); } return vaadinService; }
/** * Gets verification result based on session and request parameters. This should be called when * processing the OpenId return request. * @param siteUrl the site URL * @param returnViewName the return view name * * @return the verification result * @throws DiscoveryException if discovery exception occurs. * @throws MessageException if message exception occurs. * @throws AssociationException if association exception occurs. */ public static VerificationResult getVerificationResult(final String siteUrl , final String returnViewName) throws MessageException, DiscoveryException, AssociationException { final ConsumerManager consumerManager = UI.getCurrent().getSession().getAttribute(ConsumerManager.class); final DiscoveryInformation discovered = UI.getCurrent().getSession().getAttribute( DiscoveryInformation.class); UI.getCurrent().getSession().setAttribute(ConsumerManager.class, null); UI.getCurrent().getSession().setAttribute(DiscoveryInformation.class, null); final HttpServletRequest request = ((VaadinServletRequest) VaadinService.getCurrentRequest()) .getHttpServletRequest(); final StringBuffer urlBuilder = new StringBuffer(siteUrl + returnViewName); final String queryString = request.getQueryString(); if (queryString != null) { urlBuilder.append('?'); urlBuilder.append(queryString); } final String requestUrl = urlBuilder.toString(); final ParameterList openidResp = new ParameterList(request.getParameterMap()); // verify the response return consumerManager.verify(requestUrl, openidResp, discovered); }
private String constructStartJnlp(String uid) { StringBuilder builder = new StringBuilder(); String contextUrl = ServletUtil.getContextURL((VaadinServletRequest) VaadinService.getCurrentRequest()); builder.append(contextUrl); builder.append("/resource/browserapplication.jnlp?"); builder.append("jnlp.app_url="); builder.append(contextUrl); builder.append("/process/"); builder.append("&jnlp.close_key="); builder.append("close.html"); builder.append("&jnlp.token="); builder.append(uid); return builder.toString(); }
@Override public IView buildLayout() { layout = createTranslatedCustomLayout(templateData); if (layout != null && ! VaadinService.getCurrent().getDeploymentConfiguration().isProductionMode()) { new ComponentHighlighterExtension(getLayout()).setComponentDebugLabel(getClass().getName() + " (template name: " + templateData.name() + ".html)"); } return this; }
private void redirectToMainView() { // Close the VaadinServiceSession getUI().getSession().close(); // Invalidate underlying session instead if login info is stored there VaadinService.getCurrentRequest().getWrappedSession().invalidate(); getUI().getPage().setLocation( "/VAADIN" ); }
private void addLogo(final VerticalLayout viewLayout) { final VerticalLayout layout = new VerticalLayout(); HorizontalLayout buttons = getLoginAccountButtons(); HorizontalLayout buttonLayout = new HorizontalLayout(); buttonLayout.setWidth("100%"); buttonLayout.addComponent(buttons); buttonLayout.setComponentAlignment(buttons, Alignment.TOP_RIGHT); layout.addComponent(buttonLayout); // So the logo final HorizontalLayout logoLayout = new HorizontalLayout(); logoLayout.setWidth("100%"); final String basepath = VaadinService.getCurrent().getBaseDirectory().getAbsolutePath(); final FileResource resource = new FileResource(new File(basepath + "/images/scoutmaster-logo.png")); final Image image = new Image(null, resource); image.setAlternateText("Scoutmaster Logo"); logoLayout.addComponent(image); layout.addComponent(logoLayout); layout.setComponentAlignment(logoLayout, Alignment.TOP_LEFT); viewLayout.addComponent(layout); }