ca.qc.cegepoutaouais.tge.pige.client.ui.dialog.LoginDialog.java Source code

Java tutorial

Introduction

Here is the source code for ca.qc.cegepoutaouais.tge.pige.client.ui.dialog.LoginDialog.java

Source

/*
 * Copyright 2010, 2011 Renaud Brub
 *
 * This file is part of PIGE.
 *
 * PIGE is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * PIGE is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with PIGE.  If not, see <http://www.gnu.org/licenses/>.
 */
package ca.qc.cegepoutaouais.tge.pige.client.ui.dialog;

import ca.qc.cegepoutaouais.tge.pige.client.ui.AppEvents;
import ca.qc.cegepoutaouais.tge.pige.client.GenericUtil;
import ca.qc.cegepoutaouais.tge.pige.client.PigeMessages;
import ca.qc.cegepoutaouais.tge.pige.client.SessionObject;
import ca.qc.cegepoutaouais.tge.pige.client.services.LoginServiceAsync;
import ca.qc.cegepoutaouais.tge.pige.client.services.exceptions.LoginErrorException;
import ca.qc.cegepoutaouais.tge.pige.client.PIGE;
import ca.qc.cegepoutaouais.tge.pige.client.resources.Resources;
import ca.qc.cegepoutaouais.tge.pige.client.services.ManagementServiceAsync;
import ca.qc.cegepoutaouais.tge.pige.dao.pojos.Version;
import com.extjs.gxt.ui.client.Registry;
import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.event.BaseEvent;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.ComponentEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.KeyListener;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.mvc.Dispatcher;
import com.extjs.gxt.ui.client.util.IconHelper;
import com.extjs.gxt.ui.client.widget.Dialog;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.layout.FormLayout;
import com.extjs.gxt.ui.client.widget.toolbar.FillToolItem;
import com.extjs.gxt.ui.client.widget.Html;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.AbstractImagePrototype;
import java.util.Date;

/**
 * Bote de dialogue pour permettre aux usagers de s'authentifier au serveur.
 *
 * @author Renaud Brub
 */
public class LoginDialog extends Dialog {

    public final PigeMessages messages = PIGE.messages;
    private TextField<String> identifierTF = null;
    private TextField<String> passwordTF = null;
    private Button loginBtn = null;

    public LoginDialog() {

        FormLayout layout = new FormLayout();
        layout.setLabelWidth(100);
        layout.setDefaultWidth(175);
        setLayout(layout);

        setButtonAlign(HorizontalAlignment.LEFT);
        setButtons("");
        setIcon(IconHelper.createStyle("user"));
        setHeadingHtml(messages.loginWelcomeMessage());
        setModal(true);
        setBodyBorder(true);
        setDraggable(false);
        setBodyStyle("padding: 8px;background: none");
        setWidth(330);
        setResizable(false);
        setClosable(false);

        KeyListener keyListener = new KeyListener() {

            @Override
            public void componentKeyUp(ComponentEvent event) {
                validate();
                if (event.getKeyCode() == KeyCodes.KEY_ENTER) {
                    onSubmit();
                }
            }

        };

        identifierTF = new TextField<String>();
        identifierTF.setMinLength(4);
        identifierTF.setFieldLabel(messages.identifier());
        identifierTF.addKeyListener(keyListener);
        add(identifierTF);

        passwordTF = new TextField<String>();
        passwordTF.setRegex(GenericUtil.PASSWORD_REGEX);
        passwordTF.getMessages().setRegexText(messages.passwordFormatIsIncorrect());
        passwordTF.setPassword(true);
        passwordTF.setFieldLabel(messages.password());
        passwordTF.addKeyListener(keyListener);
        add(passwordTF);

        setFocusWidget(identifierTF);

        ManagementServiceAsync rpcService = Registry.get(PIGE.MANAGEMENT_SERVICE);
        rpcService.getVersion(new AsyncCallback<Version>() {

            @Override
            public void onSuccess(Version version) {
                setHeadingHtml(getHeadingHtml() + "<br/><span style='color: #15428B; font-style: italic;'>- "
                        + messages.version() + " " + version.getShortVersion() + "</span>");
            }

            @Override
            public void onFailure(Throwable caught) {
                PIGE.handleException(caught);
            }
        });

    }

    @Override
    protected void createButtons() {
        super.createButtons();

        Html forgotPasswordLT = new Html(
                "<span id=\"login-dialog-forgot-password-link\">" + messages.forgotPassword() + "</span>");
        getButtonBar().add(forgotPasswordLT);

        forgotPasswordLT.addListener(Events.OnClick, new Listener<BaseEvent>() {

            @Override
            public void handleEvent(BaseEvent event) {
                new ForgotPasswordDialog().show();
            }

        });

        getButtonBar().add(new FillToolItem());

        loginBtn = new Button(messages.connect());
        loginBtn.setIcon(AbstractImagePrototype.create(Resources.INSTANCE.loginIcon()));
        loginBtn.disable();
        loginBtn.addSelectionListener(new SelectionListener<ButtonEvent>() {

            @Override
            public void componentSelected(ButtonEvent ce) {
                onSubmit();
            }
        });

        addButton(loginBtn);
    }

    private boolean hasValue(TextField<String> field) {
        return field.getValue() != null && field.getValue().length() > 0;
    }

    private void validate() {
        boolean isValid = hasValue(identifierTF) && hasValue(passwordTF) && passwordTF.validate();
        loginBtn.setEnabled(isValid);
        setLoginEnabled(isValid);
    }

    /** Indique qu'une demande d'authentification peut tre excute. */
    private boolean loginEnabled = true;

    /**
     * Permet d'autoriser ou d'interdir l'excution d'une demande
     * d'authentification.
     *
     * @param b vrai pour autoriser, faux sinon.
     */
    private void setLoginEnabled(boolean b) {
        loginEnabled = b;
        loginBtn.setEnabled(b);
    }

    private boolean isLoginEnabled() {
        return loginEnabled;
    }

    private void onSubmit() {

        if (!isLoginEnabled()) {
            return;
        }

        // Interdir l'excution de nouvelle demande d'authentification pendant
        // qu'une autre est en train de se faire.
        setLoginEnabled(false);

        LoginServiceAsync rpcService = Registry.get(PIGE.LOGIN_SERVICE);

        // Envoyer la demande d'authentification au serveur.
        rpcService.logIn(identifierTF.getValue(), passwordTF.getValue(), new AsyncCallback<SessionObject>() {

            @Override
            public void onSuccess(SessionObject session) {

                // La demande d'authentification a russie!

                hide();

                // Crer le cookie de session qui va permettre  l'usager
                // d'accder ultrieurement  PIGE sans devoir
                // s'authentifier de nouveau. La dure de vie du cookie
                // est dtermin par le serveur.
                Cookies.setCookie(PIGE.SESSION_COOKIE, session.getId(),
                        new Date(System.currentTimeMillis() + session.getLifespan()));
                Registry.register(PIGE.SESSION_COOKIE, session.getId());
                Registry.register(PIGE.USER_IDENTIFIER, identifierTF.getValue());

                identifierTF.clear();
                passwordTF.clear();

                // Gnrer l'vnement permettant d'afficher la vue
                // principale.
                Dispatcher.get().dispatch(AppEvents.INIT_EVENT);

            } // onSuccess()

            @Override
            public void onFailure(Throwable caught) {

                // En cas d'chec, afficher le message d'erreur
                // indiquant la cause.

                passwordTF.clear();
                setLoginEnabled(true);

                String errMsg = caught.getMessage();
                if (caught instanceof LoginErrorException) {
                    String errType = ((LoginErrorException) caught).getErrorType();
                    if (errType.equals(LoginErrorException.ERROR_INVALID_IDENTIFIER_PASSWORD)) {
                        errMsg = messages.invalidIdentifierOrPassword();
                    } else if (errType.equals(LoginErrorException.ERROR_ACCOUNT_INACTIVE)) {
                        errMsg = messages.accountInactive();
                    } else if (errType.equals(LoginErrorException.ERROR_ACCOUNT_LOCKED)) {
                        errMsg = messages.accountLocked();
                    }
                    MessageBox.alert(messages.error(), errMsg, null).setIcon(MessageBox.ERROR);
                } else {
                    PIGE.handleException(caught);
                }

            }

        }); // logIn()

    }
}