Example usage for com.google.gwt.user.client Cookies setCookie

List of usage examples for com.google.gwt.user.client Cookies setCookie

Introduction

In this page you can find the example usage for com.google.gwt.user.client Cookies setCookie.

Prototype

public static void setCookie(String name, String value, Date expires) 

Source Link

Document

Sets a cookie.

Usage

From source file:eml.studio.client.ui.panel.LoginPanel.java

License:Open Source License

public LoginPanel() {
    this.setStyleName("bda-login");
    boolean checked = Boolean.parseBoolean(Cookies.getCookie("bdachecked"));
    checkBox.setValue(checked);/*from w  w  w  .  ja  v a  2  s  .c  o m*/

    Label emailLabel = new Label(Constants.logUIMsg.email());
    emailField.setStyleName("form-control");
    emailField.setValue(Cookies.getCookie("bdaemail"));
    Label passwordLabel = new Label(Constants.logUIMsg.password());
    passwordField.setStyleName("form-control");
    if (checked)
        passwordField.setValue(UUID.randomID());

    errorLabel.addStyleName("bad-login-error");

    checkBox.setStyleName("bda-login-checkbox");
    forgetLabel.setStyleName("bda-login-forgetpwd");
    pwdPanel.setStyleName("bda-form-group");
    pwdPanel.add(checkBox);
    pwdPanel.add(forgetLabel);

    signinButton.addStyleName("button-style");
    signinButton.getElement().getStyle().setMarginLeft(7, Unit.PX);
    signinButton.getElement().getStyle().setMarginRight(60, Unit.PX);
    signupButton.addStyleName("button-style");
    btnPanel.setStyleName("bda-form-group");
    btnPanel.add(signinButton);
    btnPanel.add(signupButton);

    HorizontalPanel hp = new HorizontalPanel();
    hp.add(emailLabel);
    hp.add(guestLabel);
    guestLabel.getElement().getStyle().setWidth(100, Unit.PX);
    guestLabel.getElement().getStyle().setTextAlign(TextAlign.RIGHT);
    guestLabel.getElement().getStyle().setMarginLeft(80, Unit.PX);
    guestLabel.getElement().getStyle().setCursor(Cursor.POINTER);
    loginContainer.add(hp);
    loginContainer.add(emailField);
    loginContainer.add(passwordLabel);
    loginContainer.add(passwordField);
    loginContainer.add(errorLabel);
    loginContainer.add(pwdPanel);
    loginContainer.add(btnPanel);

    loginContainer.setStyleName("bda-login-form");
    loginContainer.setBorderWidth(0);
    loginContainer.setStyleName((String) null);

    this.add(loginContainer);

    passwordField.addChangeHandler(new ChangeHandler() {

        @Override
        public void onChange(ChangeEvent event) {
            autoLogin = false;
        }

    });

    checkBox.addValueChangeHandler(new ValueChangeHandler() {

        @Override
        public void onValueChange(ValueChangeEvent event) {
            // Window.alert( checkBox.getValue().toString() );
            Cookies.setCookie("bdachecked", checkBox.getValue().toString(), Util.getCookieExpireDate());
            if (!getRemmenber()) {
                Cookies.removeCookie("bdaserial");
                Cookies.removeCookie("bdatoken");
            }
        }

    });
}

From source file:fr.fg.client.core.Client.java

License:Open Source License

public void onSuccess(AnswerData data) {
    StateData state = data.getState();//ww  w . ja va 2 s  .c o m

    switch (state.getState()) {
    case StateData.STATE_OFFLINE:
        // Joueur dconnect
        LoginDialog dialog = getLoginDialog();

        // Liste des serveurs
        ArrayList<ServerData> servers = new ArrayList<ServerData>();
        for (int i = 0; i < state.getServersCount(); i++)
            servers.add(state.getServerAt(i));
        dialog.setServers(servers, state.getCurrentServerIndex());

        DynamicMessages messages = (DynamicMessages) GWT.create(DynamicMessages.class);

        StaticMessages staticMessages = (StaticMessages) GWT.create(StaticMessages.class);

        // Astuce du jour
        tipOfTheDay.getElement().setInnerHTML(
                "<div class=\"icon\"></div>" + messages.getString("tip" + (int) (9 * Math.random())));

        String changelogHTML = "<div class=\"title\">Journal des modifications</div>";
        for (int i = 0; i < state.getChangelogsCount(); i++) {
            ChangelogData changelog = state.getChangelogAt(i);
            changelogHTML += "<div class=\"entry\">" + "<div class=\"date\">" + DateTimeFormat
                    .getFormat(staticMessages.dateTimeFormat()).format(new Date(1000l * changelog.getDate()))
                    + "</div>" + changelog.getText() + "</div>";
        }
        changelog.getElement().setInnerHTML(changelogHTML);
        changelogContainer.update();

        hideLoading();

        RootPanel.get().add(areaContainer);
        areaContainer.setNebula((int) (AreaContainer.NEBULAS_COUNT * Math.random()) + 1, true);
        dialog.setVisible(true);

        // Lien direct pour le parainage

        String currentUrl = Window.Location.getHref();
        int urlSearchIndex = currentUrl.indexOf("#par_:");

        if (urlSearchIndex != -1) {
            String urlSponsorName = currentUrl.substring(urlSearchIndex + 6, currentUrl.indexOf(":par"))
                    .replace("/", "");
            String oldSponsorName = urlSponsorName;

            do {
                oldSponsorName = urlSponsorName;
                urlSponsorName = urlSponsorName.replace("%20", " ");
            } while (oldSponsorName != urlSponsorName);

            dialog.activateSponsor(urlSponsorName);

            Window.Location.replace(currentUrl.substring(0, urlSearchIndex + 1));
        }

        RootPanel.get().add(tipOfTheDay);
        RootPanel.get().add(changelogContainer);
        RootPanel.get().add(logo);

        setServerShutdown(state.getServerShutdown());
        break;
    case StateData.STATE_ONLINE:
        // Sauvegarde le thme de l'utilisateur dans un cookie
        // (dure d'un an)
        Cookies.setCookie("theme", state.getOptions().getTheme(),
                new Date(1000l * Utilities.getCurrentTime() + 31536000000l));

        // Recharge la page si le thme de l'utilisateur ne correspond pas
        // au thme affich
        if (!Config.isDebug() && !state.getOptions().getTheme().equals(Config.getTheme())) {
            Window.Location.reload();
            return;
        }

        // Chargement des options
        Settings.setGridVisible(state.getOptions().isGridVisible());
        Settings.setBrightness(state.getOptions().getBrightness());
        Settings.setFleetsSkin(state.getOptions().getFleetsSkin());
        Settings.setPlayerId(state.getPlayerId());
        Settings.setPlayerLogin(state.getPlayerLogin());
        Settings.setSecurityKey(state.getSecurityKey());
        Settings.setPremium(state.isPremium());
        Settings.setRights(state.getRights());
        Settings.setEkey(state.getEkey());
        Settings.setTimeUnit(state.getTimeUnit());
        Settings.setCensorshipActive(state.getOptions().isCensorshipActive());
        Settings.setConnectionOptimized(state.getOptions().isConnectionOptimized());
        Settings.setFleetPrefix(state.getOptions().getFleetPrefix());
        Settings.setFleetSuffix(state.getOptions().getFleetSuffix());
        SoundManager.getInstance().setGeneralVolume(state.getOptions().getGeneralVolume());
        SoundManager.getInstance().setSoundVolume(state.getOptions().getSoundVolume());
        SoundManager.getInstance().setMusicVolume(state.getOptions().getMusicVolume());
        Config.setGraphicsQuality(state.getOptions().getGraphicsQuality());

        Cookies.setCookie("login", state.getPlayerLogin(),
                new Date(1000l * Utilities.getCurrentTime() + 31536000000l));

        // Initialise les diffrents composants de l'interface
        int miniMapSize = Window.getClientWidth() < 1024 ? 120 : 160;
        miniMap = new MiniMap(new Dimension(miniMapSize, miniMapSize), areaContainer.getMap());
        areaContainer.addMiniMap(miniMap);
        actionManager = new ActionManager(areaContainer);
        resourcesManager = new ResourcesManager();
        researchManager = new ResearchManager();
        productsManager = new ProductsManager();
        progressBar = new ProgressBar();
        chat = new Chat();
        empireControlPanel = new EmpireControlPanel();
        empireView = new EmpireView();
        namePanel = new NamePanel();
        selectionInfo = new SelectionInfo();
        toolBar = new ToolBar();
        missionPanel = new MissionPanel();
        allyDialog = new AllyDialog();
        lagometer = new Lagometer();
        tutorial = new Tutorial();
        advancementDialog = new AdvancementDialog();
        playerTacticsDialog = new PlayerTacticsDialog(researchManager);
        contractDialog = new ContractDialog();
        bugReportDialog = new BugReportDialog();
        codexDialog = new CodexDialog();

        if (Settings.isModerator()) {
            administrationPanelDialog = new AdministrationPanelDialog();
        }

        // Zik-mu
        String[] playlist = new String[Sounds.MUSICS.length];
        for (int i = 0; i < playlist.length; i++)
            playlist[i] = Sounds.MUSICS[i];

        for (int i = playlist.length; i > 1; i--) {
            int a = i - 1;
            int b = (int) (Math.random() * i);

            String tmp = playlist[a];
            playlist[a] = playlist[b];
            playlist[b] = tmp;
        }

        SoundManager.getInstance().setPlaylist(playlist);
        SoundManager.getInstance().playMusic(0);

        if (loginDialog.isVisible()) {
            loginDialog.setVisible(false);
            RootPanel.get().remove(tipOfTheDay);
            RootPanel.get().remove(changelogContainer);
            RootPanel.get().remove(logo);
        } else if (firstSystemDialog != null && firstSystemDialog.isVisible()) {
            firstSystemDialog.setVisible(false);
            firstSystemDialog = null;
        } else {
            hideLoading();
            RootPanel.get().add(areaContainer);
        }

        // Ajoute les composants de l'interface  la page
        RootPanel.get().add(miniMap);
        RootPanel.get().add(progressBar);
        RootPanel.get().add(chat);
        RootPanel.get().add(empireControlPanel);
        RootPanel.get().add(empireView);
        RootPanel.get().add(namePanel);
        RootPanel.get().add(toolBar);
        RootPanel.get().add(fullScreenPanel);
        RootPanel.get().add(selectionInfo);
        RootPanel.get().add(missionPanel);
        RootPanel.get().add(lagometer);

        // Initialisation des composants
        productsManager.addProductsListener(allyDialog);
        productsManager.setProducts(state.getProducts());
        allyDialog.setAlly(state.getAlly());
        areaContainer.setArea(new IndexedAreaData(state.getArea()),
                new Point(state.getViewX(), state.getViewY()));
        areaContainer.getMap().setGridVisible(Settings.isGridVisible());
        researchManager.setResearches(state.getResearch());

        Client.getInstance().getProgressBar()
                .setPlayerGeneratorsCount(state.getPlayerGenerators().getGeneratorsCount());

        ArrayList<PlayerStarSystemData> systems = new ArrayList<PlayerStarSystemData>();
        for (int i = 0; i < state.getPlayerSystems().getSystemsCount(); i++)
            systems.add(state.getPlayerSystems().getSystemAt(i));

        ArrayList<PlayerFleetData> fleets = new ArrayList<PlayerFleetData>();
        for (int i = 0; i < state.getPlayerFleets().getFleetsCount(); i++)
            fleets.add(state.getPlayerFleets().getFleetAt(i));

        ArrayList<PlayerGeneratorData> generators = new ArrayList<PlayerGeneratorData>();
        for (int i = 0; i < state.getPlayerGenerators().getGeneratorsCount(); i++)
            generators.add(state.getPlayerGenerators().getGeneratorAt(i));

        empireView.setData(systems, fleets, generators);
        resourcesManager.setSystems(systems);
        chat.addMessage("info", "", "", "Bienvenue sur Fallen Galaxy !", null, null, null, null, (Integer) null,
                (Integer) null);
        chat.addMessage("info", "", "",
                "Il y a actuellement " + state.getOnlinePlayers()
                        + (state.getOnlinePlayers() > 1 ? " joueurs connects." : " joueur connect.")
                        + (state.getLastConnection().length() > 0
                                ? " Dernire " + "connexion le " + state.getLastConnection() + "."
                                : ""),
                null, null, null, null, (Integer) null, (Integer) null);
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("type", "chat");
        new Action("messages/getmotd", params, UpdateManager.UPDATE_CALLBACK);
        missionPanel.setMissionStates(state.getContractsStates());
        contractDialog.setContracts(state.getPlayerContracts());
        progressBar.setPlayerData(state.getXp(), state.getColonizationPoints());
        chat.setChannels(state.getChatChannels());
        tutorial.setLessonDone((long) state.getTutorial());
        advancementDialog.setAdvancements(state.getAdvancements());
        playerTacticsDialog.setPlayerTactics(state.getTactics());

        if (state.getUnreadMessages() > 0)
            getMessenger().setUnreadMessages(state.getUnreadMessages());
        if (state.hasNewEvents())
            getEventsDialog().setNewEvents(state.hasNewEvents());

        if (state.getAlly().getId() != 0) {
            int unreadNews = 0;
            for (int i = 0; i < state.getAlly().getNewsCount(); i++) {
                AllyNewsData allyNews = state.getAlly().getNewsAt(i);

                if (!allyNews.isRead())
                    unreadNews++;
            }
            allyDialog.setUnreadNews(unreadNews);
        }

        EventManager.addEventHook(this);

        // Dmarre la gestion des mises  jour en temps rel
        UpdateManager.start();

        AwayManager.start();

        setServerShutdown(state.getServerShutdown());
        break;
    case StateData.STATE_ALREADY_ONLINE:
        // Joueur dj connect
        Settings.setSecurityKey(state.getSecurityKey());
        setStatus("Vous tes dj connect.");
        break;
    case StateData.STATE_NO_SYSTEM:
        Settings.setSecurityKey(state.getSecurityKey());

        if (loginDialog.isVisible()) {
            loginDialog.setVisible(false);
            RootPanel.get().remove(tipOfTheDay);
            RootPanel.get().remove(changelogContainer);
            RootPanel.get().remove(logo);
        } else {
            RootPanel.get().add(areaContainer);
            areaContainer.setNebula((int) (AreaContainer.NEBULAS_COUNT * Math.random() + 1), true);
        }

        firstSystemDialog = new FirstSystemDialog(this);
        firstSystemDialog.setVisible(true);

        setServerShutdown(state.getServerShutdown());
        break;
    }
}

From source file:fr.fg.client.core.EmpireControlPanel.java

License:Open Source License

public boolean onEventPreview(Event event) {
    switch (event.getTypeInt()) {
    case Event.ONKEYDOWN:
        Element target = DOM.eventGetTarget(event);

        int keyCode = event.getKeyCode();

        if ((currentAction != null && currentAction.isPending())
                || (target != null && DOM.getElementProperty(target, "nodeName").toLowerCase().equals("input"))) //$NON-NLS-1$ //$NON-NLS-2$
            return true;

        // combo de touche pour reset le theme CTRL/META/SHIFT + G
        if (keyCode == 71) {

            if (event.getCtrlKey() || event.getMetaKey() || event.getShiftKey()) {
                new Action("killpolling", Action.NO_PARAMETERS, new ActionCallback() {

                    public void onSuccess(AnswerData data) {

                        JSOptionPane.showMessageDialog("Voulez vous vraiment avoir le thme de base?",
                                "Confirmation", JSOptionPane.OK_OPTION | JSOptionPane.CANCEL_OPTION,
                                JSOptionPane.QUESTION_MESSAGE, new OptionPaneListener() {
                                    public void optionSelected(Object option) {
                                        if ((Integer) option == JSOptionPane.OK_OPTION) {
                                            Cookies.setCookie("theme",
                                                    Config.getMediaUrl() + "style/FallenCraft2Red", new Date(
                                                            1000l * Utilities.getCurrentTime() + 31536000000l));
                                            HashMap<String, String> params = new HashMap<String, String>();
                                            params.put("grid", String.valueOf(Settings.isGridVisible()));
                                            params.put("brightness", String.valueOf(Settings.getBrightness()));
                                            params.put("fleetsSkin", String.valueOf(Settings.getFleetsSkin()));
                                            params.put("generalvol", String
                                                    .valueOf(SoundManager.getInstance().getGeneralVolume()));
                                            params.put("musicvol", String
                                                    .valueOf(SoundManager.getInstance().getMusicVolume()));
                                            params.put("soundvol", String
                                                    .valueOf(SoundManager.getInstance().getSoundVolume()));
                                            params.put("graphics", String.valueOf(0));
                                            params.put("censorship",
                                                    String.valueOf(Settings.isCensorshipActive()));
                                            params.put("optimConnect",
                                                    String.valueOf(Settings.isConnectionOptimized()));

                                            params.put("theme", Config.getMediaUrl() + "style/FallenCraft2Red");

                                            currentAction = new Action("setsettings", params,
                                                    UpdateManager.UPDATE_CALLBACK);
                                            Window.Location.reload();

                                        }
                                    }//from  w  w  w .  jav a2 s.  c o m
                                });
                    }

                    public void onFailure(String error) {
                        ActionCallbackAdapter.onFailureDefaultBehavior(error);
                    }

                });
                event.preventDefault();
                event.cancelBubble(true);
            }

        } else if ((keyCode >= 48 && keyCode <= 57) || (keyCode >= 96 && keyCode <= 105)) {
            int shortcut = keyCode - (keyCode <= 57 ? 48 : 96);

            event.cancelBubble(true);
            event.preventDefault();

            if (event.getCtrlKey() || event.getMetaKey() || event.getShiftKey()) {
                // Affectation de raccourci
                PlayerFleetData[] fleetsData = getSelectedFleets();
                PlayerStarSystemData systemData = getSelectedSystem();
                StructureData structureData = getSelectedStructure();
                PlayerGeneratorData generatorData = null;

                if (structureData != null)
                    if (structureData.getType() == StructureData.TYPE_GENERATOR)
                        generatorData = Client.getInstance().getEmpireView()
                                .getGeneratorById(structureData.getId());

                if ((fleetsData == null || fleetsData.length != 1) && systemData == null
                        && generatorData == null)
                    return true;

                if (fleetsData != null && fleetsData.length == 1 && fleetsData[0].getShortcut() == shortcut)
                    shortcut = -1;
                if (systemData != null && systemData.getShortcut() == shortcut)
                    shortcut = -1;
                if (generatorData != null && generatorData.getShortcut() == shortcut)
                    shortcut = -1;

                HashMap<String, String> params = new HashMap<String, String>();
                params.put("shortcut", String.valueOf(shortcut));

                if (fleetsData != null && fleetsData.length == 1) {
                    params.put("id", String.valueOf(fleetsData[0].getId()));
                    params.put("type", "fleet");
                } else if (systemData != null) {
                    params.put("id", String.valueOf(systemData.getId()));
                    params.put("type", "system");
                } else if (generatorData != null) {
                    params.put("id", String.valueOf(generatorData.getId()));
                    params.put("type", "structure");
                }

                currentAction = new Action("setshortcut", params, UpdateManager.UPDATE_CALLBACK);
            } else {
                ArrayList<PlayerFleetData> fleets = Client.getInstance().getEmpireView().getFleets();

                for (PlayerFleetData fleet : fleets)
                    if (fleet.getShortcut() == shortcut) {
                        int idArea = Client.getInstance().getAreaContainer().getArea().getId();

                        Client.getInstance().getAreaContainer().setIdArea(fleet.getArea().getId(),
                                new Point(fleet.getX(), fleet.getY()));

                        if (idArea == fleet.getArea().getId())
                            SelectionManager.getInstance().selectFleet(fleet.getId());
                        return true;
                    }

                ArrayList<PlayerStarSystemData> systems = Client.getInstance().getEmpireView().getSystems();

                for (PlayerStarSystemData system : systems)
                    if (system.getShortcut() == shortcut) {
                        int idArea = Client.getInstance().getAreaContainer().getArea().getId();

                        Client.getInstance().getAreaContainer().setIdArea(system.getArea().getId(),
                                new Point(system.getX(), system.getY()));

                        if (idArea == system.getArea().getId())
                            SelectionManager.getInstance().selectSystem(system.getId());
                        return true;
                    }

                ArrayList<PlayerGeneratorData> generators = Client.getInstance().getEmpireView()
                        .getGenerators();

                for (PlayerGeneratorData generator : generators)
                    if (generator.getShortcut() == shortcut) {
                        int idArea = Client.getInstance().getAreaContainer().getArea().getId();

                        Client.getInstance().getAreaContainer().setIdArea(generator.getArea().getId(),
                                new Point(generator.getX(), generator.getY()));

                        if (idArea == generator.getArea().getId())
                            SelectionManager.getInstance().selectStructure(generator.getId());
                        return true;
                    }
            }
        }
        break;
    }

    return true;
}

From source file:fr.fg.client.core.settings.OptionsDialog.java

License:Open Source License

public void onSuccess(AnswerData data) {
    UpdateManager.UPDATE_CALLBACK.onSuccess(data);

    if (graphicsComboBox.getSelectedIndex() != Config.getGraphicsQuality() || (Settings.isPremium() && !Config
            .getTheme().equals(themeComboBox.getSelectedIndex() == OptionsData.THEMES.length ? customTheme
                    : OptionsData.THEMES[themeComboBox.getSelectedIndex()]))) {
        if (Settings.isPremium())
            // Sauvegarde le thme de l'utilisateur dans un cookie
            // (dure d'un an)
            Cookies.setCookie("theme",
                    themeComboBox.getSelectedIndex() == OptionsData.THEMES.length ? customTheme
                            : OptionsData.THEMES[themeComboBox.getSelectedIndex()],
                    new Date(1000l * Utilities.getCurrentTime() + 31536000000l));

        JSOptionPane.showMessageDialog(/*ww w .  j  av a 2 s.c o  m*/
                "Fallen Galaxy doit tre recharg "
                        + "pour pouvoir modifier les options graphiques. Voulez-vous "
                        + "rechargez le jeu immdiatement ?",
                "Avertissement", JSOptionPane.OK_OPTION | JSOptionPane.CANCEL_OPTION,
                JSOptionPane.QUESTION_MESSAGE, this);
    }
}

From source file:ibeans.client.IBeansConsole2.java

License:Open Source License

private void doSaveUser(UserInfo info) {
    Date now = new Date();
    now.setYear(now.getYear() + 1);/*  w ww  .j  ava2s . c  o  m*/
    Cookies.setCookie("ibeans-console", info.toString(), now);
    user = info;
    rightHeaderPanel.remove(0);
    rightHeaderPanel.add(createHeaderOptions());
}

From source file:net.autosauler.ballance.client.Ballance_autosauler_net.java

License:Apache License

/**
 * Logout sequence.//w ww.  jav  a 2s  . c o m
 */
public static void logoutSequence() {
    Ballance_autosauler_net.setLoggedInState(false);
    Ballance_autosauler_net.sessionId.reset();

    Cookies.setCookie("session", "", new Date(System.currentTimeMillis() + COOKIE_TIME));
    authPanel.logoffAction();
    MainPanel.dropMainPane();
    History.newItem("start");
}

From source file:net.autosauler.ballance.client.gui.AuthPanel.java

License:Apache License

/**
 * On ok button./*w w  w  .  j a va  2 s  .  co m*/
 */
private void onOkButton() {
    String login = loginText.getValue().trim();
    String password = passwordText.getValue().trim();
    if (!authPanel.isValid()) {
        return;
    }

    MainPanel.setCommInfo(true);
    Services.auth.chkAuth(login, password, new AsyncCallback<SessionId>() {

        @Override
        public void onFailure(Throwable caught) {
            MainPanel.setCommInfo(false);
            Info.display("Error", M.auth.commError());
            new AlertDialog(caught).show();
        }

        @Override
        public void onSuccess(SessionId result) {
            if (result != null) {
                Ballance_autosauler_net.setLoggedInState(true);

                Cookies.setCookie("session", result.getSessionId(),
                        new Date(System.currentTimeMillis() + Ballance_autosauler_net.COOKIE_TIME));
                Ballance_autosauler_net.sessionId.setSessionId(result.getSessionId());
                Ballance_autosauler_net.sessionId.setUsername(result.getUsername());
                Ballance_autosauler_net.sessionId.setUserrole(result.getUserrole());
                loginAction();

            } else {
                Ballance_autosauler_net.setLoggedInState(false);
                logoffAction();
                Info.display("Auth error", M.auth.badAuth());
            } // end else

            MainPanel.setCommInfo(false);
        }
    });

}

From source file:net.cbtltd.client.panel.SessionPopup.java

public void setValue(Session session) {
    Log.debug("setValue " + session);
    if (session == null || session.hasState(Session.LOGGED_OUT)) {
        AbstractField.addMessage(Level.ERROR, CONSTANTS.loginError(), emailaddressField);
        onReset(Session.LOGGED_OUT);//w ww  .  j a  v a2 s . c o  m
    } else if (session.hasState(Session.SUSPENDED)) {
        AbstractField.addMessage(Level.ERROR, CONSTANTS.suspendedError(), emailaddressField);
        onReset(Session.LOGGED_OUT);
    } else {
        onStateChange(session.getState());
        passwordField.clear();
        AbstractRoot.setSession(session);
        //         Window.alert("setValue " + session);
        Date expires = new Date(System.currentTimeMillis() + Time.WEEK.milliseconds());//duration remembering login = 7 days
        if (autologinField.getValue()) {
            Cookies.setCookie("sid", session.getId(), expires);
        } //, null, "/", false);
        //else {Cookies.removeCookie("sid");}
        if (session.hasPermission(AccessControl.ORGANIZATION_ROLES)) {
            AbstractRoot.render(Razor.WORKFLOW_TAB);
        } else {
            AbstractRoot.render(Razor.SEARCH_TAB);
        }
        hide();
    }
}

From source file:net.eve.finger.client.Net_eve_finger.java

License:Open Source License

/**
 * Handles the entire login process//from   ww w  .j  a va 2 s .  com
 */
private void showLoginForm() {
    // Login error dialog
    final Dialog loginError = new Dialog();
    loginError.setHeading("Login Failed!");
    loginError.addText("Username or password incorrect.");
    loginError.setBodyStyle("fontWeight:bold;padding:13px;");
    loginError.setSize(300, 100);
    loginError.setHideOnButtonClick(true);
    loginError.setClosable(false);
    loginError.setButtons(Dialog.OK);
    loginError.setModal(true);

    // Create the login window
    final WinLogin loginWindow = new WinLogin();

    // Set the callbacks
    loginWindow.setCallback(new LoginCallback() {
        @Override
        public void success(LoginResult result) {
            // Save the session ID
            sessionID = result.getSessionID();

            // Save the other data
            staticLoginData = result;

            // Save the username
            username = loginWindow.getUsername();

            // Calculate the expiration date of the cookies
            // (This class is deprecated for a reason...
            //  Google, implement the Calendar class...)
            Date expOn = new Date();
            expOn.setTime(expOn.getTime() + 3600000 * 24 * COOKIE_EXPIRE_DAYS);

            // Remember this user for later
            Cookies.setCookie(COOKIE_SESSION, sessionID, expOn);
            Cookies.setCookie(COOKIE_NAME, loginWindow.getUsername(), expOn);

            // Don't need the login window anymore                  
            desktop.removeWindow(loginWindow);
            loginWindow.hide();

            // Load the UI
            userAuthed();
        }

        @Override
        public void failure() {
            // Show an error 
            loginError.show();
        }
    });

    // Display the login window
    desktop.addWindow(loginWindow);
    loginWindow.show();
}

From source file:net.s17fabu.vip.gwt.showcase.client.content.other.CwCookies.java

License:Apache License

/**
 * Initialize this example./*  www. ja  v  a 2 s .  c  om*/
 */
@Override
public Widget onInitialize() {
    // Create the panel used to layout the content
    Grid mainLayout = new Grid(3, 3);

    // Display the existing cookies
    existingCookiesBox = new ListBox();
    Button deleteCookieButton = new Button(constants.cwCookiesDeleteCookie());
    deleteCookieButton.addStyleName("sc-FixedWidthButton");
    mainLayout.setHTML(0, 0, "<b>" + constants.cwCookiesExistingLabel() + "</b>");
    mainLayout.setWidget(0, 1, existingCookiesBox);
    mainLayout.setWidget(0, 2, deleteCookieButton);

    // Display the name of the cookie
    cookieNameBox = new TextBox();
    mainLayout.setHTML(1, 0, "<b>" + constants.cwCookiesNameLabel() + "</b>");
    mainLayout.setWidget(1, 1, cookieNameBox);

    // Display the name of the cookie
    cookieValueBox = new TextBox();
    Button setCookieButton = new Button(constants.cwCookiesSetCookie());
    setCookieButton.addStyleName("sc-FixedWidthButton");
    mainLayout.setHTML(2, 0, "<b>" + constants.cwCookiesValueLabel() + "</b>");
    mainLayout.setWidget(2, 1, cookieValueBox);
    mainLayout.setWidget(2, 2, setCookieButton);

    // Add a handler to set the cookie value
    setCookieButton.addClickHandler(new ClickHandler() {
        public void onClick(ClickEvent event) {
            String name = cookieNameBox.getText();
            String value = cookieValueBox.getText();
            Date expires = new Date((new Date()).getTime() + COOKIE_TIMEOUT);

            // Verify the name is valid
            if (name.length() < 1) {
                Window.alert(constants.cwCookiesInvalidCookie());
                return;
            }

            // Set the cookie value
            Cookies.setCookie(name, value, expires);
            refreshExistingCookies(name);
        }
    });

    // Add a handler to select an existing cookie
    existingCookiesBox.addChangeHandler(new ChangeHandler() {
        public void onChange(ChangeEvent event) {
            updateExstingCookie();
        }
    });

    // Add a handler to delete an existing cookie
    deleteCookieButton.addClickHandler(new ClickHandler() {
        public void onClick(ClickEvent event) {
            int selectedIndex = existingCookiesBox.getSelectedIndex();
            if (selectedIndex > -1 && selectedIndex < existingCookiesBox.getItemCount()) {
                String cookieName = existingCookiesBox.getValue(selectedIndex);
                Cookies.removeCookie(cookieName);
                existingCookiesBox.removeItem(selectedIndex);
                updateExstingCookie();
            }
        }
    });

    // Return the main layout
    refreshExistingCookies(null);
    return mainLayout;
}