finale.year.stage.main.Authentification.java Source code

Java tutorial

Introduction

Here is the source code for finale.year.stage.main.Authentification.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package finale.year.stage.main;

import java.awt.*;
import java.awt.event.*;
import javax.swing.border.*;
import finale.year.stage.agent.AgentScolarite;
import org.json.*;
import finale.year.stage.responsable.ResponsableInterface;
import finale.year.stage.utility.Util;
import java.awt.Color;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;

/**
 *
 * @author philipchicco
 */
public class Authentification extends javax.swing.JPanel {

    /**
     * Creates new form Authentification
     */
    public Authentification() {

        initComponents();
        Util.CHECK = false;
    }

    public Authentification(boolean b) {
        ///Login Automatically if credentials Present
        Util.CHECK = b;
        startL();
    }

    /**
     * These are accessors for the components
     * Thats buttons, fields and so forth.
     * @return 
     */
    public final void startL() {
        new LoginThread("", new char[0]).start();
    }

    public JButton get_forgotBtn() {
        return forgotBtn;
    }

    public JButton get_logInBtn() {
        return logInBtn;
    }

    public JButton get_signUpBtn() {
        return signUpBtn;
    }

    public JPanel get_innerPanel() {
        return innerPanel;
    }

    public JPasswordField get_passWord() {
        return passWord;
    }

    public JCheckBox get_rememberMe() {
        return rememberMe;
    }

    public JTextField get_userName() {
        return emailField;
    }

    public JLabel statusBar() {
        return errorStatusBar;
    }

    public forgotLogin getforgotFrame() {
        return new forgotLogin();
    }

    public static ResponsableInterface getResponsableWindow(JSONObject user) {
        return new ResponsableInterface(user);
    }

    public static ResponsableInterface getResponsableWindow() {
        return new ResponsableInterface();
    }

    /**
     *
     * @param message
     */
    public static void updateStatus(final String message) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                try {
                    errorStatusBar.setText("");
                    errorStatusBar.setForeground(Color.red);
                    errorStatusBar.setText(message);
                } catch (NullPointerException e) {
                    return;
                }
            }

        });

    }

    /**
     * @LoginThread handles the Login Process of a user.
     */
    private class LoginThread extends Thread {

        private char[] passwordEncrypted;
        private String email;
        private String password;

        public LoginThread(String email, char[] password) {
            this.email = email;
            this.passwordEncrypted = password;
        }

        @Override
        public void run() {
            //Verify is user wants to be remembered
            if (Util.CHECK == true) {

                // 1. User has Entered Email and Password, He may be a first User
                // 2. Verify Email entered by the User
                if (Util.validateEmail(email)) {
                    //Check for password Validity
                    if (passwordEncrypted.equals("") || passwordEncrypted == null) {
                        Authentification.updateStatus("Password(s) Empty ! ");
                        //return;
                    }
                    //Check Password Length
                    if (passwordEncrypted.length != 8) {
                        Authentification.updateStatus("Password(s) Invalid! 8 Character(s) Only! ");
                        //return;
                    }
                    //Get password as a String
                    StringBuilder bd = new StringBuilder();
                    for (char ch : passwordEncrypted) {
                        bd.append(String.format("%s", ch));
                    }
                    password = bd.toString();

                    //Send Request to Utility Class
                    //if(Util.CHECK ==false) //Normal Login
                    //Authentification.handleResponse(Util.login(email, password));
                    //else //Login with config txt
                    Util.rememberLogin(email, password);

                } else {
                    // 2. Email is empty and Invalid ( assuming its empty )
                    // 3. User already has credentials stored on System
                    // 4. Call rememberLogin withouut paramters

                    //if(password == null || password.equals(""))
                    Util.rememberLogin();
                    //else
                    //Authentification.updateStatus("Password must be Empty : Remember Me is Checked");  

                }

            } else {
                // End of User Check 
                // User wants a normal Login

                // 1. User has Entered Email and Password, He wishes normal login
                // 2. Verify Email entered by the User
                if (Util.validateEmail(email)) {
                    //Check for password Validity
                    if (passwordEncrypted.equals("") || passwordEncrypted == null) {
                        Authentification.updateStatus("Password(s) Empty ! ");
                        return;
                    }
                    //Check Password Length
                    if (passwordEncrypted.length != 8) {
                        Authentification.updateStatus("Password(s) Invalid! 8 Character(s) Only! ");
                        return;
                    }
                    //Get password as a String
                    StringBuilder bd = new StringBuilder();
                    for (char ch : passwordEncrypted) {
                        bd.append(String.format("%s", ch));
                    }
                    password = bd.toString();

                    //Send Request to Utility Class
                    Authentification.handleResponse(Util.login(email, password));

                } else {
                    Authentification.updateStatus("Invalid Email");
                }

            } // End of enite If Block

        }//End of Run

    }//End of Thread

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    // Generated using JFormDesigner Evaluation license - unknown
    private void initComponents() {
        innerPanel = new JPanel();
        emailField = new JTextField();
        rememberMe = new JCheckBox();
        logInBtn = new JButton();
        passWord = new JPasswordField();
        signUpBtn = new JButton();
        forgotBtn = new JButton();
        userIcon = new JLabel();
        passwordIcon = new JLabel();
        errorStatusBar = new JLabel();

        //======== this ========

        // JFormDesigner evaluation mark
        setBorder(
                new javax.swing.border.CompoundBorder(
                        new javax.swing.border.TitledBorder(new javax.swing.border.EmptyBorder(0, 0, 0, 0),
                                "JFormDesigner Evaluation", javax.swing.border.TitledBorder.CENTER,
                                javax.swing.border.TitledBorder.BOTTOM,
                                new java.awt.Font("Dialog", java.awt.Font.BOLD, 12), java.awt.Color.red),
                        getBorder()));
        addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent e) {
                if ("border".equals(e.getPropertyName()))
                    throw new RuntimeException();
            }
        });

        setLayout(new GridBagLayout());

        //======== innerPanel ========
        {
            innerPanel.setBorder(new EtchedBorder());

            //---- emailField ----
            emailField.setText("Email");
            emailField.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    emailFieldActionPerformed(e);
                }
            });

            //---- rememberMe ----
            rememberMe.setText("Remember me");
            rememberMe.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    rememberMeActionPerformed(e);
                }
            });

            //---- logInBtn ----
            logInBtn.setText("Log In");
            logInBtn.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    logInBtnActionPerformed(e);
                }
            });

            //---- passWord ----
            passWord.setText("password");

            //---- signUpBtn ----
            signUpBtn.setText("Sign Up");
            signUpBtn.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    signUpBtnActionPerformed(e);
                }
            });

            //---- forgotBtn ----
            forgotBtn.setText("Forgot Password?");
            forgotBtn.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    forgotBtnActionPerformed(e);
                }
            });

            //---- userIcon ----
            userIcon.setIcon(new ImageIcon(getClass().getResource("/Resources/glyphicons_user.png")));

            //---- passwordIcon ----
            passwordIcon.setIcon(new ImageIcon(getClass().getResource("/Resources/glyphicons_lock.png")));

            GroupLayout innerPanelLayout = new GroupLayout(innerPanel);
            innerPanel.setLayout(innerPanelLayout);
            innerPanelLayout.setHorizontalGroup(innerPanelLayout.createParallelGroup().addGroup(innerPanelLayout
                    .createSequentialGroup()
                    .addGroup(innerPanelLayout.createParallelGroup()
                            .addGroup(innerPanelLayout.createSequentialGroup().addGap(106, 106, 106)
                                    .addComponent(forgotBtn))
                            .addGroup(innerPanelLayout.createSequentialGroup().addGap(73, 73, 73)
                                    .addGroup(innerPanelLayout.createParallelGroup(GroupLayout.Alignment.TRAILING)
                                            .addComponent(userIcon, GroupLayout.PREFERRED_SIZE, 45,
                                                    GroupLayout.PREFERRED_SIZE)
                                            .addComponent(passwordIcon, GroupLayout.PREFERRED_SIZE, 45,
                                                    GroupLayout.PREFERRED_SIZE))
                                    .addGap(18, 18, 18)
                                    .addGroup(innerPanelLayout
                                            .createParallelGroup(GroupLayout.Alignment.TRAILING, false)
                                            .addComponent(passWord).addComponent(emailField,
                                                    GroupLayout.DEFAULT_SIZE, 318, Short.MAX_VALUE)))
                            .addGroup(innerPanelLayout.createParallelGroup(GroupLayout.Alignment.TRAILING, false)
                                    .addGroup(innerPanelLayout.createSequentialGroup().addGap(106, 106, 106)
                                            .addComponent(rememberMe)
                                            .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED,
                                                    GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                            .addComponent(logInBtn, GroupLayout.PREFERRED_SIZE, 79,
                                                    GroupLayout.PREFERRED_SIZE))
                                    .addGroup(innerPanelLayout.createSequentialGroup().addGap(375, 375, 375)
                                            .addComponent(signUpBtn, GroupLayout.PREFERRED_SIZE, 79,
                                                    GroupLayout.PREFERRED_SIZE)))
                            .addGroup(innerPanelLayout.createSequentialGroup().addGap(218, 218, 218)
                                    .addComponent(errorStatusBar)))
                    .addContainerGap(100, Short.MAX_VALUE)));
            innerPanelLayout.setVerticalGroup(innerPanelLayout.createParallelGroup().addGroup(innerPanelLayout
                    .createSequentialGroup().addContainerGap().addComponent(errorStatusBar).addGap(30, 30, 30)
                    .addGroup(innerPanelLayout.createParallelGroup()
                            .addComponent(userIcon, GroupLayout.PREFERRED_SIZE, 42, GroupLayout.PREFERRED_SIZE)
                            .addComponent(emailField, GroupLayout.PREFERRED_SIZE, 42, GroupLayout.PREFERRED_SIZE))
                    .addGap(30, 30, 30)
                    .addGroup(innerPanelLayout.createParallelGroup()
                            .addComponent(passwordIcon, GroupLayout.PREFERRED_SIZE, 38, GroupLayout.PREFERRED_SIZE)
                            .addComponent(passWord, GroupLayout.PREFERRED_SIZE, 38, GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(
                            innerPanelLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                                    .addComponent(rememberMe, GroupLayout.PREFERRED_SIZE, 59,
                                            GroupLayout.PREFERRED_SIZE)
                                    .addComponent(logInBtn))
                    .addGap(6, 6, 6).addComponent(forgotBtn).addGap(6, 6, 6).addComponent(signUpBtn)
                    .addContainerGap(69, Short.MAX_VALUE)));
        }
        add(innerPanel, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.NORTHWEST,
                GridBagConstraints.NONE, new Insets(0, 0, 0, 0), -20, 4));
    }// </editor-fold>//GEN-END:initComponents

    private void emailFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_emailFieldActionPerformed
        // TODO add your handling code here:
        //Do nothing
    }//GEN-LAST:event_emailFieldActionPerformed

    private void logInBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_logInBtnActionPerformed
        // TODO add your handling code here:

        String email = emailField.getText();
        char[] password = passWord.getPassword();

        new LoginThread(email, password).start();

    }//GEN-LAST:event_logInBtnActionPerformed

    private void signUpBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_signUpBtnActionPerformed
        // TODO add your handling code here:
        mainF.mainFrame.dispose();
        Inscription inscibe = new Inscription();
        mainFrame = new mainF();
        mainFrame.launchFrame(inscibe, mainFrame);
    }//GEN-LAST:event_signUpBtnActionPerformed

    private void forgotBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_forgotBtnActionPerformed
        // In event of forgotten password ; open new frame
        forgotlogin = getforgotFrame();
        mainF.mainFrame.dispose();
        mainFrame = new mainF();
        mainFrame.launchFrame(forgotlogin, mainFrame);

    }//GEN-LAST:event_forgotBtnActionPerformed

    private void rememberMeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rememberMeActionPerformed
        // TODO add your handling code here:
        if (get_rememberMe().isSelected()) {
            Util.CHECK = true;
            //new LoginThread("",new char[0]).start();
        } else {
            Util.CHECK = false;

        }
    }//GEN-LAST:event_rememberMeActionPerformed

    public static void handleResponse(JSONObject serverRes) {
        //Handle Server Response here : Open particular user
        JSONObject user = null;
        int code = -1;
        String responseMessage = null;
        int type = -1;

        if (serverRes == null) {
            Authentification.updateStatus(" Server Unresponsive! Null Exception ");
        } else {
            try {

                code = serverRes.getInt("response code");
                responseMessage = serverRes.getString("response message");
            } catch (JSONException ex) {
                Authentification.updateStatus("Response Handle Error " + ex.getMessage().trim());
            }

        }

        if (code == 1) {
            try {
                user = serverRes.getJSONObject("user");
                type = user.getInt("type");
            } catch (JSONException ex) {
                ex.printStackTrace();
            }
            switch (type) {
            case TYPE_4: //Responsable

                mainF.mainFrame.dispose();
                respInterface = getResponsableWindow(user);
                mainFrame = new mainF();
                mainFrame.launchFrame(respInterface, mainFrame);
                break;

            case TYPE_3: //Agnet de la Scolarite
                mainF.mainFrame.dispose();
                AgentScolarite.main(user);
                break;
            default:
                Authentification.updateStatus(" Unauthrized User /n Contact Administrator ");
                break;

            }
            //
        } else {
            //If Server Status is not Ok : get ServerResoponse Message 
            Authentification.updateStatus(responseMessage);
        }

    }

    //User Object 
    public static JSONObject USER = null;

    //These are user types (Responsable,Etudiant, Tutuer, Agent, Enseignant )
    private final static int TYPE_0 = 0; //Student
    private final static int TYPE_1 = 1; //Tutor
    private final static int TYPE_2 = 2; //Enseignant
    private final static int TYPE_3 = 3; //Agent
    private final static int TYPE_4 = 4; //Responsable
    //
    private static ResponsableInterface respInterface = null;
    private final static int CODE = 1;
    //
    private static mainF mainFrame = null;
    private forgotLogin forgotlogin = null;
    private boolean access = false;
    // Variables declaration - do not modify//GEN-BEGIN:variables
    // Generated using JFormDesigner Evaluation license - unknown
    private JPanel innerPanel;
    private JTextField emailField;
    private JCheckBox rememberMe;
    private JButton logInBtn;
    private JPasswordField passWord;
    private JButton signUpBtn;
    private JButton forgotBtn;
    private JLabel userIcon;
    private JLabel passwordIcon;
    private static JLabel errorStatusBar;
    // End of variables declaration//GEN-END:variables
}