Java 类com.vaadin.server.VaadinService 实例源码

项目:holon-vaadin7    文件:TestDeviceInfo.java   
@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());

}
项目:holon-vaadin    文件:TestDeviceInfo.java   
@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());

}
项目:vaadin-vertx-samples    文件:SimpleUI.java   
@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());
}
项目:dungeonstory-java    文件:SpellChoiceForm.java   
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);
}
项目:metasfresh-procurement-webui    文件:LoginRememberMeService.java   
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);
    }
}
项目:metasfresh-procurement-webui    文件:LoginRememberMeService.java   
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);
    }
}
项目:cuba    文件:ConnectionImpl.java   
@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;
}
项目:hawkbit    文件:AbstractHawkbitLoginUI.java   
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);
}
项目:hawkbit    文件:AbstractHawkbitUI.java   
/**
 * 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;
}
项目:cia    文件:LogoutClickListener.java   
@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());
    }
}
项目:hypothesis    文件:PublicPacksPresenter.java   
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();
}
项目:scoutmaster    文件:SchoolView.java   
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;
}
项目:jdal    文件:VaadinAccessDeniedHandler.java   
/**
 * 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;
}
项目:holon-vaadin7    文件:NavigatorActuator.java   
/**
 * 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;
}
项目:holon-vaadin7    文件:DeviceInfo.java   
/**
 * 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()));
        }
    });
}
项目:Persephone    文件:PersephoneUI.java   
@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;
            });
}
项目:holon-vaadin    文件:NavigatorActuator.java   
/**
 * 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;
}
项目:holon-vaadin    文件:DeviceInfo.java   
/**
 * 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()));
        }
    }
}
项目:bbplay    文件:Cookies.java   
public static Cookie getCookie(String name) {
    Cookie[] cookies = VaadinService.getCurrentRequest().getCookies();
    for (Cookie cookie : cookies) {
        if (name.equals(cookie.getName())) {
            return cookie;
        }
    }
    return null;
}
项目:bbplay    文件:Cookies.java   
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;
}
项目:metasfresh-procurement-webui    文件:LoginRememberMeService.java   
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;
}
项目:cuba    文件:ConnectionImpl.java   
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;
}
项目:cuba    文件:IdpLoginLifecycleManager.java   
@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);
            }
        }
    }
}
项目:cuba    文件:WebHttpSessionUrlsHolder.java   
@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;
    }
}
项目:cuba    文件:WebHttpSessionUrlsHolder.java   
@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);
        }
    }
}
项目:cuba    文件:IdpAuthProvider.java   
@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());
        }
    }
}
项目:tree-grid    文件:DataSource.java   
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);
}
项目:VaadinSpringShiroMongoDB    文件:CurrentUser.java   
private static VaadinRequest getCurrentRequest() {
    VaadinRequest request = VaadinService.getCurrentRequest();
    if (request == null) {
        throw new IllegalStateException(
                "No request bound to current thread");
    }
    return request;
}
项目:VaadinSpringShiroMongoDB    文件:ShiroAccessControl.java   
public static Subject getCurrentSubject()
{
    Subject subject = (Subject) VaadinService.getCurrentRequest()
            .getAttribute(FrameworkConfig.SECURITY_SUBJECT);
    return subject==null? SecurityUtils.getSubject():subject;

}
项目:hybridbpm    文件:HybridbpmUI.java   
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);
    }
}
项目:hybridbpm    文件:HybridbpmUI.java   
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();
}
项目:hawkbit    文件:AbstractHawkbitLoginUI.java   
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;
}
项目:minimal-j    文件:Vaadin.java   
@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);
}
项目:root    文件:WoundSelector.java   
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;
}
项目:vaadin4spring    文件:VaadinServiceFactory.java   
@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;
}
项目:ilves    文件:OpenIdUtil.java   
/**
 * 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);
}
项目:hypothesis    文件:PublicPacksPresenter.java   
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();
}
项目:AppBaseForVaadin    文件:TranslatedCustomLayout.java   
@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;
}
项目:usergrid    文件:MainView.java   
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" );
}
项目:scoutmaster    文件:HomeView.java   
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);

}