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.ejt.vaadin.loginform.LoginForm.java

License:Apache License

private void init() {
    if (initialized) {
        return;/*from  www .  j a v  a 2 s  .co  m*/
    }

    LoginFormState state = getState();
    state.userNameFieldConnector = createUserNameField();
    state.passwordFieldConnector = createPasswordField();
    state.loginButtonConnector = createLoginButton();

    String contextPath = VaadinService.getCurrentRequest().getContextPath();
    if (contextPath.endsWith("/")) {
        contextPath = contextPath.substring(0, contextPath.length() - 1);
    }
    state.contextPath = contextPath;

    VaadinSession.getCurrent().addRequestHandler(new RequestHandler() {
        @Override
        public boolean handleRequest(VaadinSession session, VaadinRequest request, VaadinResponse response)
                throws IOException {
            if (LoginFormConnector.LOGIN_URL.equals(request.getPathInfo())) {
                response.setContentType("text/html; charset=utf-8");
                response.setCacheTime(-1);
                PrintWriter writer = response.getWriter();
                writer.append("<html>Success</html>");
                return true;
            } else {
                return false;
            }
        }
    });

    registerRpc(new LoginFormRpc() {
        @Override
        public void submitCompleted() {
            login();
        }
    });

    initialized = true;

    setContent(createContent(getUserNameField(), getPasswordField(), getLoginButton()));
}

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

License:Open Source License

@Override
protected void init(VaadinRequest request) {
    LOG.debug("Init mycollab mobile application {}", this.toString());

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

        @Override/*  w ww . j  a  va 2 s  .co  m*/
        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(AppContext
                        .getMessage(GenericI18Enum.ERROR_USER_INPUT_MESSAGE, invalidException.getMessage()));
            } else {

                UsageExceedBillingPlanException usageBillingException = (UsageExceedBillingPlanException) getExceptionType(
                        e, UsageExceedBillingPlanException.class);
                if (usageBillingException != null) {
                    if (AppContext.isAdmin()) {
                        ConfirmDialog.show(UI.getCurrent(),
                                AppContext.getMessage(GenericI18Enum.EXCEED_BILLING_PLAN_MSG_FOR_ADMIN),
                                AppContext.getMessage(GenericI18Enum.BUTTON_YES),
                                AppContext.getMessage(GenericI18Enum.BUTTON_NO),
                                new ConfirmDialog.CloseListener() {
                                    private static final long serialVersionUID = 1L;

                                    @Override
                                    public void onClose(ConfirmDialog dialog) {
                                        if (dialog.isConfirmed()) {
                                            Collection<Window> windowsList = UI.getCurrent().getWindows();
                                            for (Window window : windowsList) {
                                                window.close();
                                            }
                                            EventBusFactory.getInstance()
                                                    .post(new ShellEvent.GotoUserAccountModule(this,
                                                            new String[] { "billing" }));
                                        }
                                    }
                                });

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

        }
    });

    initialUrl = this.getPage().getUriFragment();
    MyCollabSession.putVariable(CURRENT_APP, this);
    currentContext = new AppContext();
    postSetupApp(request);
    try {
        currentContext.initDomain(initialSubDomain);
    } catch (Exception e) {
        // TODO: show content notice user there is no existing domain
        return;
    }

    this.getLoadingIndicatorConfiguration().setFirstDelay(0);
    this.getLoadingIndicatorConfiguration().setSecondDelay(300);
    this.getLoadingIndicatorConfiguration().setThirdDelay(500);

    final MobileNavigationManager manager = new MobileNavigationManager();
    manager.addNavigationListener(new NavigationManager.NavigationListener() {
        private static final long serialVersionUID = -2317588983851761998L;

        @SuppressWarnings("unchecked")
        @Override
        public void navigate(NavigationEvent event) {
            NavigationManager currentNavigator = (NavigationManager) event.getSource();
            if (event.getDirection() == Direction.BACK) {
                Component nextComponent = currentNavigator.getNextComponent();
                ViewState currentState = MobileHistoryViewManager.peak();

                if (!(currentState instanceof NullViewState)
                        && currentState.getPresenter().getView().equals(nextComponent)) {
                    ViewState viewState = MobileHistoryViewManager.pop();
                    while (!(viewState instanceof NullViewState)) {
                        if (viewState.getPresenter().getView().equals(currentNavigator.getCurrentComponent())) {
                            viewState.getPresenter().go(viewState.getContainer(), viewState.getParams());
                            break;
                        }
                        viewState = MobileHistoryViewManager.pop(false);
                    }
                }
                if (nextComponent instanceof NavigationView) {
                    ((NavigationView) nextComponent).setPreviousComponent(null);
                }
                currentNavigator.removeComponent(nextComponent);
                currentNavigator.getState().setNextComponent(null);

            }
        }
    });
    setContent(manager);

    registerControllers(manager);

    getPage().addUriFragmentChangedListener(new UriFragmentChangedListener() {

        private static final long serialVersionUID = -6410955178515535406L;

        @Override
        public void uriFragmentChanged(UriFragmentChangedEvent event) {
            setInitialUrl(event.getUriFragment());
            enter(event.getUriFragment());
        }
    });
    enter(initialUrl);
}

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

License:Open Source License

private void setUserVariables() {
    String language = session.getLanguage();
    userLocale = LocaleHelper.toLocale(language);
    VaadinSession.getCurrent().setLocale(userLocale);
    messageHelper = LocalizationHelper.getMessageConveyor(userLocale);
    MyCollabSession.putVariable(USER_DATE_FORMAT, LocaleHelper.getDateFormatAssociateToLocale(userLocale));
    MyCollabSession.putVariable(USER_DATE_TIME_DATE_FORMAT,
            LocaleHelper.getDateTimeFormatAssociateToLocale(userLocale));
    MyCollabSession.putVariable(USER_SHORT_DATE_FORMAT,
            LocaleHelper.getShortDateFormatAssociateToLocale(userLocale));
    MyCollabSession.putVariable(USER_DAY_MONTH_FORMAT,
            LocaleHelper.getDayMonthFormatAssociateToLocale(userLocale));

    TimeZone timezone = null;/* w  w  w  .  j a v  a 2  s .c  o  m*/
    if (session.getTimezone() == null) {
        timezone = TimeZone.getDefault();
    } else {
        timezone = TimezoneMapper.getTimezone(session.getTimezone());
    }
    MyCollabSession.putVariable(USER_TIMEZONE, timezone);
}

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

License:Open Source License

@Override
protected void init(VaadinRequest request) {
    LOG.debug("Init mycollab application {} associate with session {}", this.toString(),
            VaadinSession.getCurrent());
    LOG.debug("Register default error handler");

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

        @Override/* w w  w  .  j  ava 2  s . co  m*/
        public void error(com.vaadin.server.ErrorEvent event) {
            Throwable e = event.getThrowable();
            handleException(e);
        }
    });

    initialUrl = this.getPage().getUriFragment();
    MyCollabSession.putVariable(CURRENT_APP, this);
    currentContext = new AppContext();
    postSetupApp(request);
    try {
        currentContext.initDomain(initialSubDomain);
    } catch (SubDomainNotExistException e) {
        this.setContent(new NoSubDomainExistedWindow(initialSubDomain));
        return;
    }

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

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

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

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

    String userAgent = request.getHeader("user-agent");
    if (isInNotSupportedBrowserList(userAgent.toLowerCase())) {
        NotificationUtil
                .showWarningNotification("Your browser is out of date. Some features of MyCollab will not"
                        + " behave correctly. You should upgrade to the newer browser.");
    }
}

From source file:com.etest.administrator.UserAccess.java

public static boolean approve() {
    return VaadinSession.getCurrent().getAttribute("userType").toString().equals("Year Level Coordinator");
}

From source file:com.etest.administrator.UserAccess.java

public static boolean delete() {
    return VaadinSession.getCurrent().getAttribute("userType").toString().equals("Year Level Coordinator");
}

From source file:com.etest.dao.CellCaseDAO.java

public static boolean approveCellCase(int cellCaseId) {
    Connection conn = DBConnection.connectToDB();
    PreparedStatement pstmt = null;
    boolean result = false;

    try {//from  w  ww .  ja v  a  2s.  c om
        conn.setAutoCommit(false);
        pstmt = conn
                .prepareStatement("UPDATE cell_cases SET " + "ApprovalStatus = ? " + "WHERE CellCaseID = ? ");
        pstmt.setInt(1, 1);
        pstmt.setInt(2, cellCaseId);
        pstmt.executeUpdate();

        pstmt = conn.prepareStatement("INSERT INTO case_log SET " + "cellCaseID = ?, " + "UserID = ?, "
                + "Remarks = ?, " + "DateRemarked = now(), " + "ActionDone = ? ");
        pstmt.setInt(1, cellCaseId);
        pstmt.setInt(2, CommonUtilities
                .convertStringToInt(VaadinSession.getCurrent().getAttribute("userId").toString()));
        pstmt.setString(3, "approved case");
        pstmt.setString(4, "approved");
        pstmt.executeUpdate();

        pstmt = conn.prepareStatement(
                "INSERT INTO system_logs SET " + "UserID = ?, " + "EntryDateTime = now(), " + "Activity = ? ");
        pstmt.setInt(1, CommonUtilities
                .convertStringToInt(VaadinSession.getCurrent().getAttribute("userId").toString()));
        pstmt.setString(2, "Approved cell case with CellCaseID #" + cellCaseId);
        pstmt.executeUpdate();

        conn.commit();
        result = true;
    } catch (SQLException ex) {
        try {
            conn.rollback();
        } catch (SQLException ex1) {
            ErrorDBNotification.showLoggedErrorOnWindow(ex1.toString());
            Logger.getLogger(CellCaseDAO.class.getName()).log(Level.SEVERE, null, ex1);
        }
        ErrorDBNotification.showLoggedErrorOnWindow(ex.toString());
        Logger.getLogger(CellCaseDAO.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            pstmt.close();
            conn.close();
        } catch (SQLException ex) {
            ErrorDBNotification.showLoggedErrorOnWindow(ex.toString());
            Logger.getLogger(CellCaseDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    return result;
}

From source file:com.etest.dao.CellCaseDAO.java

public static boolean removeCellCase(int cellCaseId) {
    Connection conn = DBConnection.connectToDB();
    PreparedStatement pstmt = null;
    boolean result = false;

    try {/*from w  w w .j av  a  2 s. co  m*/
        conn.setAutoCommit(false);
        pstmt = conn
                .prepareStatement("UPDATE cell_cases SET " + "CellCaseStatus = ? " + "WHERE CellCaseID = ? ");
        pstmt.setInt(1, 1);
        pstmt.setInt(2, cellCaseId);
        pstmt.executeUpdate();

        pstmt = conn.prepareStatement("INSERT INTO case_log SET " + "cellCaseID = ?, " + "UserID = ?, "
                + "Remarks = ?, " + "DateRemarked = now(), " + "ActionDone = ? ");
        pstmt.setInt(1, cellCaseId);
        pstmt.setInt(2, CommonUtilities
                .convertStringToInt(VaadinSession.getCurrent().getAttribute("userId").toString()));
        pstmt.setString(3, "delete case");
        pstmt.setString(4, "delete");
        pstmt.executeUpdate();

        pstmt = conn
                .prepareStatement("UPDATE cell_items SET " + "CellItemStatus = ? " + "WHERE CellCaseID = ? ");
        pstmt.setInt(1, 1);
        pstmt.setInt(2, cellCaseId);
        pstmt.executeUpdate();

        for (CellItem cellItem : CellItemDAO.getCellItemByCase(cellCaseId)) {
            pstmt = conn.prepareStatement("INSERT INTO item_log SET " + "CellItemID = ?, " + "UserID = ?, "
                    + "Remarks = ?, " + "DateRemarked = now(), " + "ActionDone = ? ");
            pstmt.setInt(1, cellItem.getCellItemId());
            pstmt.setInt(2, CommonUtilities
                    .convertStringToInt(VaadinSession.getCurrent().getAttribute("userId").toString()));
            pstmt.setString(3, "delete cell item by case");
            pstmt.setString(4, "delete");
            pstmt.executeUpdate();
        }

        pstmt = conn.prepareStatement(
                "INSERT INTO system_logs SET " + "UserID = ?, " + "EntryDateTime = now(), " + "Activity = ? ");
        pstmt.setInt(1, CommonUtilities
                .convertStringToInt(VaadinSession.getCurrent().getAttribute("userId").toString()));
        pstmt.setString(2, "Removed cell case with CellCaseID #" + cellCaseId);
        pstmt.executeUpdate();

        conn.commit();
        result = true;
    } catch (SQLException ex) {
        try {
            conn.rollback();
        } catch (SQLException ex1) {
            ErrorDBNotification.showLoggedErrorOnWindow(ex1.toString());
            Logger.getLogger(CellCaseDAO.class.getName()).log(Level.SEVERE, null, ex1);
        }
        ErrorDBNotification.showLoggedErrorOnWindow(ex.toString());
        Logger.getLogger(CellCaseDAO.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            pstmt.close();
            conn.close();
        } catch (SQLException ex) {
            ErrorDBNotification.showLoggedErrorOnWindow(ex.toString());
            Logger.getLogger(CellCaseDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    return result;
}

From source file:com.etest.dao.CellItemDAO.java

public static boolean insertNewCellItem(CellItem ci) {
    Connection conn = DBConnection.connectToDB();
    Statement stmt = null;/*from  w  w  w . j a  v  a 2  s  .c o  m*/
    ResultSet rs = null;
    PreparedStatement pstmt = null;
    boolean result = false;

    try {
        conn.setAutoCommit(false);
        pstmt = conn.prepareStatement("INSERT INTO cell_items SET " + "CellCaseID = ?, " + "BloomsClassID = ?, "
                + "Item = ?, " + "OptionA = ?, " + "OptionB = ?, " + "OptionC = ?, " + "OptionD = ?, "
                + "AuthoredBy_UserID = ?, " + "DateCreated = now() ");
        pstmt.setInt(1, ci.getCellCaseId());
        pstmt.setInt(2, ci.getBloomsClassId());
        pstmt.setString(3, ci.getItem());
        pstmt.setString(4, ci.getOptionA());
        pstmt.setString(5, ci.getOptionB());
        pstmt.setString(6, ci.getOptionC());
        pstmt.setString(7, ci.getOptionD());
        pstmt.setInt(8, ci.getUserId());
        pstmt.executeUpdate();

        int cellItemId = 0;
        stmt = conn.createStatement();
        rs = stmt.executeQuery("SELECT last_insert_id() AS id FROM cell_items ");
        while (rs.next()) {
            cellItemId = CommonUtilities.convertStringToInt(rs.getString("id"));
        }

        for (Map.Entry<String, String> entrySet : ci.getItemKeys().entrySet()) {
            Object key = entrySet.getKey();
            Object value = entrySet.getValue();

            pstmt = conn.prepareStatement(
                    "INSERT INTO item_keys " + "SET CellItemID = ?, " + "ItemKey = ?, " + "Answer = ? ");
            pstmt.setInt(1, cellItemId);
            pstmt.setString(2, key.toString());
            pstmt.setString(3, value.toString());
            pstmt.executeUpdate();

            int itemKeyId = 0;
            stmt = conn.createStatement();
            rs = stmt.executeQuery("SELECT last_insert_id() AS id FROM item_keys ");
            while (rs.next()) {
                itemKeyId = CommonUtilities.convertStringToInt(rs.getString("id"));
            }

            pstmt = conn.prepareStatement("INSERT INTO key_log SET " + "ItemKeyID = ?, " + "UserID = ?, "
                    + "Remarks = ?, " + "DateRemarked = now(), " + "ActionDone = ? ");
            pstmt.setInt(1, itemKeyId);
            pstmt.setInt(2, CommonUtilities
                    .convertStringToInt(VaadinSession.getCurrent().getAttribute("userId").toString()));
            pstmt.setString(3, "insert new item key");
            pstmt.setString(4, "insert");
            pstmt.executeUpdate();
        }

        pstmt = conn.prepareStatement("INSERT INTO item_log SET " + "CellItemID = ?, " + "UserID = ?, "
                + "Remarks = ?, " + "DateRemarked = now(), " + "ActionDone = ? ");
        pstmt.setInt(1, cellItemId);
        pstmt.setInt(2, CommonUtilities
                .convertStringToInt(VaadinSession.getCurrent().getAttribute("userId").toString()));
        pstmt.setString(3, "insert new item");
        pstmt.setString(4, "insert");
        pstmt.executeUpdate();

        conn.commit();

        conn.setAutoCommit(true);
        pstmt = conn.prepareStatement("INSERT INTO notifications SET " + "UserID = ?, " + "SenderID = ?, "
                + "Notice = ?, " + "Remarks = ?, " + "NoteDate = now() ");
        pstmt.setInt(1, TeamTeachDAO.getTeamLeaderIdByCurriculumId(SyllabusDAO
                .getCurriculumIdBySyllabusId(CellCaseDAO.getSyllabusIdByCellCaseId(ci.getCellCaseId()))));
        pstmt.setInt(2, ci.getUserId());
        pstmt.setString(3, "CellItemID #" + cellItemId);
        pstmt.setString(4, EtestNotificationConstants.NEW_ITEM_NOTIFICATION);
        pstmt.executeUpdate();

        pstmt = conn.prepareStatement(
                "INSERT INTO system_logs SET " + "UserID = ?, " + "EntryDateTime = now(), " + "Activity = ? ");
        pstmt.setInt(1, ci.getUserId());
        pstmt.setString(2, "Created new cell item with CellItemID #" + cellItemId);
        pstmt.executeUpdate();

        result = true;
    } catch (SQLException ex) {
        try {
            conn.rollback();
        } catch (SQLException ex1) {
            ErrorDBNotification.showLoggedErrorOnWindow(ex1.toString());
            Logger.getLogger(CellItemDAO.class.getName()).log(Level.SEVERE, null, ex1);
        }
        ErrorDBNotification.showLoggedErrorOnWindow(ex.toString());
        Logger.getLogger(CellItemDAO.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            pstmt.close();
            conn.close();
        } catch (SQLException ex) {
            ErrorDBNotification.showLoggedErrorOnWindow(ex.toString());
            Logger.getLogger(CellItemDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    return result;
}

From source file:com.etest.dao.CellItemDAO.java

public static boolean modifyCellItem(CellItem ci) {
    Connection conn = DBConnection.connectToDB();
    PreparedStatement pstmt = null;
    boolean result = false;

    try {//from   w  w  w .j  av a2s . co  m
        conn.setAutoCommit(false);
        pstmt = conn.prepareStatement(
                "UPDATE cell_items SET " + "BloomsClassID = ?, " + "Item = ? " + "WHERE CellItemID = ? ");
        pstmt.setInt(1, ci.getBloomsClassId());
        pstmt.setString(2, ci.getItem());
        pstmt.setInt(3, ci.getCellItemId());
        pstmt.executeUpdate();

        pstmt = conn.prepareStatement("INSERT INTO item_log SET " + "CellItemID = ?, " + "UserID = ?, "
                + "Remarks = ?, " + "DateRemarked = now(), " + "ActionDone = ? ");
        pstmt.setInt(1, ci.getCellItemId());
        pstmt.setInt(2, CommonUtilities
                .convertStringToInt(VaadinSession.getCurrent().getAttribute("userId").toString()));
        pstmt.setString(3, ci.getRemarks());
        pstmt.setString(4, ci.getActionDone());
        pstmt.executeUpdate();

        pstmt = conn.prepareStatement(
                "INSERT INTO system_logs SET " + "UserID = ?, " + "EntryDateTime = now(), " + "Activity = ? ");
        pstmt.setInt(1, CommonUtilities
                .convertStringToInt(VaadinSession.getCurrent().getAttribute("userId").toString()));
        pstmt.setString(2, "Modify cell item with CellItemID #" + ci.getCellItemId());
        pstmt.executeUpdate();

        conn.commit();
        result = true;
    } catch (SQLException ex) {
        try {
            conn.rollback();
        } catch (SQLException ex1) {
            ErrorDBNotification.showLoggedErrorOnWindow(ex1.toString());
            Logger.getLogger(CellItemDAO.class.getName()).log(Level.SEVERE, null, ex1);
        }
        ErrorDBNotification.showLoggedErrorOnWindow(ex.toString());
        Logger.getLogger(CellItemDAO.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            pstmt.close();
            conn.close();
        } catch (SQLException ex) {
            ErrorDBNotification.showLoggedErrorOnWindow(ex.toString());
            Logger.getLogger(CellItemDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    return result;
}