Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package inventory;
- import java.awt.BorderLayout;
- import java.awt.Color;
- import java.awt.Dimension;
- import java.awt.FlowLayout;
- import java.awt.GridLayout;
- import java.awt.event.ActionEvent;
- import java.awt.event.ActionListener;
- import java.awt.event.WindowAdapter;
- import java.awt.event.WindowEvent;
- import java.io.File;
- import javax.swing.filechooser.FileFilter;
- import java.io.BufferedWriter;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.io.FileWriter;
- import java.io.IOException;
- import java.io.ObjectInputStream;
- import java.io.ObjectOutputStream;
- import java.security.MessageDigest;
- import java.security.NoSuchAlgorithmException;
- import java.text.DateFormat;
- import java.text.SimpleDateFormat;
- import java.util.ArrayList;
- import java.util.Date;
- import java.util.Iterator;
- import javax.swing.BorderFactory;
- import javax.swing.JButton;
- import javax.swing.JFileChooser;
- import javax.swing.JFrame;
- import javax.swing.JLabel;
- import javax.swing.JOptionPane;
- import javax.swing.JPanel;
- import javax.swing.JPasswordField;
- import javax.swing.JTextField;
- import javax.swing.UIManager;
- public class Main {
- //Initialize ArrayLists and File
- protected static File masterDBFile = new File("master.zbdb");
- protected static File masterDBFileBackup = new File("master.backup.zbdb");
- protected static File userLoadedFile = null;
- private static boolean fileExists = false;
- private static boolean forceSaveAs = false;
- private static JFileChooser forceSave = null;
- protected static boolean userAuthorized = false;
- protected static ArrayList<Users> userList = new ArrayList<Users>();
- protected static ArrayList<ArrayList<Products>> productLineList = new ArrayList<ArrayList<Products>>();
- protected static ArrayList<Components> componentList = new ArrayList<Components>();
- //JFrame
- protected static JFrame zbFrame = null;
- public static void main(String[] args) {
- try {
- UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
- }
- catch (Exception ignore) { }
- //Check if master.zbdb or master.backup.zbdb exist. This to avoid dual error
- fileExists = (masterDBFile.exists() || masterDBFileBackup.exists()) ? true : false;
- //If it doesn't exist skip login and loading database
- if(!fileExists) {
- showDialog(1, "No default database exists. A new one will be created.", null);
- showSplashScreen();
- createAndShowGUI();
- }
- //If it does then load everything
- else {
- showSplashScreen();
- loadUserDatabase(null);
- //User Authorization first if user ArrayList is populated. Function loads full database and GUI if credentials are valid
- if(!userList.isEmpty()) {
- showUserLoginFrame();
- if(userAuthorized) {
- //Load entire database and GUI. Reset userAuthorized to false for future use.
- userAuthorized = false;
- loadDatabase(null);
- createAndShowGUI();
- }
- }
- else {
- loadDatabase(null);
- createAndShowGUI();
- }
- }
- }
- protected static void createAndShowGUI() {
- //Tabs
- InventoryTabs zbTabs = new InventoryTabs();
- //GUI
- zbFrame = new JFrame("ZeroBull Inventory v0.2 BUILD_0200_ALPHA");
- zbFrame.getContentPane().add(zbTabs.topPanel);
- zbFrame.setPreferredSize(new Dimension(800,600));
- zbFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
- zbFrame.setResizable(false);
- zbFrame.setJMenuBar(new InventoryMenubar().menuBar);
- zbFrame.add(zbTabs, BorderLayout.EAST);
- zbFrame.addWindowListener(new WindowAdapter() {
- public void windowClosing(WindowEvent we) {
- int closeOperation = saveBeforeExit();
- if(closeOperation == 0)
- System.exit(0);
- else
- zbFrame.setVisible(true);
- }
- });
- zbFrame.pack();
- zbFrame.setLocationRelativeTo(null);
- zbFrame.setVisible(true);
- }
- private static void showSplashScreen() {
- new SplashScreen();
- }
- protected static void disposeMainFrame() {
- zbFrame.dispose();
- }
- //This should ONLY be called after calling disposeMainFrame()
- protected static void reloadGUI() {
- createAndShowGUI();
- }
- public static void showUserLoginFrame() {
- final JFrame authFrame = new JFrame("Login");
- authFrame.setPreferredSize(new Dimension(200,150));
- authFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- authFrame.setResizable(false);
- JPanel authPanel = new JPanel();
- authPanel.setLayout(new BorderLayout());
- authPanel.setBorder(BorderFactory.createTitledBorder("Enter Credentials"));
- JPanel leftColumn = new JPanel(new GridLayout(0,1,0,25));
- JPanel rightColumn = new JPanel(new GridLayout(0,1,0,25));
- JPanel bottomPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
- JLabel userLabel = new JLabel("Username: ");
- JLabel passLabel = new JLabel("Password: ");
- final JTextField userField = new JTextField(15);
- userField.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY));
- final JPasswordField passField = new JPasswordField(15);
- passField.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY));
- JButton loginButton = new JButton("Login");
- loginButton.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent ev) {
- String userName = userField.getText();
- char[] userPass = passField.getPassword();
- boolean valid = authorizeUser(userName, userPass);
- if(valid) {
- showDialog(2, "Success! Welcome, " +userName, authFrame);
- authFrame.dispose();
- userAuthorized = true;
- createAndShowGUI();
- }
- else
- showDialog(0, "Invalid Credentialds.", authFrame);
- }
- });
- JButton exitButton = new JButton("Exit");
- exitButton.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent ev) {
- authFrame.dispose();
- System.exit(0);
- }
- });
- leftColumn.add(userLabel);
- leftColumn.add(passLabel);
- rightColumn.add(userField);
- rightColumn.add(passField);
- bottomPanel.add(loginButton);
- bottomPanel.add(exitButton);
- authPanel.add(leftColumn, BorderLayout.WEST);
- authPanel.add(rightColumn, BorderLayout.EAST);
- authPanel.add(bottomPanel, BorderLayout.SOUTH);
- authFrame.add(authPanel);
- authFrame.pack();
- authFrame.setLocationRelativeTo(null);
- authFrame.setVisible(true);
- }
- public static void createNewProductLine(String productLineName, int productLineQty, int productLineComp, int productLineIncomp) {
- ArrayList<Products> productList = new ArrayList<Products>();
- productList.ensureCapacity(productLineQty);
- for(int i=0; i<productLineComp; i++)
- productList.add(new Products(productLineName, "COMPLETE"));
- for(int i=0; i<productLineIncomp; i++)
- productList.add(new Products(productLineName, "INCOMPLETE"));
- productLineList.add(productList);
- }
- public static boolean checkExistingProductLine(String productLineName) {
- for(int i=0; i<productLineList.size(); i++) {
- if (productLineName.equalsIgnoreCase(productLineList.get(i).get(0).getProductLineName()))
- return false;
- }
- return true;
- }
- public static void addToProductLine(int index, int qtyToAdd, int qtyComplete, int qtyIncomplete) {
- ArrayList<Products> temp = new ArrayList<Products>();
- for(int i=0; i<qtyComplete; i++)
- temp.add(new Products(productLineList.get(index).get(0).getProductLineName(), "COMPLETE"));
- for(int i=0; i<qtyIncomplete; i++)
- temp.add(new Products(productLineList.get(index).get(0).getProductLineName(), "INCOMPLETE"));
- productLineList.get(index).addAll(temp);
- }
- public static void renameProductLine(int index, String newname) {
- }
- public static void deleteProductLine(int index) {
- for(int i=0; i<componentList.size(); i++) {
- if(componentList.get(i).getComponentHashMap().containsKey(index))
- componentList.get(i).getComponentHashMap().remove(index);
- }
- productLineList.remove(index);
- }
- protected static void editSelProdRows(String status, String serial, String date, String loc, int[] selRows, int productLineIndex) {
- for(int i=0; i<selRows.length; i++) {
- if(!status.equalsIgnoreCase("(Status)"))
- productLineList.get(productLineIndex).get(selRows[i]).setProductLineStatus(status);
- if(!serial.equalsIgnoreCase(""))
- productLineList.get(productLineIndex).get(selRows[i]).setProductSerial(serial);
- if(!date.equalsIgnoreCase(""))
- productLineList.get(productLineIndex).get(selRows[i]).setProductMFGDate(date);
- if(!loc.equalsIgnoreCase(""))
- productLineList.get(productLineIndex).get(selRows[i]).setProductMFGLoc(loc);
- }
- }
- public static void createNewComponent(String componentName, int componentQty, int[] plKeys, int[] plValues, String compDesc) {
- componentList.add(new Components(componentName, componentQty, plKeys, plValues, compDesc));
- }
- public static void createNewComponent(String componentName, int componentQty, int[] plKeys, int[] plValues, int shipQty, String compDesc) {
- componentList.add(new Components(componentName, componentQty, plKeys, plValues, shipQty, compDesc));
- }
- public static boolean checkExistingComponent(String compName) {
- for (int i=0; i<componentList.size(); i++)
- if(componentList.get(i).getComponentName().equalsIgnoreCase(compName))
- return false;
- return true;
- }
- public static ArrayList<Components> checkComponentsUsed(int index) {
- ArrayList<Components> temp = new ArrayList<Components>();
- for(int i=0; i<componentList.size(); i++) {
- Iterator<Integer> iter = componentList.get(i).getComponentHashMap().keySet().iterator();
- while(iter.hasNext()) {
- int currentElem = (Integer)iter.next();
- if(currentElem == (Integer)index)
- temp.add(componentList.get(i));
- }
- }
- return temp;
- }
- public static void createNewUser(String name, char[] pass) {
- userList.add(new Users(name, pass));
- }
- public static boolean authorizeUser(String name, char[] pass) {
- int userIndex = 0;
- boolean userExists = false;
- //First check if user exists. If it doesnt then don't bother checking the pass just return false
- for(int i=0; i<userList.size(); i++) {
- if(userList.get(i).getUserName().equalsIgnoreCase(name)) {
- userIndex = i;
- userExists = true;
- break;
- }
- }
- if(!userExists)
- return false;
- //Name has been validated. Now check password.
- byte[] bytePass = new byte[pass.length];
- byte[] salt = userList.get(userIndex).getUserSalt();
- byte[] digested = null;
- String hashCheck = "";
- for(int i=0; i<bytePass.length; i++)
- bytePass[i] = (byte) pass[i];
- MessageDigest md = null;
- try {
- md = MessageDigest.getInstance("SHA");
- } catch(NoSuchAlgorithmException nsae) { }
- md.update(salt);
- md.update(bytePass);
- digested = md.digest();
- for(int i=0; i<999; i++) {
- md.reset();
- digested = md.digest(digested);
- }
- for(int i=0; i<digested.length; i++)
- hashCheck += (Integer.toHexString((0x000000ff & digested[i]) | 0xffffff00).substring(6));
- if(userList.get(userIndex).getUserSHAHash().equals(hashCheck))
- return true;
- else
- return false;
- }
- public static boolean checkUserExists(String name) {
- for(int i=0; i<userList.size(); i++) {
- if(userList.get(i).getUserName().equalsIgnoreCase(name))
- return true;
- }
- return false;
- }
- public static void saveDatabase(File file) {
- ArrayList<Users> userListSave = userList;
- ArrayList<ArrayList<Products>> productLineListSave = productLineList;
- ArrayList<Components> componentListSave = componentList;
- ObjectOutputStream fileOut = null;
- try {
- file.createNewFile();
- } catch (IOException ioe) { }
- if(file.canWrite() == false) {
- showDialog(0, "Program does not have permission to write in current directory. Exit", zbFrame);
- return;
- }
- try {
- fileOut = new ObjectOutputStream(new FileOutputStream(file));
- } catch(IOException ioe) { }
- try {
- fileOut.writeUTF("ZeroBull(tm) Inventory Master Database\t\t ZB_INVENTORY_BUILD_0700_ALPHA\t\t");
- fileOut.writeUTF(getCurrentDate()+"\t\t");
- fileOut.writeUTF("Begin Database\t\t");
- fileOut.writeObject(userListSave);
- fileOut.writeObject(productLineListSave);
- fileOut.writeObject(componentListSave);
- fileOut.writeUTF("\t\tEnd Database\t\t");
- fileOut.close();
- } catch(IOException ioe) { }
- }
- @SuppressWarnings("unchecked")
- public static void loadUserDatabase(File customFile) {
- ObjectInputStream fileIn = null;
- //Try and load from main. If that fails use backup
- if(customFile != null) {
- try {
- fileIn = new ObjectInputStream(new FileInputStream(customFile));
- } catch(IOException ioe) { }
- }
- else {
- if(masterDBFile.exists() == true) {
- try {
- fileIn = new ObjectInputStream(new FileInputStream(masterDBFile));
- } catch(IOException ioe) { }
- }
- else if(masterDBFileBackup.exists() == true) {
- try {
- fileIn = new ObjectInputStream(new FileInputStream(masterDBFileBackup));
- } catch(IOException ioe) { }
- }
- }
- try {
- fileIn.readUTF();
- fileIn.readUTF();
- fileIn.readUTF();
- userList = (ArrayList<Users>) fileIn.readObject();
- fileIn.close();
- } catch(Exception invalidDB) {
- showDialog(0, "Invalid database file!", zbFrame);
- }
- }
- @SuppressWarnings("unchecked")
- public static void loadDatabase(File customFile) {
- //Must clear user ArrayList first since it was [supposedly] already loaded.
- userList.clear();
- ObjectInputStream fileIn = null;
- //Try main database first. If file does not exist load backup. If that fails then throw error message and let user select a database.
- if(customFile != null) {
- try {
- fileIn = new ObjectInputStream(new FileInputStream(customFile));
- } catch(IOException ioe) { }
- }
- else {
- if(masterDBFile.exists() == true) {
- try {
- fileIn = new ObjectInputStream(new FileInputStream(masterDBFile));
- } catch(IOException ioe) { }
- }
- else if(masterDBFileBackup.exists() == true) {
- try {
- fileIn = new ObjectInputStream(new FileInputStream(masterDBFileBackup));
- } catch(IOException ioe) { }
- }
- }
- try {
- fileIn.readUTF();
- fileIn.readUTF();
- fileIn.readUTF();
- userList = (ArrayList<Users>) fileIn.readObject();
- productLineList = (ArrayList<ArrayList<Products>>) fileIn.readObject();
- componentList = (ArrayList<Components>) fileIn.readObject();
- fileIn.readUTF();
- fileIn.close();
- } catch(Exception ignore) { }
- }
- protected static void flushDatabases() {
- userList.clear();
- productLineList.clear();
- componentList.clear();
- }
- public static void setForceSaveAs() {
- forceSaveAs = true;
- }
- public static int saveBeforeExit() {
- int option = JOptionPane.showConfirmDialog(null, "Save before exiting?", "Save", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE);
- if(option == JOptionPane.YES_OPTION) {
- if(!forceSaveAs) {
- if (userLoadedFile != null)
- saveDatabase(userLoadedFile);
- else {
- saveDatabase(masterDBFile);
- saveDatabase(masterDBFileBackup);
- }
- return 0;
- }
- else {
- forceSave = new JFileChooser("Save As...");
- forceSave.setFileFilter(new FileFilter() {
- public boolean accept(File saveFile) {
- return saveFile.getName().toLowerCase().endsWith(".zbdb") || saveFile.isDirectory();
- }
- public String getDescription() {
- return "ZeroBull Database";
- }
- });
- int saveReturn = forceSave.showSaveDialog(null);
- if(saveReturn == JFileChooser.APPROVE_OPTION) {
- if (Main.productLineList.isEmpty() && Main.componentList.isEmpty() && Main.userList.isEmpty())
- JOptionPane.showMessageDialog(null, "Can not save an empty database!", "Error!", JOptionPane.ERROR_MESSAGE);
- else {
- String savePath = forceSave.getSelectedFile().getPath() +".zbdb";
- saveDatabase(new File(savePath));
- }
- }
- }
- }
- else if(option == JOptionPane.NO_OPTION)
- return 0;
- else if(option == JOptionPane.CANCEL_OPTION)
- return 1;
- return 0;
- }
- public static String getCurrentDate() {
- DateFormat date = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
- Date currentDate = new Date();
- return date.format(currentDate);
- }
- private static void showDialog(int level, String message, JFrame owner) {
- switch(level) {
- case 0:
- JOptionPane.showMessageDialog(owner, message, "Error", JOptionPane.ERROR_MESSAGE); break;
- case 1:
- JOptionPane.showMessageDialog(owner, message, "Warning", JOptionPane.WARNING_MESSAGE); break;
- case 2:
- JOptionPane.showMessageDialog(owner, message, "Message", JOptionPane.INFORMATION_MESSAGE); break;
- }
- }
- }
- class outWriter {
- //This awesome class here allows me to write to the log file from ANYWHERE.
- private static final File logFile = new File("log.txt");
- private static BufferedWriter logOut = null;
- public static boolean initialize() {
- try {
- if(logOut == null) {
- logOut = new BufferedWriter(new FileWriter(logFile, true));
- return true;
- }
- } catch(IOException ioe) { }
- return false;
- }
- public static boolean write (String out, boolean close) {
- try {
- if(out != null && logOut != null) {
- logOut.write(out +"\r\n");
- return true;
- }
- } catch(IOException ioe) { }
- return false;
- }
- public static boolean close() {
- try {
- if(logOut != null) {
- logOut.close();
- return true;
- }
- } catch(IOException ioe) { }
- return false;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement