Example usage for com.vaadin.server VaadinSession getCurrent

List of usage examples for com.vaadin.server VaadinSession getCurrent

Introduction

In this page you can find the example usage for com.vaadin.server VaadinSession getCurrent.

Prototype

public static VaadinSession getCurrent() 

Source Link

Document

Gets the currently used session.

Usage

From source file:com.lexaden.platform.web.ApplicationUIProvider.java

License:Apache License

@SuppressWarnings("unchecked")
@Override//  w  w  w  .  ja v a 2s.c  o  m
public UI createInstance(UICreateEvent event) {
    VaadinRequest request = event.getRequest();
    Object uiBeanNameObj = request.getService().getDeploymentConfiguration()
            .getApplicationOrSystemProperty("UIBean", null);

    //Stored in VaadinSession to use it in
    // the ApplicationScope later to initialize vaadin application scope beans
    final Integer uiId = event.getUiId();
    VaadinSession.getCurrent().setAttribute("applicationScope.UiId", uiId);

    if (uiBeanNameObj instanceof String) {
        String uiBeanName = uiBeanNameObj.toString();
        return (UI) ApplicationContextLocator.getBean(uiBeanName);
    }
    return super.createInstance(event);
}

From source file:com.mcparland.john.vaadin_mvn_arch.samples.Menu.java

License:Apache License

public Menu(Navigator navigator) {
    this.navigator = navigator;
    setPrimaryStyleName(ValoTheme.MENU_ROOT);
    menuPart = new CssLayout();
    menuPart.addStyleName(ValoTheme.MENU_PART);

    // header of the menu
    final HorizontalLayout top = new HorizontalLayout();
    top.setDefaultComponentAlignment(Alignment.MIDDLE_LEFT);
    top.addStyleName(ValoTheme.MENU_TITLE);
    top.setSpacing(true);/*from  w  w  w.  j  ava2s  .c o m*/
    Label title = new Label("My CRUD");
    title.addStyleName(ValoTheme.LABEL_H3);
    title.setSizeUndefined();
    Image image = new Image(null, new ThemeResource("img/table-logo.png"));
    image.setStyleName("logo");
    top.addComponent(image);
    top.addComponent(title);
    menuPart.addComponent(top);

    // logout menu item
    MenuBar logoutMenu = new MenuBar();
    logoutMenu.addItem("Logout", FontAwesome.SIGN_OUT, new Command() {

        /**
         * The serialVersionUID.
         */
        private static final long serialVersionUID = 1L;

        @Override
        public void menuSelected(MenuItem selectedItem) {
            VaadinSession.getCurrent().getSession().invalidate();
            Page.getCurrent().reload();
        }
    });

    logoutMenu.addStyleName("user-menu");
    menuPart.addComponent(logoutMenu);

    // button for toggling the visibility of the menu when on a small screen
    final Button showMenu = new Button("Menu", new ClickListener() {
        /**
         * The serialVersionUID.
         */
        private static final long serialVersionUID = 1L;

        @Override
        public void buttonClick(final ClickEvent event) {
            if (menuPart.getStyleName().contains(VALO_MENU_VISIBLE)) {
                menuPart.removeStyleName(VALO_MENU_VISIBLE);
            } else {
                menuPart.addStyleName(VALO_MENU_VISIBLE);
            }
        }
    });
    showMenu.addStyleName(ValoTheme.BUTTON_PRIMARY);
    showMenu.addStyleName(ValoTheme.BUTTON_SMALL);
    showMenu.addStyleName(VALO_MENU_TOGGLE);
    showMenu.setIcon(FontAwesome.NAVICON);
    menuPart.addComponent(showMenu);

    // container for the navigation buttons, which are added by addView()
    menuItemsLayout = new CssLayout();
    menuItemsLayout.setPrimaryStyleName(VALO_MENUITEMS);
    menuPart.addComponent(menuItemsLayout);

    addComponent(menuPart);
}

From source file:com.mycollab.mobile.MobileApplication.java

License:Open Source License

@Override
protected void init(VaadinRequest request) {
    OfflineMode offlineMode = new OfflineMode();
    offlineMode.extend(this);

    // Maintain the session when the browser app closes
    offlineMode.setPersistentSessionCookie(true);

    // Define the timeout in secs to wait when a server
    // request is sent before falling back to offline mode
    offlineMode.setOfflineModeTimeout(15);

    VaadinSession.getCurrent().setErrorHandler(new DefaultErrorHandler() {
        private static final long serialVersionUID = 1L;

        @Override/* w  w w.j a v  a  2 s . com*/
        public void error(com.vaadin.server.ErrorEvent event) {
            Throwable e = event.getThrowable();
            IgnoreException ignoreException = (IgnoreException) getExceptionType(e, IgnoreException.class);
            if (ignoreException != null) {
                return;
            }

            SessionExpireException sessionExpireException = (SessionExpireException) getExceptionType(e,
                    SessionExpireException.class);
            if (sessionExpireException != null) {
                Page.getCurrent().getJavaScript().execute("window.location.reload();");
                return;
            }

            UserInvalidInputException invalidException = (UserInvalidInputException) getExceptionType(e,
                    UserInvalidInputException.class);
            if (invalidException != null) {
                NotificationUtil.showWarningNotification(UserUIContext
                        .getMessage(GenericI18Enum.ERROR_USER_INPUT_MESSAGE, invalidException.getMessage()));
            } else {
                UsageExceedBillingPlanException usageBillingException = (UsageExceedBillingPlanException) getExceptionType(
                        e, UsageExceedBillingPlanException.class);
                if (usageBillingException != null) {
                    if (UserUIContext.isAdmin()) {
                        ConfirmDialog.show(UI.getCurrent(),
                                UserUIContext.getMessage(GenericI18Enum.EXCEED_BILLING_PLAN_MSG_FOR_ADMIN),
                                UserUIContext.getMessage(GenericI18Enum.BUTTON_YES),
                                UserUIContext.getMessage(GenericI18Enum.BUTTON_NO), dialog -> {
                                    if (dialog.isConfirmed()) {
                                        Collection<Window> windows = UI.getCurrent().getWindows();
                                        for (Window window : windows) {
                                            window.close();
                                        }
                                        EventBusFactory.getInstance().post(new ShellEvent.GotoUserAccountModule(
                                                this, new String[] { "billing" }));
                                    }
                                });

                    } else {
                        NotificationUtil.showErrorNotification(
                                UserUIContext.getMessage(GenericI18Enum.EXCEED_BILLING_PLAN_MSG_FOR_USER));
                    }
                } else {
                    LOG.error("Error", e);
                    NotificationUtil.showErrorNotification(
                            UserUIContext.getMessage(GenericI18Enum.ERROR_USER_NOTICE_INFORMATION_MESSAGE));
                }
            }

        }
    });

    setCurrentFragmentUrl(this.getPage().getUriFragment());
    currentContext = new UserUIContext();
    postSetupApp(request);

    final NavigationManager manager = new NavigationManager();
    setContent(manager);

    registerControllers(manager);
    ThemeManager.loadMobileTheme(MyCollabUI.getAccountId());

    getPage().addUriFragmentChangedListener(new UriFragmentChangedListener() {
        private static final long serialVersionUID = -6410955178515535406L;

        @Override
        public void uriFragmentChanged(UriFragmentChangedEvent event) {
            setCurrentFragmentUrl(event.getUriFragment());
            enter(event.getUriFragment());
        }
    });
    detectAutoLogin();
}

From source file:com.mycollab.vaadin.AppContext.java

License:Open Source License

/**
 * Keep user session in server sessions/*from  w  w  w . j a  v  a2  s  . c  om*/
 *
 * @param userSession current user
 * @param billingAc   account information of current user
 */
public void setSessionVariables(SimpleUser userSession, SimpleBillingAccount billingAc) {
    session = userSession;
    billingAccount = billingAc;

    String language = session.getLanguage();
    userLocale = language != null ? LocalizationHelper.getLocaleInstance(language)
            : billingAccount.getLocaleInstance();
    VaadinSession.getCurrent().setLocale(userLocale);
    messageHelper = LocalizationHelper.getMessageConveyor(userLocale);

    userTimeZone = TimezoneVal.valueOf(session.getTimezone());
    MyCollabSession.putSessionVariable(USER_VAL, userSession);
}

From source file:com.mycollab.vaadin.ui.MyCollabSession.java

License:Open Source License

public static void putSessionVariable(String key, Object value) {
    try {/*w  w w  .  j a  v a  2 s.  c  o m*/
        VaadinSession.getCurrent().setAttribute(key, value);
    } catch (Exception e) {
        throw new SessionExpireException("Expire Exception");
    }
}

From source file:com.mycollab.vaadin.ui.MyCollabSession.java

License:Open Source License

public static Object getSessionVariable(String key) {
    try {/*w  w w.  j a v  a 2  s  .  c o  m*/
        return VaadinSession.getCurrent().getAttribute(key);
    } catch (Exception e) {
        throw new SessionExpireException("Expire Exception");
    }
}

From source file:com.mycollab.vaadin.ui.MyCollabSession.java

License:Open Source License

public static void removeSessionVariable(String key) {
    try {// w  w  w.  jav  a 2s  . c om
        VaadinSession.getCurrent().setAttribute(key, null);
    } catch (Exception e) {
        throw new SessionExpireException("Expire Exception");
    }
}

From source file:com.mycollab.web.DesktopApplication.java

License:Open Source License

@Override
protected void init(final VaadinRequest request) {
    broadcastReceiverService = AppContextUtil.getSpringBean(BroadcastReceiverService.class);
    if (SiteConfiguration.getPullMethod() == SiteConfiguration.PullMethod.push) {
        getPushConfiguration().setPushMode(PushMode.MANUAL);
    }//from ww w  .java  2s  . c o  m

    VaadinSession.getCurrent().setErrorHandler(new DefaultErrorHandler() {
        private static final long serialVersionUID = 1L;

        @Override
        public void error(com.vaadin.server.ErrorEvent event) {
            Throwable e = event.getThrowable();
            handleException(request, e);
        }
    });

    setCurrentFragmentUrl(this.getPage().getUriFragment());
    currentContext = new UserUIContext();
    postSetupApp(request);

    EventBusFactory.getInstance().register(new ShellErrorHandler());

    mainWindowContainer = new MainWindowContainer();
    this.setContent(mainWindowContainer);

    getPage().setTitle("MyCollab - Online project management");

    getPage().addUriFragmentChangedListener(
            uriFragmentChangedEvent -> enter(uriFragmentChangedEvent.getUriFragment()));

    String userAgent = request.getHeader("user-agent");
    if (isInNotSupportedBrowserList(userAgent.toLowerCase())) {
        NotificationUtil.showWarningNotification(UserUIContext.getMessage(ErrorI18nEnum.BROWSER_OUT_UP_DATE));
    }
}

From source file:com.ocs.dynamo.domain.model.impl.EntityModelFactoryImpl.java

License:Apache License

protected Locale getLocale() {
    VaadinSession session = VaadinSession.getCurrent();
    if (session != null) {
        return session.getLocale();
    }//from   w w w .j  a v  a2 s .co m
    return Locale.getDefault();
}

From source file:com.ocs.dynamo.domain.model.impl.ModelBasedFieldFactory.java

License:Apache License

/**
 * Creates a field//from   w w w  . jav a 2 s.c om
 * 
 * @param propertyId
 *            the name of the property that can be edited by this field
 * @param fieldEntityModel
 *            the custom entity model for the field
 * @return
 */
public Field<?> createField(String propertyId, EntityModel<?> fieldEntityModel) {

    // in case of a read-only field, return <code>null</code> so Vaadin will
    // render a label instead
    AttributeModel attributeModel = model.getAttributeModel(propertyId);
    if (attributeModel.isReadOnly()
            && (!attributeModel.isUrl() && !AttributeType.DETAIL.equals(attributeModel.getAttributeType()))
            && !search) {
        return null;
    }

    Field<?> field = null;

    if (AttributeTextFieldMode.TEXTAREA.equals(attributeModel.getTextFieldMode()) && !search) {
        // text area field
        field = new TextArea();
    } else if (attributeModel.isWeek()) {
        // special case - week field in a table
        TextField tf = new TextField();
        tf.setConverter(new WeekCodeConverter());
        field = tf;
    } else if (search && attributeModel.getType().equals(Boolean.class)) {
        // in a search screen, we need to offer the true, false, and
        // undefined options
        field = constructSearchBooleanComboBox(attributeModel);
    } else if (AbstractEntity.class.isAssignableFrom(attributeModel.getType())) {
        // lookup or combo field for an entity
        field = constructSelectField(attributeModel, fieldEntityModel, null);
    } else if (AttributeType.ELEMENT_COLLECTION.equals(attributeModel.getAttributeType())) {
        // use a "collection table" for an element collection
        FormOptions fo = new FormOptions();
        fo.setShowRemoveButton(true);
        if (String.class.equals(attributeModel.getMemberType())) {
            CollectionTable<String> table = new CollectionTable<>(false, fo, String.class);
            table.setMinLength(attributeModel.getMinLength());
            table.setMaxLength(attributeModel.getMaxLength());
            field = table;
        } else if (Integer.class.equals(attributeModel.getMemberType())) {
            CollectionTable<Integer> table = new CollectionTable<>(false, fo, Integer.class);
            field = table;
        } else {
            // other types not supported for now
            throw new OCSRuntimeException();
        }
    } else if (Collection.class.isAssignableFrom(attributeModel.getType())) {
        // render a multiple select component for a collection
        field = constructCollectionSelect(attributeModel.getNestedEntityModel(), attributeModel, null, true,
                search);
    } else if (AttributeDateType.TIME.equals(attributeModel.getDateType())) {
        TimeField tf = new TimeField();
        tf.setResolution(Resolution.MINUTE);
        tf.setLocale(VaadinSession.getCurrent() == null ? DynamoConstants.DEFAULT_LOCALE
                : VaadinSession.getCurrent().getLocale());
        field = tf;
    } else if (attributeModel.isUrl()) {
        // URL field (offers clickable link in readonly mode)
        TextField tf = (TextField) createField(attributeModel.getType(), Field.class);
        tf.addValidator(new URLValidator(messageService.getMessage("ocs.no.valid.url")));
        tf.setNullRepresentation(null);
        tf.setSizeFull();

        // wrap text field in URL field
        field = new URLField(tf, attributeModel, false);
        field.setSizeFull();
    } else {
        // just a regular field
        field = createField(attributeModel.getType(), Field.class);
    }
    field.setCaption(attributeModel.getDisplayName());

    postProcessField(field, attributeModel);

    // add a field validator based on JSR-303 bean validation
    if (validate) {
        field.addValidator(new BeanValidator(model.getEntityClass(), (String) propertyId));
        // disable the field if it cannot be edited
        if (!attributeModel.isUrl()) {
            field.setEnabled(!attributeModel.isReadOnly());
        }

        if (attributeModel.isNumerical()) {
            field.addStyleName(DynamoConstants.CSS_NUMERICAL);
        }
    }
    return field;
}