Advertisement
Guest User

Untitled

a guest
Jun 16th, 2017
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 17.55 KB | None | 0 0
  1. package inventory;
  2.  
  3. import java.awt.BorderLayout;
  4. import java.awt.Color;
  5. import java.awt.Dimension;
  6. import java.awt.FlowLayout;
  7. import java.awt.GridLayout;
  8. import java.awt.event.ActionEvent;
  9. import java.awt.event.ActionListener;
  10. import java.awt.event.WindowAdapter;
  11. import java.awt.event.WindowEvent;
  12.  
  13. import java.io.File;
  14. import javax.swing.filechooser.FileFilter;
  15.  
  16. import java.io.BufferedWriter;
  17. import java.io.FileInputStream;
  18. import java.io.FileOutputStream;
  19. import java.io.FileWriter;
  20. import java.io.IOException;
  21. import java.io.ObjectInputStream;
  22. import java.io.ObjectOutputStream;
  23. import java.security.MessageDigest;
  24. import java.security.NoSuchAlgorithmException;
  25. import java.text.DateFormat;
  26. import java.text.SimpleDateFormat;
  27. import java.util.ArrayList;
  28. import java.util.Date;
  29. import java.util.Iterator;
  30.  
  31. import javax.swing.BorderFactory;
  32. import javax.swing.JButton;
  33. import javax.swing.JFileChooser;
  34. import javax.swing.JFrame;
  35. import javax.swing.JLabel;
  36. import javax.swing.JOptionPane;
  37. import javax.swing.JPanel;
  38. import javax.swing.JPasswordField;
  39. import javax.swing.JTextField;
  40. import javax.swing.UIManager;
  41.  
  42. public class Main {
  43.    
  44.     //Initialize ArrayLists and File
  45.     protected static File masterDBFile = new File("master.zbdb");
  46.     protected static File masterDBFileBackup = new File("master.backup.zbdb");
  47.     protected static File userLoadedFile = null;
  48.     private static boolean fileExists = false;
  49.     private static boolean forceSaveAs = false;
  50.     private static JFileChooser forceSave = null;
  51.     protected static boolean userAuthorized = false;
  52.     protected static ArrayList<Users> userList = new ArrayList<Users>();
  53.     protected static ArrayList<ArrayList<Products>> productLineList = new ArrayList<ArrayList<Products>>();
  54.     protected static ArrayList<Components> componentList = new ArrayList<Components>();
  55.     //JFrame
  56.     protected static JFrame zbFrame = null;
  57.    
  58.     public static void main(String[] args) {
  59.         try {
  60.             UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
  61.         }
  62.         catch (Exception ignore) { }
  63.        
  64.         //Check if master.zbdb or master.backup.zbdb exist. This to avoid dual error
  65.         fileExists = (masterDBFile.exists() || masterDBFileBackup.exists()) ? true : false;
  66.         //If it doesn't exist skip login and loading database
  67.         if(!fileExists) {
  68.             showDialog(1, "No default database exists. A new one will be created.", null);
  69.             showSplashScreen();
  70.             createAndShowGUI();
  71.         }
  72.         //If it does then load everything
  73.         else {
  74.             showSplashScreen();
  75.             loadUserDatabase(null);
  76.             //User Authorization first if user ArrayList is populated. Function loads full database and GUI if credentials are valid
  77.             if(!userList.isEmpty()) {
  78.                 showUserLoginFrame();
  79.                 if(userAuthorized) {
  80.                     //Load entire database and GUI. Reset userAuthorized to false for future use.
  81.                     userAuthorized = false;
  82.                     loadDatabase(null);
  83.                     createAndShowGUI();
  84.                 }
  85.             }
  86.             else {
  87.                 loadDatabase(null);
  88.                 createAndShowGUI();
  89.             }
  90.         }
  91.     }
  92.    
  93.     protected static void createAndShowGUI() {
  94.         //Tabs
  95.         InventoryTabs zbTabs = new InventoryTabs();
  96.         //GUI
  97.         zbFrame = new JFrame("ZeroBull Inventory v0.2 BUILD_0200_ALPHA");
  98.         zbFrame.getContentPane().add(zbTabs.topPanel);
  99.         zbFrame.setPreferredSize(new Dimension(800,600));
  100.         zbFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
  101.         zbFrame.setResizable(false);
  102.         zbFrame.setJMenuBar(new InventoryMenubar().menuBar);
  103.         zbFrame.add(zbTabs, BorderLayout.EAST);
  104.         zbFrame.addWindowListener(new WindowAdapter() {
  105.             public void windowClosing(WindowEvent we) {
  106.                 int closeOperation = saveBeforeExit();
  107.                 if(closeOperation == 0)
  108.                     System.exit(0);
  109.                 else
  110.                     zbFrame.setVisible(true);
  111.             }
  112.         });
  113.         zbFrame.pack();
  114.         zbFrame.setLocationRelativeTo(null);
  115.         zbFrame.setVisible(true);
  116.     }
  117.    
  118.     private static void showSplashScreen() {
  119.         new SplashScreen();
  120.     }
  121.    
  122.     protected static void disposeMainFrame() {
  123.         zbFrame.dispose();
  124.     }
  125.    
  126.     //This should ONLY be called after calling disposeMainFrame()
  127.     protected static void reloadGUI() {
  128.         createAndShowGUI();
  129.     }
  130.    
  131.     public static void showUserLoginFrame() {
  132.         final JFrame authFrame = new JFrame("Login");
  133.         authFrame.setPreferredSize(new Dimension(200,150));
  134.         authFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  135.         authFrame.setResizable(false);
  136.         JPanel authPanel = new JPanel();
  137.         authPanel.setLayout(new BorderLayout());
  138.        
  139.             authPanel.setBorder(BorderFactory.createTitledBorder("Enter Credentials"));
  140.             JPanel leftColumn = new JPanel(new GridLayout(0,1,0,25));
  141.             JPanel rightColumn = new JPanel(new GridLayout(0,1,0,25));
  142.             JPanel bottomPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
  143.            
  144.                 JLabel userLabel = new JLabel("Username: ");
  145.                 JLabel passLabel = new JLabel("Password: ");
  146.                 final JTextField userField = new JTextField(15);
  147.                 userField.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY));
  148.                 final JPasswordField passField = new JPasswordField(15);
  149.                 passField.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY));
  150.                
  151.                 JButton loginButton = new JButton("Login");
  152.                 loginButton.addActionListener(new ActionListener() {
  153.                     public void actionPerformed(ActionEvent ev) {
  154.                         String userName = userField.getText();
  155.                         char[] userPass = passField.getPassword();
  156.                         boolean valid = authorizeUser(userName, userPass);
  157.                         if(valid) {
  158.                             showDialog(2, "Success! Welcome, " +userName, authFrame);
  159.                             authFrame.dispose();
  160.                             userAuthorized = true;
  161.                             createAndShowGUI();
  162.                         }
  163.                         else
  164.                             showDialog(0, "Invalid Credentialds.", authFrame);
  165.                     }
  166.                 });
  167.                 JButton exitButton = new JButton("Exit");
  168.                 exitButton.addActionListener(new ActionListener() {
  169.                     public void actionPerformed(ActionEvent ev) {
  170.                         authFrame.dispose();
  171.                         System.exit(0);
  172.                     }
  173.                 });
  174.                
  175.             leftColumn.add(userLabel);
  176.             leftColumn.add(passLabel);
  177.             rightColumn.add(userField);
  178.             rightColumn.add(passField);
  179.             bottomPanel.add(loginButton);
  180.             bottomPanel.add(exitButton);
  181.            
  182.         authPanel.add(leftColumn, BorderLayout.WEST);
  183.         authPanel.add(rightColumn, BorderLayout.EAST);
  184.         authPanel.add(bottomPanel, BorderLayout.SOUTH);
  185.         authFrame.add(authPanel);
  186.         authFrame.pack();
  187.         authFrame.setLocationRelativeTo(null);
  188.         authFrame.setVisible(true);    
  189.     }
  190.    
  191.     public static void createNewProductLine(String productLineName, int productLineQty, int productLineComp, int productLineIncomp) {
  192.         ArrayList<Products> productList = new ArrayList<Products>();
  193.         productList.ensureCapacity(productLineQty);
  194.         for(int i=0; i<productLineComp; i++)
  195.             productList.add(new Products(productLineName, "COMPLETE"));
  196.         for(int i=0; i<productLineIncomp; i++)
  197.             productList.add(new Products(productLineName, "INCOMPLETE"));
  198.         productLineList.add(productList);
  199.     }
  200.    
  201.     public static boolean checkExistingProductLine(String productLineName) {
  202.         for(int i=0; i<productLineList.size(); i++) {
  203.             if (productLineName.equalsIgnoreCase(productLineList.get(i).get(0).getProductLineName()))
  204.                 return false;
  205.         }
  206.         return true;
  207.     }
  208.    
  209.     public static void addToProductLine(int index, int qtyToAdd, int qtyComplete, int qtyIncomplete) {
  210.         ArrayList<Products> temp = new ArrayList<Products>();
  211.         for(int i=0; i<qtyComplete; i++)
  212.             temp.add(new Products(productLineList.get(index).get(0).getProductLineName(), "COMPLETE"));
  213.         for(int i=0; i<qtyIncomplete; i++)
  214.             temp.add(new Products(productLineList.get(index).get(0).getProductLineName(), "INCOMPLETE"));
  215.         productLineList.get(index).addAll(temp);
  216.     }
  217.    
  218.     public static void renameProductLine(int index, String newname) {
  219.        
  220.     }
  221.     public static void deleteProductLine(int index) {
  222.          for(int i=0; i<componentList.size(); i++) {
  223.              if(componentList.get(i).getComponentHashMap().containsKey(index))
  224.                  componentList.get(i).getComponentHashMap().remove(index);
  225.          }
  226.          productLineList.remove(index);
  227.     }
  228.    
  229.     protected static void editSelProdRows(String status, String serial, String date, String loc, int[] selRows, int productLineIndex) {
  230.         for(int i=0; i<selRows.length; i++) {
  231.             if(!status.equalsIgnoreCase("(Status)"))
  232.                 productLineList.get(productLineIndex).get(selRows[i]).setProductLineStatus(status);
  233.             if(!serial.equalsIgnoreCase(""))
  234.                 productLineList.get(productLineIndex).get(selRows[i]).setProductSerial(serial);
  235.             if(!date.equalsIgnoreCase(""))
  236.                 productLineList.get(productLineIndex).get(selRows[i]).setProductMFGDate(date);
  237.             if(!loc.equalsIgnoreCase(""))
  238.                 productLineList.get(productLineIndex).get(selRows[i]).setProductMFGLoc(loc);
  239.         }
  240.     }
  241.    
  242.     public static void createNewComponent(String componentName, int componentQty, int[] plKeys, int[] plValues, String compDesc) {
  243.         componentList.add(new Components(componentName, componentQty, plKeys, plValues, compDesc));
  244.     }
  245.    
  246.     public static void createNewComponent(String componentName, int componentQty, int[] plKeys, int[] plValues, int shipQty, String compDesc) {
  247.         componentList.add(new Components(componentName, componentQty, plKeys, plValues, shipQty, compDesc));
  248.     }
  249.    
  250.     public static boolean checkExistingComponent(String compName) {
  251.         for (int i=0; i<componentList.size(); i++)
  252.             if(componentList.get(i).getComponentName().equalsIgnoreCase(compName))
  253.                 return false;
  254.         return true;
  255.     }
  256.    
  257.     public static ArrayList<Components> checkComponentsUsed(int index) {
  258.         ArrayList<Components> temp = new ArrayList<Components>();
  259.         for(int i=0; i<componentList.size(); i++) {
  260.             Iterator<Integer> iter = componentList.get(i).getComponentHashMap().keySet().iterator();
  261.             while(iter.hasNext()) {
  262.                 int currentElem = (Integer)iter.next();
  263.                 if(currentElem == (Integer)index)
  264.                     temp.add(componentList.get(i));
  265.             }
  266.         }
  267.         return temp;
  268.     }
  269.    
  270.     public static void createNewUser(String name, char[] pass) {
  271.         userList.add(new Users(name, pass));
  272.     }
  273.    
  274.     public static boolean authorizeUser(String name, char[] pass) {
  275.         int userIndex = 0;
  276.         boolean userExists = false;
  277.         //First check if user exists. If it doesnt then don't bother checking the pass just return false
  278.         for(int i=0; i<userList.size(); i++) {
  279.             if(userList.get(i).getUserName().equalsIgnoreCase(name)) {
  280.                 userIndex = i;
  281.                 userExists = true;
  282.                 break;
  283.             }
  284.         }
  285.         if(!userExists)
  286.             return false;
  287.        
  288.         //Name has been validated. Now check password.
  289.         byte[] bytePass = new byte[pass.length];
  290.         byte[] salt = userList.get(userIndex).getUserSalt();
  291.         byte[] digested = null;
  292.         String hashCheck = "";
  293.         for(int i=0; i<bytePass.length; i++)
  294.             bytePass[i] = (byte) pass[i];
  295.         MessageDigest md = null;
  296.         try {
  297.             md = MessageDigest.getInstance("SHA");
  298.         } catch(NoSuchAlgorithmException nsae) {    }
  299.        
  300.         md.update(salt);
  301.         md.update(bytePass);
  302.        
  303.         digested = md.digest();
  304.         for(int i=0; i<999; i++) {
  305.             md.reset();
  306.             digested = md.digest(digested);
  307.         }
  308.         for(int i=0; i<digested.length; i++)
  309.             hashCheck += (Integer.toHexString((0x000000ff & digested[i]) | 0xffffff00).substring(6));
  310.         if(userList.get(userIndex).getUserSHAHash().equals(hashCheck))
  311.             return true;
  312.         else
  313.             return false;
  314.     }
  315.    
  316.     public static boolean checkUserExists(String name) {
  317.         for(int i=0; i<userList.size(); i++) {
  318.             if(userList.get(i).getUserName().equalsIgnoreCase(name))
  319.                 return true;
  320.         }
  321.         return false;
  322.     }
  323.    
  324.     public static void saveDatabase(File file) {
  325.         ArrayList<Users> userListSave = userList;
  326.         ArrayList<ArrayList<Products>> productLineListSave = productLineList;
  327.         ArrayList<Components> componentListSave = componentList;
  328.         ObjectOutputStream fileOut = null;
  329.         try {
  330.             file.createNewFile();
  331.         } catch (IOException ioe) { }
  332.         if(file.canWrite() == false) {
  333.             showDialog(0, "Program does not have permission to write in current directory. Exit", zbFrame);
  334.             return;
  335.         }
  336.         try {
  337.             fileOut = new ObjectOutputStream(new FileOutputStream(file));
  338.         } catch(IOException ioe) {  }
  339.        
  340.         try {
  341.             fileOut.writeUTF("ZeroBull(tm) Inventory Master Database\t\t ZB_INVENTORY_BUILD_0700_ALPHA\t\t");
  342.             fileOut.writeUTF(getCurrentDate()+"\t\t");
  343.             fileOut.writeUTF("Begin Database\t\t");
  344.             fileOut.writeObject(userListSave);
  345.             fileOut.writeObject(productLineListSave);
  346.             fileOut.writeObject(componentListSave);
  347.             fileOut.writeUTF("\t\tEnd Database\t\t");
  348.             fileOut.close();
  349.         } catch(IOException ioe) {  }
  350.     }
  351.    
  352.     @SuppressWarnings("unchecked")
  353.     public static void loadUserDatabase(File customFile) {
  354.         ObjectInputStream fileIn = null;
  355.         //Try and load from main. If that fails use backup
  356.         if(customFile != null) {
  357.             try {
  358.                 fileIn = new ObjectInputStream(new FileInputStream(customFile));
  359.             } catch(IOException ioe) {  }
  360.         }
  361.        
  362.         else {
  363.             if(masterDBFile.exists() == true) {
  364.                 try {
  365.                     fileIn = new ObjectInputStream(new FileInputStream(masterDBFile));
  366.                 } catch(IOException ioe) {  }
  367.             }
  368.            
  369.             else if(masterDBFileBackup.exists() == true) {
  370.                 try {
  371.                     fileIn = new ObjectInputStream(new FileInputStream(masterDBFileBackup));
  372.                 } catch(IOException ioe) {  }
  373.             }
  374.         }
  375.  
  376.         try {
  377.             fileIn.readUTF();
  378.             fileIn.readUTF();
  379.             fileIn.readUTF();
  380.             userList = (ArrayList<Users>) fileIn.readObject();
  381.             fileIn.close();
  382.         } catch(Exception invalidDB) {
  383.             showDialog(0, "Invalid database file!", zbFrame);
  384.             }
  385.     }
  386.    
  387.     @SuppressWarnings("unchecked")
  388.     public static void loadDatabase(File customFile) {
  389.         //Must clear user ArrayList first since it was [supposedly] already loaded.
  390.         userList.clear();
  391.         ObjectInputStream fileIn = null;
  392.         //Try main database first. If file does not exist load backup. If that fails then throw error message and let user select a database.
  393.         if(customFile != null) {
  394.             try {
  395.                 fileIn = new ObjectInputStream(new FileInputStream(customFile));
  396.             } catch(IOException ioe) {  }
  397.         }
  398.         else {
  399.             if(masterDBFile.exists() == true) {
  400.                 try {
  401.                     fileIn = new ObjectInputStream(new FileInputStream(masterDBFile));
  402.                 } catch(IOException ioe) {  }
  403.             }
  404.             else if(masterDBFileBackup.exists() == true) {
  405.                 try {
  406.                     fileIn = new ObjectInputStream(new FileInputStream(masterDBFileBackup));
  407.                 } catch(IOException ioe) {  }
  408.             }
  409.         }
  410.         try {
  411.             fileIn.readUTF();
  412.             fileIn.readUTF();
  413.             fileIn.readUTF();
  414.             userList = (ArrayList<Users>) fileIn.readObject();
  415.             productLineList = (ArrayList<ArrayList<Products>>) fileIn.readObject();
  416.             componentList = (ArrayList<Components>) fileIn.readObject();
  417.             fileIn.readUTF();
  418.             fileIn.close();
  419.         } catch(Exception ignore) { }
  420.     }
  421.    
  422.     protected static void flushDatabases() {
  423.         userList.clear();
  424.         productLineList.clear();
  425.         componentList.clear();
  426.     }
  427.    
  428.     public static void setForceSaveAs() {
  429.         forceSaveAs = true;
  430.     }
  431.    
  432.     public static int saveBeforeExit() {
  433.         int option = JOptionPane.showConfirmDialog(null, "Save before exiting?", "Save", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE);
  434.         if(option == JOptionPane.YES_OPTION) {
  435.             if(!forceSaveAs) {
  436.                 if (userLoadedFile != null)
  437.                     saveDatabase(userLoadedFile);
  438.                 else {
  439.                     saveDatabase(masterDBFile);
  440.                     saveDatabase(masterDBFileBackup);
  441.                 }
  442.                 return 0;
  443.             }
  444.             else {
  445.                 forceSave = new JFileChooser("Save As...");
  446.                 forceSave.setFileFilter(new FileFilter() {
  447.                     public boolean accept(File saveFile) {
  448.                         return saveFile.getName().toLowerCase().endsWith(".zbdb") || saveFile.isDirectory();
  449.                     }
  450.                    
  451.                     public String getDescription() {
  452.                         return "ZeroBull Database";
  453.                     }
  454.                 });
  455.                 int saveReturn = forceSave.showSaveDialog(null);
  456.                 if(saveReturn == JFileChooser.APPROVE_OPTION) {
  457.                     if (Main.productLineList.isEmpty() && Main.componentList.isEmpty() && Main.userList.isEmpty())
  458.                         JOptionPane.showMessageDialog(null, "Can not save an empty database!", "Error!", JOptionPane.ERROR_MESSAGE);
  459.                     else {
  460.                         String savePath = forceSave.getSelectedFile().getPath() +".zbdb";
  461.                         saveDatabase(new File(savePath));
  462.                     }
  463.                 }
  464.             }
  465.         }
  466.         else if(option == JOptionPane.NO_OPTION)
  467.             return 0;
  468.         else if(option == JOptionPane.CANCEL_OPTION)
  469.             return 1;
  470.         return 0;
  471.     }
  472.    
  473.     public static String getCurrentDate() {
  474.         DateFormat date = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
  475.         Date currentDate = new Date();
  476.         return date.format(currentDate);
  477.     }
  478.    
  479.     private static void showDialog(int level, String message, JFrame owner) {
  480.         switch(level) {
  481.         case 0:
  482.             JOptionPane.showMessageDialog(owner, message, "Error", JOptionPane.ERROR_MESSAGE); break;
  483.         case 1:
  484.             JOptionPane.showMessageDialog(owner, message, "Warning", JOptionPane.WARNING_MESSAGE); break;
  485.         case 2:
  486.             JOptionPane.showMessageDialog(owner, message, "Message", JOptionPane.INFORMATION_MESSAGE); break;
  487.         }
  488.     }
  489. }
  490.  
  491. class outWriter {
  492.     //This awesome class here allows me to write to the log file from ANYWHERE.
  493.     private static final File logFile = new File("log.txt");
  494.     private static BufferedWriter logOut = null;
  495.    
  496.     public static boolean initialize() {
  497.         try {
  498.             if(logOut == null) {
  499.                 logOut = new BufferedWriter(new FileWriter(logFile, true));
  500.                 return true;
  501.             }
  502.         } catch(IOException ioe) { }
  503.         return false;
  504.     }
  505.    
  506.     public static boolean write (String out, boolean close) {
  507.         try {
  508.             if(out != null && logOut != null) {
  509.                 logOut.write(out +"\r\n");
  510.                 return true;
  511.             }
  512.         } catch(IOException ioe) { }
  513.         return false;
  514.     }
  515.    
  516.     public static boolean close() {
  517.         try {
  518.             if(logOut != null) {
  519.                 logOut.close();
  520.                 return true;
  521.             }
  522.         } catch(IOException ioe) { }
  523.         return false;
  524.     }
  525. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement