dialog.DialogFunctionUser.java Source code

Java tutorial

Introduction

Here is the source code for dialog.DialogFunctionUser.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 dialog;

import Utils.PictureUtil;
import bean.User;
import common.Constant;
import controller.ControllerUser;
import java.awt.Frame;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.sql.Date;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import library.LibraryString;
import model.ModelUser;
import org.apache.commons.io.FilenameUtils;

/**
 *
 * @author GloomySunday
 */
public class DialogFunctionUser extends javax.swing.JDialog {

    private final int mType;
    private ControllerUser mControllerUser;
    private int mRow;
    private User mUser;
    private File mAvatar;

    public DialogFunctionUser(Frame owner, boolean modal) {
        super(owner, modal);
        initComponents();
        this.mType = Constant.TYPE_ADD;
    }

    private void actionAddUserNoController() {
        if (!isValidData()) {
            return;
        }
        if (isExistUsername(tfUsername.getText())) {
            JOptionPane.showMessageDialog(null, "Username  tn ti", "Error", JOptionPane.ERROR_MESSAGE);
            return;
        }
        String username = tfUsername.getText();
        String fullname = tfFullname.getText();
        String password = new String(tfPassword.getPassword());
        password = LibraryString.md5(password);
        int role = cbRole.getSelectedIndex();
        User objUser;
        if (mAvatar != null) {
            objUser = new User(UUID.randomUUID().toString(), username, password, fullname, role,
                    new Date(System.currentTimeMillis()), mAvatar.getPath());
            String fileName = FilenameUtils.getBaseName(mAvatar.getName()) + "-" + System.nanoTime() + "."
                    + FilenameUtils.getExtension(mAvatar.getName());
            Path source = Paths.get(mAvatar.toURI());
            Path destination = Paths.get("files/" + fileName);
            try {
                Files.copy(source, destination, StandardCopyOption.REPLACE_EXISTING);
            } catch (IOException ex) {
                Logger.getLogger(DialogFunctionRoom.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else {
            objUser = new User(UUID.randomUUID().toString(), username, password, fullname, role,
                    new Date(System.currentTimeMillis()), "");
        }
        if ((new ModelUser()).addItem(objUser)) {
            ImageIcon icon = new ImageIcon(getClass().getResource("/images/ic_success.png"));
            JOptionPane.showMessageDialog(this.getParent(), "Thm thnh cng", "Success",
                    JOptionPane.INFORMATION_MESSAGE, icon);
        } else {
            JOptionPane.showMessageDialog(this.getParent(), "Thm tht bi", "Fail",
                    JOptionPane.ERROR_MESSAGE);
        }
        this.dispose();
    }

    public DialogFunctionUser(Frame owner, boolean modal, User objUser) {
        super(owner, modal);
        initComponents();
        mType = Constant.TYPE_EDIT;
        mUser = objUser;
        tfUsername.setEditable(false);
        btnFunction.setText("Edit");
        btnFunction.setIcon(new ImageIcon(getClass().getResource("/images/ic_edit.png")));
        tfUsername.setText(objUser.getUsername());
        tfFullname.setText(objUser.getFullname());
        cbRole.setSelectedIndex(objUser.getRole());
        File file = new File(objUser.getAvatar());
        if (file.exists()) {
            PictureUtil.setPicture(lbAvatar, file);
        }
    }

    private void actionEditUserNoController() {
        if (!isValidData()) {
            return;
        }
        tfUsername.setEditable(false);
        String username = tfUsername.getText();
        String fullname = tfFullname.getText();
        String password = mUser.getPassword();
        if (tfPassword.getPassword().length == 0) {
            password = new String(tfPassword.getPassword());
            password = LibraryString.md5(password);
        }
        int role = cbRole.getSelectedIndex();
        User objUser;
        if (mAvatar != null) {
            objUser = new User(mUser.getIdUser(), username, password, fullname, role,
                    new Date(System.currentTimeMillis()), mAvatar.getPath());
            if ((new ModelUser()).editItem(objUser)) {
                String fileName = FilenameUtils.getBaseName(mAvatar.getName()) + "-" + System.nanoTime() + "."
                        + FilenameUtils.getExtension(mAvatar.getName());
                Path source = Paths.get(mAvatar.toURI());
                Path destination = Paths.get("files/" + fileName);
                Path pathOldAvatar = Paths.get(mUser.getAvatar());
                try {
                    Files.copy(source, destination, StandardCopyOption.REPLACE_EXISTING);
                    Files.deleteIfExists(pathOldAvatar);
                } catch (IOException ex) {
                    Logger.getLogger(DialogFunctionRoom.class.getName()).log(Level.SEVERE, null, ex);
                }
                ImageIcon icon = new ImageIcon(getClass().getResource("/images/ic_success.png"));
                JOptionPane.showMessageDialog(this.getParent(), "Sa thnh cng", "Success",
                        JOptionPane.INFORMATION_MESSAGE, icon);
            } else {
                JOptionPane.showMessageDialog(this.getParent(), "Sa tht bi", "Fail",
                        JOptionPane.ERROR_MESSAGE);
            }
        } else {
            objUser = new User(mUser.getIdUser(), username, password, fullname, role,
                    new Date(System.currentTimeMillis()), mUser.getAvatar());
            if (mControllerUser.editItem(objUser, mRow)) {
                ImageIcon icon = new ImageIcon(getClass().getResource("/images/ic_success.png"));
                JOptionPane.showMessageDialog(this.getParent(), "Sa thnh cng", "Success",
                        JOptionPane.INFORMATION_MESSAGE, icon);
            } else {
                JOptionPane.showMessageDialog(this.getParent(), "Sa tht bi", "Fail",
                        JOptionPane.ERROR_MESSAGE);
            }
        }
        mUser = objUser;
        this.dispose();
    }

    public DialogFunctionUser(Frame owner, boolean modal, ControllerUser controllerUser) {
        super(owner, modal);
        initComponents();
        mType = Constant.TYPE_ADD;
        this.mControllerUser = controllerUser;
        tfFullname.setVisible(false);
        lbQuantity.setVisible(false);
        mAvatar = null;
    }

    private void actionAddUser() {
        if (!isValidData()) {
            return;
        }
        if (isExistUsername(tfUsername.getText())) {
            JOptionPane.showMessageDialog(null, "Username  tn ti", "Error", JOptionPane.ERROR_MESSAGE);
            return;
        }
        String username = tfUsername.getText();
        String fullname = tfFullname.getText();
        String password = new String(tfPassword.getPassword());
        password = LibraryString.md5(password);
        int role = cbRole.getSelectedIndex();
        User objUser;
        if (mAvatar != null) {
            objUser = new User(UUID.randomUUID().toString(), username, password, fullname, role,
                    new Date(System.currentTimeMillis()), mAvatar.getPath());
            String fileName = FilenameUtils.getBaseName(mAvatar.getName()) + "-" + System.nanoTime() + "."
                    + FilenameUtils.getExtension(mAvatar.getName());
            Path source = Paths.get(mAvatar.toURI());
            Path destination = Paths.get("files/" + fileName);
            try {
                Files.copy(source, destination, StandardCopyOption.REPLACE_EXISTING);
            } catch (IOException ex) {
                Logger.getLogger(DialogFunctionRoom.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else {
            objUser = new User(UUID.randomUUID().toString(), username, password, fullname, role,
                    new Date(System.currentTimeMillis()), "");
        }
        if (mControllerUser.addItem(objUser)) {
            ImageIcon icon = new ImageIcon(getClass().getResource("/images/ic_success.png"));
            JOptionPane.showMessageDialog(this.getParent(), "Thm thnh cng", "Success",
                    JOptionPane.INFORMATION_MESSAGE, icon);
        } else {
            JOptionPane.showMessageDialog(this.getParent(), "Thm tht bi", "Fail",
                    JOptionPane.ERROR_MESSAGE);
        }
        this.dispose();
    }

    public DialogFunctionUser(Frame owner, boolean modal, ControllerUser controllerUser, User objUser, int row) {
        super(owner, modal);
        initComponents();
        mType = Constant.TYPE_EDIT;
        tfUsername.setEditable(false);
        this.mControllerUser = controllerUser;
        mUser = objUser;
        btnFunction.setText("Edit");
        btnFunction.setIcon(new ImageIcon(getClass().getResource("/images/ic_edit.png")));
        tfUsername.setText(objUser.getUsername());
        tfFullname.setText(objUser.getUsername());
        cbRole.setSelectedIndex(objUser.getRole());
        File file = new File(objUser.getAvatar());
        if (file.exists()) {
            PictureUtil.setPicture(lbAvatar, file);
        }
        mRow = row;
    }

    private void actionEditUser() {
        if (!isValidData()) {
            return;
        }
        if (!isValidData()) {
            return;
        }
        String username = tfUsername.getText();
        String fullname = tfFullname.getText();
        String password = mUser.getPassword();
        if (tfPassword.getPassword().length == 0) {
            password = new String(tfPassword.getPassword());
            password = LibraryString.md5(password);
        }
        int role = cbRole.getSelectedIndex();
        if (mAvatar != null) {
            User objUser = new User(mUser.getIdUser(), username, password, fullname, role,
                    new Date(System.currentTimeMillis()), mAvatar.getPath());
            if (mControllerUser.editItem(objUser, mRow)) {
                String fileName = FilenameUtils.getBaseName(mAvatar.getName()) + "-" + System.nanoTime() + "."
                        + FilenameUtils.getExtension(mAvatar.getName());
                Path source = Paths.get(mAvatar.toURI());
                Path destination = Paths.get("files/" + fileName);
                Path pathOldAvatar = Paths.get(mUser.getAvatar());
                try {
                    Files.copy(source, destination, StandardCopyOption.REPLACE_EXISTING);
                    Files.deleteIfExists(pathOldAvatar);
                } catch (IOException ex) {
                    Logger.getLogger(DialogFunctionRoom.class.getName()).log(Level.SEVERE, null, ex);
                }
                ImageIcon icon = new ImageIcon(getClass().getResource("/images/ic_success.png"));
                JOptionPane.showMessageDialog(this.getParent(), "Sa thnh cng", "Success",
                        JOptionPane.INFORMATION_MESSAGE, icon);
            } else {
                JOptionPane.showMessageDialog(this.getParent(), "Sa tht bi", "Fail",
                        JOptionPane.ERROR_MESSAGE);
            }
        } else {
            User objUser = new User(mUser.getIdUser(), username, password, fullname, role,
                    new Date(System.currentTimeMillis()), mUser.getAvatar());
            if (mControllerUser.editItem(objUser, mRow)) {
                ImageIcon icon = new ImageIcon(getClass().getResource("/images/ic_success.png"));
                JOptionPane.showMessageDialog(this.getParent(), "Sa thnh cng", "Success",
                        JOptionPane.INFORMATION_MESSAGE, icon);
            } else {
                JOptionPane.showMessageDialog(this.getParent(), "Sa tht bi", "Fail",
                        JOptionPane.ERROR_MESSAGE);
            }
        }
        this.dispose();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel3 = new javax.swing.JPanel();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        lbQuantity = new javax.swing.JLabel();
        tfUsername = new javax.swing.JTextField();
        tfFullname = new javax.swing.JTextField();
        jPanel2 = new javax.swing.JPanel();
        btnFunction = new javax.swing.JButton();
        btnRefill = new javax.swing.JButton();
        btnExit = new javax.swing.JButton();
        tfPassword = new javax.swing.JPasswordField();
        jLabel3 = new javax.swing.JLabel();
        cbRole = new javax.swing.JComboBox<>();
        jLabel4 = new javax.swing.JLabel();
        btnUpload = new javax.swing.JButton();
        lbAvatar = new javax.swing.JLabel();

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(jPanel3Layout
                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGap(0, 320, Short.MAX_VALUE));
        jPanel3Layout.setVerticalGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGap(0, 100, Short.MAX_VALUE));

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setBackground(new java.awt.Color(251, 250, 202));

        jPanel1.setBackground(new java.awt.Color(251, 250, 202));

        jLabel1.setText("Tn ng nhp");

        jLabel2.setText("Mt khu");

        lbQuantity.setText("H? tn");

        jPanel2.setBackground(new java.awt.Color(251, 250, 202));

        btnFunction.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/ic_add.png"))); // NOI18N
        btnFunction.setText("Thm");
        btnFunction.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnFunctionActionPerformed(evt);
            }
        });
        jPanel2.add(btnFunction);

        btnRefill.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/ic_refill.png"))); // NOI18N
        btnRefill.setText("Nhp li");
        btnRefill.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRefillActionPerformed(evt);
            }
        });
        jPanel2.add(btnRefill);

        btnExit.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/ic_del.png"))); // NOI18N
        btnExit.setText("Thot");
        btnExit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnExitActionPerformed(evt);
            }
        });
        jPanel2.add(btnExit);

        jLabel3.setText("Chc v");

        cbRole.setModel(
                new javax.swing.DefaultComboBoxModel<>(new String[] { "", "Admin", "Qun l", "Nhn vin" }));

        jLabel4.setText("nh i din");

        btnUpload.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/ic_upload.png"))); // NOI18N
        btnUpload.setText("Ch?n nh");
        btnUpload.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnUploadActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(jPanel1Layout
                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, 352, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createSequentialGroup().addContainerGap()
                        .addGroup(jPanel1Layout
                                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(
                                        jPanel1Layout.createSequentialGroup().addGroup(jPanel1Layout
                                                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                .addComponent(
                                                        jLabel1)
                                                .addComponent(jLabel2).addComponent(lbQuantity)
                                                .addComponent(jLabel3)).addGap(68, 68, 68)
                                                .addGroup(jPanel1Layout
                                                        .createParallelGroup(
                                                                javax.swing.GroupLayout.Alignment.LEADING)
                                                        .addGroup(jPanel1Layout.createSequentialGroup()
                                                                .addComponent(cbRole,
                                                                        javax.swing.GroupLayout.PREFERRED_SIZE,
                                                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                                                .addGap(0, 0, Short.MAX_VALUE))
                                                        .addComponent(tfUsername).addComponent(tfPassword)
                                                        .addComponent(tfFullname)))
                                .addGroup(jPanel1Layout.createSequentialGroup().addComponent(jLabel4)
                                        .addGap(26, 26, 26)
                                        .addComponent(lbAvatar, javax.swing.GroupLayout.DEFAULT_SIZE,
                                                javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(btnUpload)))
                        .addContainerGap()));
        jPanel1Layout.setVerticalGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup().addGap(30, 30, 30).addGroup(jPanel1Layout
                        .createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER).addComponent(jLabel1)
                        .addComponent(tfUsername, javax.swing.GroupLayout.PREFERRED_SIZE,
                                javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jLabel2).addComponent(tfPassword,
                                        javax.swing.GroupLayout.PREFERRED_SIZE,
                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                        javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                                .addComponent(lbQuantity).addComponent(tfFullname,
                                        javax.swing.GroupLayout.PREFERRED_SIZE,
                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                        javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                                .addComponent(cbRole, javax.swing.GroupLayout.PREFERRED_SIZE,
                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jLabel3))
                        .addGap(18, 18, 18).addGroup(
                                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addGroup(jPanel1Layout.createSequentialGroup().addGroup(jPanel1Layout
                                                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                .addComponent(jLabel4).addComponent(lbAvatar,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE, 130,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE))
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED,
                                                        41, Short.MAX_VALUE)
                                                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE,
                                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE))
                                        .addGroup(jPanel1Layout.createSequentialGroup().addComponent(btnUpload)
                                                .addGap(0, 0, Short.MAX_VALUE)))));

        getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnRefillActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRefillActionPerformed
        tfUsername.setText("");
        tfPassword.setText("");
        tfFullname.setText("");
    }//GEN-LAST:event_btnRefillActionPerformed

    private void btnExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExitActionPerformed
        this.dispose();
    }//GEN-LAST:event_btnExitActionPerformed

    private void btnFunctionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFunctionActionPerformed
        if (mType == Constant.TYPE_ADD && mControllerUser != null) {
            actionAddUser();
        } else if (mType == Constant.TYPE_EDIT && mControllerUser != null) {
            actionEditUser();
        } else if (mType == Constant.TYPE_ADD && mControllerUser == null) {
            actionAddUserNoController();
        } else if (mType == Constant.TYPE_EDIT && mControllerUser == null) {
            actionEditUserNoController();
        }
    }//GEN-LAST:event_btnFunctionActionPerformed

    private void btnUploadActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnUploadActionPerformed
        JFileChooser fileChooser = new JFileChooser();
        int result = fileChooser.showDialog(null, "Upload avatar");
        if (result == JFileChooser.APPROVE_OPTION) {
            mAvatar = fileChooser.getSelectedFile();
            if (!PictureUtil.isPicture(mAvatar)) {
                JOptionPane.showMessageDialog(null, "?y khng phi l nh", "Error",
                        JOptionPane.ERROR_MESSAGE);
                mAvatar = null;
            } else {
                PictureUtil.setPicture(lbAvatar, mAvatar);
            }
        }
    }//GEN-LAST:event_btnUploadActionPerformed

    private boolean isExistUsername(String username) {
        return (new ModelUser()).isExistUsername(username);
    }

    private boolean isValidData() {
        if ("".equals(tfUsername.getText())) {
            JOptionPane.showMessageDialog(null, "Tn ng nhp khng c  trng", "Error",
                    JOptionPane.ERROR_MESSAGE);
            tfUsername.requestFocus();
            return false;
        }

        if ("".equals(tfFullname.getText())) {
            JOptionPane.showMessageDialog(null, "H? tn khng c  trng", "Error",
                    JOptionPane.ERROR_MESSAGE);
            tfFullname.requestFocus();
            return false;
        }

        if (mType == Constant.TYPE_ADD && tfPassword.getPassword().length == 0) {
            JOptionPane.showMessageDialog(null, "Mt khu khng c  trng", "Error",
                    JOptionPane.ERROR_MESSAGE);
            tfPassword.requestFocus();
            return false;
        }

        if (cbRole.getSelectedIndex() == 0) {
            JOptionPane.showMessageDialog(null, "Ch?n chc v!", "Error", JOptionPane.ERROR_MESSAGE);
            cbRole.requestFocus();
            return false;
        }

        return true;
    }

    public User setVisibleReturnUser() {
        this.setVisible(true);
        return mUser;
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnExit;
    private javax.swing.JButton btnFunction;
    private javax.swing.JButton btnRefill;
    private javax.swing.JButton btnUpload;
    private javax.swing.JComboBox<String> cbRole;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JLabel lbAvatar;
    private javax.swing.JLabel lbQuantity;
    private javax.swing.JTextField tfFullname;
    private javax.swing.JPasswordField tfPassword;
    private javax.swing.JTextField tfUsername;
    // End of variables declaration//GEN-END:variables
}