Assignment Brief:
Assignment 2 should be a simple Model View Controller application which has the following data
model. All data should be persisted to a MySQL database.
Download full brief here
Download zip of all source code for 'CallCenter' here

MainApplication is the main class (gui folder):
Download source code for 'MainApplication' here

// Start of code---------------------
package gui;

import model.persistors.DatabaseFilePersistor;
import controller.ContactsController;
import controller.PersistanceMode;

/* Usage notes:
 * Redistribution, alteration and use of this code with or without
 * modification, are permitted provided that the following conditions are met:
 * In no event shall the copyright owner be liable for any direct, indirect,
 * incidental, special, exemplary, or consequential damages arising in any
 * way out of the use of this software, even if advised of the possibility
 * of such damage.
 */


public class MainApplication {

    public static void main(String[] args) {

        ContactsController.getInstance().setPersistor(
                new DatabaseFilePersistor());
        ContactsController.getInstance().setPersistenceMode(
                PersistanceMode.DATABASE);
        ContactsController.getInstance().init();

        ContactAndCallFrame contactCallFrame = new ContactAndCallFrame(
                "Contact and Call History");
        contactCallFrame.setSize(500, 400);
        contactCallFrame.setVisible(true);
        contactCallFrame.setResizable(false);

        ContactsController.getInstance().setView(contactCallFrame);

    }

}//End of code---------------------

ContactAndCallFrame class(gui folder):
Download source code for 'ContactAndCallFrame' here

// Start of code---------------------
package gui;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;

import controller.ContactsController;

import model.Contact;

/* Usage notes:
 * Redistribution, alteration and use of this code with or without
 * modification, are permitted provided that the following conditions are met:
 * In no event shall the copyright owner be liable for any direct, indirect,
 * incidental, special, exemplary, or consequential damages arising in any
 * way out of the use of this software, even if advised of the possibility
 * of such damage.
 */


public class ContactAndCallFrame extends JFrame {
    private JPanel mainPanel;
    private JButton addContact;
    private JButton deleteContact;
    private JButton updateContact;
    private JButton showCallHistory;
    private JButton exitButton;
    private JLabel contactLabel;
    private ContactsTableModel tableModel;

    private JTable table;

    public ContactAndCallFrame(String title) {
        super(title);
        this.mainPanel = new JPanel();
        this.mainPanel.setLayout(new BorderLayout());
        this.getContentPane().add(this.mainPanel);
        this.mainPanel.add(createSidePanel(), BorderLayout.EAST);
        this.mainPanel.add(createTopPanel(), BorderLayout.NORTH);
        this.mainPanel.add(createTable(ContactsController.getInstance()
                .getContacts()), BorderLayout.CENTER);
        this.mainPanel.add(createBottomPanel(), BorderLayout.SOUTH);
    }

    //Create side panel buttons
    private JPanel createSidePanel() {
        JPanel sidePanel = new JPanel();

        BoxLayout boxLeft = new BoxLayout(sidePanel, BoxLayout.Y_AXIS);
        sidePanel.setLayout(boxLeft);

        addContact = new JButton("Add Contact");
        deleteContact = new JButton("Delete Contact");
        updateContact = new JButton("Update Contact");
        showCallHistory = new JButton("Show call history");

        // Setting up add contact button action listener
        AddButtonListener addButton = new AddButtonListener(this);
        addContact.addActionListener(addButton);

        //Action listener for delete contact button
        deleteContact.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {

                JFrame outerFrame = (JFrame) getRootPane().getParent();

                int selectedRow = table.getSelectedRow();
                if (selectedRow >= 0) {
                    ContactsController.getInstance().deleteContact(selectedRow);
                } else {
                    String quitMessage = "WARNING - You must select a contact to delete contact details.";
                    JOptionPane.showMessageDialog(outerFrame, quitMessage);
                }

            }
        });

        //Action listener for updating contact button
        updateContact.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {

                JFrame outerFrame = (JFrame) getRootPane().getParent();

                int selectedIndex = table.getSelectedRow();
                if (selectedIndex >= 0) {
                    Contact selectedContact = ContactsController.getInstance()
                            .getContacts().get(selectedIndex);

                    AddContactDialog addContactDialog = new AddContactDialog(
                            outerFrame, "Edit Contact", selectedContact);
                    addContactDialog.setSize(500, 250);
                    addContactDialog.setVisible(true);
                } else {
                    String quitMessage = "WARNING - You must select a contact to update contact details.";
                    JOptionPane.showMessageDialog(outerFrame, quitMessage);
                }

            }
        });

        //Action listener for showing call history button
        showCallHistory.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                JFrame outerFrame = (JFrame) getRootPane().getParent();

                int selectedIndex = table.getSelectedRow();
                if (selectedIndex >= 0) {
                    Contact selectedContact = ContactsController.getInstance()
                            .getContacts().get(selectedIndex);

                    // Launch the Add Competitor dialog

                    ShowCallsDialog showCallsDialog = new ShowCallsDialog(
                            outerFrame, "Call History", selectedContact.getName());
                    showCallsDialog.setSize(500, 100);
                    showCallsDialog.setVisible(true);
                } else {
                    String quitMessage = "WARNING - You must select a contact to show call history.";
                    JOptionPane.showMessageDialog(outerFrame, quitMessage);
                }

            }
        });

        sidePanel.add(addContact);
        sidePanel.add(deleteContact);
        sidePanel.add(updateContact);
        sidePanel.add(showCallHistory);

        return sidePanel;
    }

    private JPanel createTopPanel()

    {
        JPanel topPanel = new JPanel();

        contactLabel = new JLabel("Contact details");

        topPanel.add(contactLabel);

        return topPanel;
    }

    private JScrollPane createTable(ArrayList<Contact> contacts) {
        table = new JTable();
        tableModel = new ContactsTableModel(contacts);
        table.setModel(tableModel);

        JScrollPane scroller = new JScrollPane(table);
        return scroller;
    }

    public void refreshTable() {
        this.tableModel.fireTableDataChanged();
    }
   
    private class AddButtonListener implements ActionListener {
        private JFrame outerFrame;

        public AddButtonListener(JFrame outerFrame) {
            this.outerFrame = outerFrame;
        }

        public void actionPerformed(ActionEvent e) {
       
            AddContactDialog addCompetitorDialog = new AddContactDialog(
                    outerFrame, "Add Contact");
            addCompetitorDialog.setSize(500, 250);
            addCompetitorDialog.setVisible(true);
        }
    }

    private JPanel createBottomPanel() {
        JPanel bottomPanel = new JPanel();

        exitButton = new JButton("Exit");
        bottomPanel.add(exitButton);
        exitButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JFrame outerFrame = (JFrame) getRootPane().getParent();

                String quitMessage = "Do you want to quit?";
                int answer = JOptionPane.showConfirmDialog(outerFrame,
                        quitMessage);
                if (answer == JOptionPane.YES_OPTION) {
                    System.exit(0); // User clicked YES - Close appliaction
                } else if (answer == JOptionPane.NO_OPTION) {
                    // User clicked NO or CANCEL - return to application
                }
            }

        });
        return bottomPanel;
    }
}//End of code---------------------

ContactsTableModel class(gui folder):
Download source code for 'ContactsTableModel' here

// Start of code---------------------
package gui;

import java.util.ArrayList;
import javax.swing.table.DefaultTableModel;

import model.Contact;

/* Usage notes:
 * Redistribution, alteration and use of this code with or without
 * modification, are permitted provided that the following conditions are met:
 * In no event shall the copyright owner be liable for any direct, indirect,
 * incidental, special, exemplary, or consequential damages arising in any
 * way out of the use of this software, even if advised of the possibility
 * of such damage.
 */


public class ContactsTableModel extends DefaultTableModel
{
    private static final int NO_OF_COLS = 2;
   
    //These are the indices of the table columns
    private static final int NAME_COL = 0;
    private static final int PHONE_NUM_COL = 1;
   
    private ArrayList<Contact> contacts;
   
    public ContactsTableModel(ArrayList<Contact> contacts)
    {
        super();
        this.contacts = contacts;
    }

    //We are overriding the getColumnCount() method from superclass
    public int getColumnCount()
    {
        return NO_OF_COLS;
    }
    //We are overriding the getColumnCount() method from superclass   
    public String getColumnName(int column)
    {
        if(column == NAME_COL)
        {
            return "Name";
        }
        else if(column == PHONE_NUM_COL)
        {
            return "Phone Number";
        }
        else
        {
            return "";
        }
    }
    //We are overriding the getColumnCount() method from superclass   
    public int getRowCount()
    {
        if(this.contacts != null)
        {
            return this.contacts.size();
        }
        else
        {   
            return 0;
        }
    }
   
    public Object getValueAt(int row, int col)
    {
       
        Contact contactsToGet = this.contacts.get(row);
        if(col == NAME_COL)
        {
            return contactsToGet.getName();
        }
        else if(col == PHONE_NUM_COL)
        {
            return contactsToGet.getPhoneNumber();
        }
        else
        {
            return "";
        }
    }
   
}//End of code---------------------

AddContactDialog class(gui folder):
Download source code for 'AddContactDialog' here

// Start of code---------------------
package gui;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

import model.Contact;

import controller.ContactsController;

/* Usage notes:
 * Redistribution, alteration and use of this code with or without
 * modification, are permitted provided that the following conditions are met:
 * In no event shall the copyright owner be liable for any direct, indirect,
 * incidental, special, exemplary, or consequential damages arising in any
 * way out of the use of this software, even if advised of the possibility
 * of such damage.
 */


public class AddContactDialog extends JDialog {
    private enum Mode {
        ADD, EDIT
    };

    private JPanel mainPanel;
    private JLabel nameLabel;
    private JTextField nameField;
    private JLabel phoneNumberLabel;
    private JTextField phoneNumberField;
    private JButton okButton;
    private JButton cancelButton;

    private Mode dialogMode;

    private Contact contactBeingEdited;

    public AddContactDialog(JFrame parent, String title, Contact c) {
        this(parent, title);
        this.contactBeingEdited = c;
        this.nameField.setText(c.getName());
        this.phoneNumberField.setText(c.getPhoneNumber());
        dialogMode = Mode.EDIT;
    }

    public AddContactDialog(JFrame parent, String title) {
        super(parent, title);
        this.mainPanel = new JPanel();
        BoxLayout boxL = new BoxLayout(this.mainPanel, BoxLayout.Y_AXIS);
        this.mainPanel.setLayout(boxL);
        this.getContentPane().add(this.mainPanel);

        this.mainPanel.add(createNamePanel());
        this.mainPanel.add(createPhoneNumberPanel());
        this.mainPanel.add(createButtonPanel());
        dialogMode = Mode.ADD;
    }

    private JPanel createNamePanel() {
        JPanel namePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        nameLabel = new JLabel("Name: ");
        nameField = new JTextField(30);
        namePanel.add(nameLabel);
        namePanel.add(nameField);
        return namePanel;
    }

    private JPanel createPhoneNumberPanel() {
        JPanel phoneNumberPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        phoneNumberLabel = new JLabel("Phone Number: ");

        phoneNumberField = new JTextField(8);
        phoneNumberPanel.add(phoneNumberLabel);
        phoneNumberPanel.add(phoneNumberField);
        return phoneNumberPanel;
    }


    private JPanel createButtonPanel() {
        JPanel buttonPanel = new JPanel();
        okButton = new JButton("OK");

        okButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (dialogMode == Mode.ADD) {
                    ContactsController.getInstance().createNewContact(
                            nameField.getText(), phoneNumberField.getText());
                } else if (dialogMode == Mode.EDIT) {
                    ContactsController.getInstance().updateContact(
                            contactBeingEdited.getName(), nameField.getText(),
                            phoneNumberField.getText());
                }
                dispose();
            }
        });
        cancelButton = new JButton("Cancel");

        buttonPanel.add(okButton);
        buttonPanel.add(cancelButton);
        return buttonPanel;
    }

}//End of code---------------------

ShowCallsDialog class(gui folder):
Download source code for 'ShowCallsDialog' here

// Start of code---------------------
package gui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Calendar;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

import controller.ContactsController;

import model.Call;

/* Usage notes:
 * Redistribution, alteration and use of this code with or without
 * modification, are permitted provided that the following conditions are met:
 * In no event shall the copyright owner be liable for any direct, indirect,
 * incidental, special, exemplary, or consequential damages arising in any
 * way out of the use of this software, even if advised of the possibility
 * of such damage.
 */


public class ShowCallsDialog extends JDialog {

    private JComboBox callCombo;
    private JButton addCallButton;
    private JPanel mainPanel;
    private String selectedContactName;

    public ShowCallsDialog(JFrame parent, String title,
            String selectedContactName) {
        super(parent, title);
        this.mainPanel = new JPanel();
        this.selectedContactName = selectedContactName;
        BoxLayout boxL = new BoxLayout(this.mainPanel, BoxLayout.Y_AXIS);
        this.mainPanel.setLayout(boxL);
        this.getContentPane().add(this.mainPanel);
        this.mainPanel.add(createCallComboPanel());

    }

    private JPanel createCallComboPanel() {
        JPanel callComboPanel = new JPanel();
        callCombo = new JComboBox();
        populateCallsCombo();
        callComboPanel.add(callCombo);
        addCallButton = new JButton("Add Call...");
        addCallButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                String callDuration = JOptionPane
                        .showInputDialog("Call Duration :");
                if (callDuration.length() > 0) {
                    ContactsController.getInstance().addCallForContact(
                            selectedContactName,
                            Calendar.getInstance().getTime(), callDuration);
                } else {
                    // Show error dialog
                }
            }
        });
       
        callComboPanel.add(addCallButton);
        return callComboPanel;
    };

    public void populateCallsCombo() {
        callCombo.removeAll();
        ArrayList<Call> callsForContact = ContactsController.getInstance()
                .getCallsForContact(selectedContactName);

        for (Call currCall : callsForContact) {
            callCombo.addItem(currCall);
        }

    }
}//End of code---------------------

ContactAndCallModel class(model folder):
Download source code for 'ContactAndCallModel' here

// Start of code---------------------
package model;

import java.util.ArrayList;

/* Usage notes:
 * Redistribution, alteration and use of this code with or without
 * modification, are permitted provided that the following conditions are met:
 * In no event shall the copyright owner be liable for any direct, indirect,
 * incidental, special, exemplary, or consequential damages arising in any
 * way out of the use of this software, even if advised of the possibility
 * of such damage.
 */


public class ContactAndCallModel
{
   
   private ArrayList<Contact> contacts;
  
  
   public ContactAndCallModel()
   {
      this.contacts= new ArrayList<Contact>();
   }
  
   public ContactAndCallModel(ArrayList<Contact> contacts)
   {
       this.contacts = contacts;
   }
  
   public void addContact(Contact c)
   {
      this.contacts.add(c);
   }
  
   public ArrayList<Contact> getContacts()
   {
       return this.contacts;
   }
  
}//End of code---------------------

Call class (model folder):
Download source code for 'Call' here

// Start of code---------------------
package model;

import java.util.Date;

/* Usage notes:
 * Redistribution, alteration and use of this code with or without
 * modification, are permitted provided that the following conditions are met:
 * In no event shall the copyright owner be liable for any direct, indirect,
 * incidental, special, exemplary, or consequential damages arising in any
 * way out of the use of this software, even if advised of the possibility
 * of such damage.
 */


public class Call {

    private String name;
    private Date dayAndTime;
    private String durationSecs;
       
    public Call(String name, Date dayAndTime, String durationSecs)
    {
        this.name = name;
        this.dayAndTime = dayAndTime;
        this.durationSecs = durationSecs;
    }
       
   
    public String getName() {
        return name;
    }


    public void setName(String name) {
        this.name = name;
    }


    public Date getDayAndTime() {
        return dayAndTime;
    }


    public void setDayAndTime(Date dayAndTime) {
        this.dayAndTime = dayAndTime;
    }


    public String getDurationSecs() {
        return durationSecs;
    }


    public void setDurationSecs(String durationSecs) {
        this.durationSecs = durationSecs;
    }


    public String toString()
    {
        return this.name + "  -  " + this.dayAndTime + "  -  "+ this.durationSecs;
    }
}//End of code---------------------

Contact class:
Download source code for 'Contact' here

// Start of code---------------------
package model;

import java.util.ArrayList;

/* Usage notes:
 * Redistribution, alteration and use of this code with or without
 * modification, are permitted provided that the following conditions are met:
 * In no event shall the copyright owner be liable for any direct, indirect,
 * incidental, special, exemplary, or consequential damages arising in any
 * way out of the use of this software, even if advised of the possibility
 * of such damage.
 */


public class Contact
{
   
private String name;
private String phoneNumber;

ArrayList<Call> callHistory = new ArrayList<Call>();

public Contact(String name, String phoneNumber)
{
    this.name = name;
    this.phoneNumber = phoneNumber;
}

public String getName()
{
    return name;
   
}
public void setName(String name) {
    this.name = name;
}

public String getPhoneNumber()
{
    return phoneNumber;
}

public void setPhoneNumber(String phoneNumber) {
    this.phoneNumber = phoneNumber;
}

}//End of code---------------------

DatabaseFilePersistor class (persisters folder inside model folder):
Download source code for 'DatabaseFilePersistor' here

// Start of code---------------------
package model.persistors;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Calendar;

import model.Call;
import model.Contact;

/* Usage notes:
 * Redistribution, alteration and use of this code with or without
 * modification, are permitted provided that the following conditions are met:
 * In no event shall the copyright owner be liable for any direct, indirect,
 * incidental, special, exemplary, or consequential damages arising in any
 * way out of the use of this software, even if advised of the possibility
 * of such damage.
 */


public class DatabaseFilePersistor implements IPersistor {

    private Connection dbConnection;
    private ArrayList<AutoCloseable> dbObjects;

    private static final String DB_NAME_COL = "name";
    private static final String DB_PHONE_NUM_COL = "phoneNumber";

    private static final String DB_DATE_COL = "dateandtime";
    private static final String DB_DURATION_COL = "callduration";

    // Setting up connection to database - I have taken out the password because
    // I could not connect to database
    public DatabaseFilePersistor() {
        dbObjects = new ArrayList<AutoCloseable>();
        try {
            Class.forName("com.mysql.jdbc.Driver");

            dbConnection = DriverManager
                    .getConnection("jdbc:mysql://localhost/phonebook?"
                            + "user=root&password=");
            System.out.println("Database connection successful : "
                    + dbConnection);
        } catch (ClassNotFoundException cnfe) {
            cnfe.printStackTrace();
            System.out.println(cnfe.getMessage());
        }

        catch (SQLException sqlEx) {
            sqlEx.printStackTrace();
            System.out.println(sqlEx.getMessage());
        }

    }

    public void write(ArrayList<Contact> contacts) {
        try {
            for (Contact currContact : contacts) {
                PreparedStatement prepStmt = dbConnection
                        .prepareStatement("INSERT into CONTACT values (?,?)");

                prepStmt.setString(1, currContact.getName());
                prepStmt.setString(2, currContact.getPhoneNumber());

                prepStmt.executeUpdate();
                dbObjects.add(prepStmt);

            }
            close();
        } catch (SQLException sqlEx) {
            System.out.println(sqlEx.getMessage());
        }

    }

    public void close() {
        try {
            for (AutoCloseable curr : dbObjects) {
                curr.close();
            }
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
    }

    public ArrayList<Contact> read() {
        ArrayList<Contact> contacts = new ArrayList<Contact>();
        try {
            Statement getAllContacts = dbConnection.createStatement();
            dbObjects.add(getAllContacts);
            ResultSet rs = getAllContacts.executeQuery("SELECT * from CONTACT");
            dbObjects.add(rs);

            while (rs.next()) {
                String currContactName = rs.getString(DB_NAME_COL);
                String currContactPhoneNumber = rs.getString(DB_PHONE_NUM_COL);

                Contact recreatedContact = new Contact(currContactName,
                        currContactPhoneNumber);
                contacts.add(recreatedContact);
            }

        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        } finally {
            close();
            return contacts;
        }
    }

    @Override
    public ArrayList<Call> getCallsForContact(String contactName) {
        ArrayList<Call> calls = new ArrayList<Call>();
        try {
            PreparedStatement getAllCalls = dbConnection
                    .prepareStatement("SELECT * FROM CALLS WHERE name=?");
            getAllCalls.setString(1, contactName);
            ResultSet rs = getAllCalls.executeQuery();

            while (rs.next()) {
                String currCallContactName = rs.getString(DB_NAME_COL);
                String currCallDate = rs.getString(DB_DATE_COL);
                String currCallDuration = rs.getString(DB_DURATION_COL);

                long timeInMillis = Long.parseLong(currCallDate);
                Calendar c = Calendar.getInstance();
                c.setTimeInMillis(timeInMillis);
                Call e = new Call(currCallContactName, c.getTime(),
                        currCallDuration);
                calls.add(e);
            }

            getAllCalls.close();
            rs.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            return calls;
        }
    }

    // Add a call to list for a selected contact
    public void addCallForContact(Call newCall) {

        try {
            PreparedStatement prepStmt = dbConnection
                    .prepareStatement("INSERT into CALLS values (? ,?, ?)");

            prepStmt.setString(1, newCall.getName());
            prepStmt.setString(2,
                    Long.toString(newCall.getDayAndTime().getTime()));
            prepStmt.setString(3, newCall.getDurationSecs());

            prepStmt.executeUpdate();
            dbObjects.add(prepStmt);
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
            ex.printStackTrace();
        } finally {
            close();
        }

    }

    // Delete a contact after a name is selected
    public void delete(String name) {
        try {
            PreparedStatement deleteContactStmt = dbConnection
                    .prepareStatement("DELETE from CONTACT WHERE name=?");
            dbObjects.add(deleteContactStmt);
            deleteContactStmt.setString(1, name);
            deleteContactStmt.executeUpdate();
            PreparedStatement deleteCallsStmt = dbConnection
                    .prepareStatement("DELETE from CALLS WHERE name=?");
            dbObjects.add(deleteCallsStmt);
            deleteCallsStmt.setString(1, name);
            deleteCallsStmt.executeUpdate();
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        } finally {
            close();
        }

    }

    // Update a contact after a name is selected
    public void update(String originalName, String newName,
            String newPhoneNumber) {
        try {
            PreparedStatement prepStmt = dbConnection
                    .prepareStatement("UPDATE CONTACT SET name=?, phonenumber=? WHERE name=?");
            dbObjects.add(prepStmt);
            prepStmt.setString(1, newName);
            prepStmt.setString(2, newPhoneNumber);
            prepStmt.setString(3, originalName);

            prepStmt.executeUpdate();

        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        } finally {
            close();
        }
    }
}//End of code---------------------

IPersistor  interface (persisters folder inside model folder):
Download source code for 'IPersistor' here

// Start of code---------------------
package model.persistors;

import java.util.ArrayList;

import model.Call;
import model.Contact;
/* Usage notes:
 * Redistribution, alteration and use of this code with or without
 * modification, are permitted provided that the following conditions are met:
 * In no event shall the copyright owner be liable for any direct, indirect,
 * incidental, special, exemplary, or consequential damages arising in any
 * way out of the use of this software, even if advised of the possibility
 * of such damage.
 */


public interface IPersistor
{
    public void write(ArrayList<Contact> contacts);
  
    public ArrayList<Contact> read();
  
    public void delete(String name);
  
    public void update(String originalName, String newName, String newPhoneNumber);

    public ArrayList<Call> getCallsForContact(String competitorName);

    public void addCallForContact(Call newCall);
}//End of code---------------------

ContactsController class (controller folder):
Download source code for 'ContactsController' here

// Start of code---------------------
package controller;

import gui.ContactAndCallFrame;

import java.util.ArrayList;
import java.util.Date;

import model.Call;
import model.Contact;
import model.ContactAndCallModel;

import model.persistors.IPersistor;

/* Usage notes:
 * Redistribution, alteration and use of this code with or without
 * modification, are permitted provided that the following conditions are met:
 * In no event shall the copyright owner be liable for any direct, indirect,
 * incidental, special, exemplary, or consequential damages arising in any
 * way out of the use of this software, even if advised of the possibility
 * of such damage.
 */


public class ContactsController
{
   private static ContactsController instance;
   private ContactAndCallModel dataModel;
   private ContactAndCallFrame view;
 
   private PersistanceMode persistenceMode;
   
   private IPersistor persistor;

 
   public static ContactsController getInstance()
   {
      if(instance == null)
      {
         instance = new ContactsController();
      }
      return instance;
   }
 
 
   public void init()
   {
       try
       {
           ArrayList<Contact> contacts = this.persistor.read();
         
           if(contacts != null)
           {
               ContactAndCallModel dataModel = new ContactAndCallModel(contacts);
               this.setModel(dataModel);
           }
           else
           {
               this.setModel(new ContactAndCallModel());
           }
       }
       catch(Exception ex)
       {
           System.out.println(ex.getMessage());
         
           this.setModel(new ContactAndCallModel());
       }
   }
 
   private void setModel(ContactAndCallModel dataModel)
   {
      this.dataModel = dataModel;
   }

   public void setPersistor(IPersistor persistor)
   {
      this.persistor = persistor;
    
   }

   public void setView(ContactAndCallFrame view)
   {
       this.view = view;
   }
 
   public void setPersistenceMode(PersistanceMode persistenceMode)
   {
       this.persistenceMode = persistenceMode;
   }
 
   public void createNewContact(String name, String phoneNumber)
   {
      Contact newContact = null;
      newContact = new Contact(name, phoneNumber);
          
      this.dataModel.addContact(newContact);
      switch(this.persistenceMode)
      {
          case DATABASE :
          {
                ArrayList<Contact> contactWrapper = new ArrayList<Contact>();
              contactWrapper.add(newContact);
              this.persistor.write(contactWrapper);
              break;
          }
      }
      this.view.refreshTable();
   }
    
   public ArrayList<Contact> getContacts()
   {
      return this.dataModel.getContacts();
   }
 
   public void deleteContact(int selectedIndex)
   {
       Contact removedContact =
               this.dataModel.getContacts().remove(selectedIndex);
     
       this.persistor.delete(removedContact.getName());
     
       this.view.refreshTable();
   }
 
   public void updateContact(String originalName, String newName, String newPhoneNumber)
   {
    
       for(Contact currContact : this.dataModel.getContacts())
       {
           if(currContact.getName().equals(originalName))
           {
               currContact.setName(newName);
               currContact.setPhoneNumber(newPhoneNumber);
           }
       }
       this.persistor.update(originalName, newName, newPhoneNumber);
       this.view.refreshTable();
   }
 
    public ArrayList<Call> getCallsForContact(String contactName)
   {
       return this.persistor.getCallsForContact(contactName);
   }
 
   public void addCallForContact(String contactName, Date dayAndTime, String durationSecs)
   {
       Call c = new Call(contactName, dayAndTime, durationSecs);
       this.persistor.addCallForContact(c);
   } 
}//End of code---------------------

PersistanceMode enum (controller folder):
Download source code for 'PersistanceMode' here

// Start of code---------------------
package controller;
/* Usage notes:
 * Redistribution, alteration and use of this code with or without
 * modification, are permitted provided that the following conditions are met:
 * In no event shall the copyright owner be liable for any direct, indirect,
 * incidental, special, exemplary, or consequential damages arising in any
 * way out of the use of this software, even if advised of the possibility
 * of such damage.
 */


public enum PersistanceMode {
    DATABASE;
}//End of code---------------------

0 comments:

Post a Comment

Please feel free to leave comments or ask questions related to the tutorials.