Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

This is from Murach Java programming Project. NetBeans Instructions will also be

ID: 3846969 • Letter: T

Question

This is from Murach Java programming Project. NetBeans Instructions will also be very helpfu, Thanks so much.

Console

Welcome to the Customer Maintenance application

COMMAND MENU

list    - List all customers

add     - Add a customer

del     - Delete a customer

help    - Show this menu

exit    - Exit this application

Enter a command: list

CUSTOMER LIST

frank46@hotmail.com               Frank              Jones

sarah_smith@yahoo.com             Sarah              Smith

Enter a command: add

Enter customer email address: xml_test@gm'ail.com

Enter first name: XML

Enter last name: Test

XML Test was added to the database.

Enter a command: list

CUSTOMER LIST

frank44@hotmail.com               Frank              Jones

sarah_smith@yahoo.com             Sarah              Smith

xml_test@gm'ail.com                XML                Test

Enter a command: del

Enter customer email to delete: xml_test@gm'ail.com

XML Test was deleted from the database.

Enter a command: list

CUSTOMER LIST

frank44@hotmail.com                Frank               Jones

sarah_smith@yahoo.com              Sarah               Smith

Enter a command: exit

Bye.

Operation

This application begins by displaying a menu with five choices: list, add, del, help, and exit.

If the user enters “list”, the application displays the customer data that’s stored in an XML file.

If the user enters “add”, the application prompts the user to enter data for a customer and saves that data to the XML file.

If the user enters “del”, the application prompts the user for an email address and deletes the corresponding customer from the XML file.

If the user enters “help”, the application displays the menu again.

If the user enters “exit”, the application displays a goodbye message and exits.

Specifications

Create a class named Customer that stores data for the user’s email address, first name, and last name.

Use a text editor to create an XML file named customers.xml in the same directory as the Customer class. This file should contain valid XML tags for at least one customer. For example:

<?xml version="1.0" encoding="UTF-8"?>
<Customers>
<Customer Email="frank44@hotmail.com">
<FirstName>Frank</FirstName>
<LastName>Jones</LastName>
</Customer>
</Customers>

Create a class named CustomerXMLFile that reads the customers.xml file when it’s instantiated. This class should include a public method that return an array list of Customer objects created from the data in the file, a public method that returns a Customer object for a specified email address, and public methods for adding and deleting records. Include any additional private methods that you need to perform these functions.

Create a CustomerMaintApp class that works as shown in the console output. This class should use the Customer and CustomerXMLFile classes to work with Customer data.

Use spaces to align the customer data in columns on the console. To do that, you can create a utility class named StringUtils that has a method that adds the necessary spaces to a string to reach a specified length.

Use the Validator class or a variation of it to validate the user’s entries. Non-empty strings are required for the email address, first name, and last name.

Add an “update” command that lets the user update an existing customer. This command should prompt the user to enter the email address for a customer. Then, it should let the user update the first name and last name for the customer.

Add a method to the Validator class that uses string parsing techniques to validate the email address. At the least, you can check to make sure that this string contains some text, followed by an @ sign, followed by some more text, followed by a period, followed by some more text. For example, “x@x.x” would be valid while “xxx” or “x@x” would not.

Use an interface to eliminate any direct calls to the CustomerXMLFile class from the CustomerMaintApp class. To do that, you can use CustomerReader, CustomerWriter, CustomerConstants, and CustomerDAO interfaces as well as a DAOFactory class as described in project 19-3. Then, you can modify the CustomerXMLFile and CustomerMaintApp classes so they use these interfaces and class.

Explanation / Answer

CustomerMaintApp.java


import java.util.Scanner;
import java.util.ArrayList;

public class CustomerMaintApp implements CustomerConstants
{
    // declare two class variables
    private static CustomerDAO customerDAO = null;
    private static Scanner sc = null;

    public static void main(String args[])
    {
        // display a welcome message
        System.out.println("Welcome to the Customer Maintenance application ");

        // set the class variables
        customerDAO = DAOFactory.getCustomerDAO();
        sc = new Scanner(System.in);

        // display the command menu
        displayMenu();

        // perform 1 or more actions
        String action = "";
        while (!action.equalsIgnoreCase("exit"))
        {
            // get the input from the user
            action = Validator.getString(sc,
                    "Enter a command: ");
            System.out.println();

            if (action.equalsIgnoreCase("list"))
                displayAllCustomers();
            else if (action.equalsIgnoreCase("add"))
                addCustomer();
            else if (action.equalsIgnoreCase("del") || action.equalsIgnoreCase("delete"))
                deleteCustomer();
            else if (action.equalsIgnoreCase("help") || action.equalsIgnoreCase("menu"))
                displayMenu();
            else if (action.equalsIgnoreCase("exit") || action.equalsIgnoreCase("quit"))
                System.out.println("Bye. ");
            else
                System.out.println("Error! Not a valid command. ");
        }
    }

    public static void displayMenu()
    {
        System.out.println("COMMAND MENU");
        System.out.println("list    - List all customers");
        System.out.println("add     - Add a customer");
        System.out.println("del     - Delete a customer");
        System.out.println("help    - Show this menu");
        System.out.println("exit    - Exit this application ");
    }

    public static void displayAllCustomers()
    {
        System.out.println("CUSTOMERS LIST");

        ArrayList<Customer> customers = customerDAO.getCustomers();
        Customer c = null;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < customers.size(); i++)
        {
            c = customers.get(i);
            sb.append(StringUtils.padWithSpaces(c.getEmail(),EMAIL_SIZE + 4));
            sb.append(StringUtils.padWithSpaces(c.getFirstName(),FIRST_SIZE +4));
            sb.append(c.getLastName());
            sb.append(" ");
        }
        System.out.println(sb.toString());
    }

    public static void addCustomer()
    {
        String email = Validator.getString(
                sc, "Enter customer email address: ");
        String firstName = Validator.getLine(
                sc, "Enter first name: ");
        String lastName = Validator.getLine(
                sc, "Enter last name: ");

        Customer customer = new Customer();
        customer.setEmail(email);
        customer.setFirstName(firstName);
        customer.setLastName(lastName);
        customerDAO.addCustomer(customer);

        System.out.println();
        System.out.println(firstName
                + " has been added. ");
    }

    public static void deleteCustomer()
    {
        String email = Validator.getString(sc,
                "Enter customer email address to delete: ");

        Customer c = customerDAO.getCustomer(email);

        System.out.println();
        if (c != null)
        {
            customerDAO.deleteCustomer(c);
            System.out.println(c.getFirstName()
            + " has been deleted. ");
        }
        else
        {
            System.out.println("No customer matches that email. ");
        }
    }
}

Validator.java


import java.util.Scanner;

public class Validator
{
    public static String getLine(Scanner sc, String prompt)
    {
        System.out.print(prompt);
        String s = sc.nextLine();        // read the whole line
        return s;
    }

    public static String getString(Scanner sc, String prompt)
    {
        System.out.print(prompt);
        String s = sc.next();        // read the first string on the line
        sc.nextLine();               // discard the rest of the line
        return s;
    }

    public static int getInt(Scanner sc, String prompt)
    {
        boolean isValid = false;
        int i = 0;
        while (isValid == false)
        {
            System.out.print(prompt);
            if (sc.hasNextInt())
            {
                i = sc.nextInt();
                isValid = true;
            }
            else
            {
                System.out.println("Error! Invalid integer value. Try again.");
            }
            sc.nextLine(); // discard any other data entered on the line
        }
        return i;
    }

    public static int getInt(Scanner sc, String prompt,
    int min, int max)
    {
        int i = 0;
        boolean isValid = false;
        while (isValid == false)
        {
            i = getInt(sc, prompt);
            if (i <= min)
                System.out.println(
                    "Error! Number must be greater than " + min);
            else if (i >= max)
                System.out.println(
                    "Error! Number must be less than " + max);
            else
                isValid = true;
        }
        return i;
    }

    public static double getDouble(Scanner sc, String prompt)
    {
        boolean isValid = false;
        double d = 0;
        while (isValid == false)
        {
            System.out.print(prompt);
            if (sc.hasNextDouble())
            {
                d = sc.nextDouble();
                isValid = true;
            }
            else
            {
                System.out.println("Error! Invalid decimal value. Try again.");
            }
            sc.nextLine(); // discard any other data entered on the line
        }
        return d;
    }

    public static double getDouble(Scanner sc, String prompt,
    double min, double max)
    {
        double d = 0;
        boolean isValid = false;
        while (isValid == false)
        {
            d = getDouble(sc, prompt);
            if (d <= min)
                System.out.println(
                    "Error! Number must be greater than " + min);
            else if (d >= max)
                System.out.println(
                    "Error! Number must be less than " + max);
            else
                isValid = true;
        }
        return d;
    }

}

CustomerMainAppt.java


import java.util.Scanner;
import java.util.ArrayList;

public class CustomerMaintApp implements CustomerConstants
{
    // declare two class variables
    private static CustomerDAO customerDAO = null;
    private static Scanner sc = null;

    public static void main(String args[])
    {
        // display a welcome message
        System.out.println("Welcome to the Customer Maintenance application ");

        // set the class variables
        customerDAO = DAOFactory.getCustomerDAO();
        sc = new Scanner(System.in);

        // display the command menu
        displayMenu();

        // perform 1 or more actions
        String action = "";
        while (!action.equalsIgnoreCase("exit"))
        {
            // get the input from the user
            action = Validator.getString(sc,
                    "Enter a command: ");
            System.out.println();

            if (action.equalsIgnoreCase("list"))
                displayAllCustomers();
            else if (action.equalsIgnoreCase("add"))
                addCustomer();
            else if (action.equalsIgnoreCase("del") || action.equalsIgnoreCase("delete"))
                deleteCustomer();
            else if (action.equalsIgnoreCase("help") || action.equalsIgnoreCase("menu"))
                displayMenu();
            else if (action.equalsIgnoreCase("exit") || action.equalsIgnoreCase("quit"))
                System.out.println("Bye. ");
            else
                System.out.println("Error! Not a valid command. ");
        }
    }

    public static void displayMenu()
    {
        System.out.println("COMMAND MENU");
        System.out.println("list    - List all customers");
        System.out.println("add     - Add a customer");
        System.out.println("del     - Delete a customer");
        System.out.println("help    - Show this menu");
        System.out.println("exit    - Exit this application ");
    }

    public static void displayAllCustomers()
    {
        System.out.println("CUSTOMERS LIST");

        ArrayList<Customer> customers = customerDAO.getCustomers();
        Customer c = null;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < customers.size(); i++)
        {
            c = customers.get(i);
            sb.append(StringUtils.padWithSpaces(c.getEmail(),EMAIL_SIZE + 4));
            sb.append(StringUtils.padWithSpaces(c.getFirstName(),FIRST_SIZE +4));
            sb.append(c.getLastName());
            sb.append(" ");
        }
        System.out.println(sb.toString());
    }

    public static void addCustomer()
    {
        String email = Validator.getString(
                sc, "Enter customer email address: ");
        String firstName = Validator.getLine(
                sc, "Enter first name: ");
        String lastName = Validator.getLine(
                sc, "Enter last name: ");

        Customer customer = new Customer();
        customer.setEmail(email);
        customer.setFirstName(firstName);
        customer.setLastName(lastName);
        customerDAO.addCustomer(customer);

        System.out.println();
        System.out.println(firstName
                + " has been added. ");
    }

    public static void deleteCustomer()
    {
        String email = Validator.getString(sc,
                "Enter customer email address to delete: ");

        Customer c = customerDAO.getCustomer(email);

        System.out.println();
        if (c != null)
        {
            customerDAO.deleteCustomer(c);
            System.out.println(c.getFirstName()
            + " has been deleted. ");
        }
        else
        {
            System.out.println("No customer matches that email. ");
        }
    }
}

Customer.java


public class Customer
{
    private String email;
    private String firstName;
    private String lastName;

    public Customer()
    {
        this("", "", "");
    }

    public Customer(String email, String firstName, String lastName)
    {
        this.email = email;
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public void setEmail(String email)
    {
        this.email = email;
    }

    public String getEmail(){
        return email;
    }

    public void setFirstName(String firstName)
    {
        this.firstName = firstName;
    }

    public String getFirstName()
    {
        return firstName;
    }

    public void setLastName(String lastName)
    {
        this.lastName = lastName;
    }

    public String getLastName()
    {
        return lastName;
    }


    public boolean equals(Object object)
    {
        if (object instanceof Customer)
        {
            Customer customer2 = (Customer) object;
            if
            (
                email.equals(customer2.getEmail()) &&
                firstName.equals(customer2.getFirstName()) &&
                lastName.equals(customer2.getLastName())
            )
                return true;
        }
        return false;
    }

    public String toString()
    {
        return "Email:        " + email + " " +
               "First Name: " + firstName + " " +
               "Last Name:       " + lastName + " ";
    }
}

DAOFactory.java


public class DAOFactory
{
    // this method maps the ProductDAO interface
    // to the appropriate data storage mechanism
    public static CustomerDAO getCustomerDAO()
    {
        CustomerDAO pDAO = new CustomerXMLFile();
        return pDAO;
    }
}

CustomerDAO.java


public interface CustomerDAO extends CustomerReader, CustomerWriter, CustomerConstants
{
    // all methods from the ProductReader and ProductWriter interfaces
    // all static constants from the ProductConstants interface
}

CustomerReader.java


import java.util.ArrayList;

public interface CustomerReader
{
    Customer getCustomer(String email);
    ArrayList<Customer> getCustomers();
}

CustomerConstants.java


public interface CustomerConstants

{
    int EMAIL_SIZE = 35;
    int FIRST_SIZE = 15;
}

CustomerWriter.java


public interface CustomerWriter
{
    boolean addCustomer(Customer c);
    boolean updateCustomer(Customer c);
    boolean deleteCustomer(Customer c);
}

CustomerXMLFile.java


import java.util.*;
import java.io.*;
import java.nio.file.*;
import javax.xml.stream.*; // StAX API

public class CustomerXMLFile implements CustomerDAO
{
    private Path customersPath = null;
    private ArrayList<Customer> customers = null;

    public CustomerXMLFile()
    {
        customersPath = Paths.get("customer.xml");
        customers = this.getCustomers();
    }
    private boolean saveCustomers()
    {
        // create the XMLOutputFactory object
        XMLOutputFactory outputFactory = XMLOutputFactory.newFactory();
        try
        {
            // create XMLStreamWriter object
            FileWriter fileWriter =
                new FileWriter(customersPath.toFile());
            XMLStreamWriter writer =
                outputFactory.createXMLStreamWriter(fileWriter);

            //write the products to the file
            writer.writeStartDocument("1.0");
            writer.writeStartElement("Customers");
            for (Customer c: customers)
            {
                writer.writeStartElement("Customer");
                writer.writeAttribute("Email", c.getEmail());
           
                writer.writeStartElement("FirstName");
                writer.writeCharacters(c.getFirstName());
                writer.writeEndElement();

                writer.writeStartElement("LastName");
                writer.writeCharacters(c.getLastName());
                writer.writeEndElement();

                writer.writeEndElement();
              
            }
            writer.writeEndElement();
            writer.flush();
            writer.close();
        }
        catch (IOException | XMLStreamException e)
        {
            System.out.println(e);
            return false;
        }
        return true;
    }

    public ArrayList<Customer> getCustomers()
    {
        // if the XML file has already been read, don't read it again
        if (customers != null)
            return customers;      

        customers = new ArrayList();      
        Customer c = null;      
        if (Files.exists(customersPath)) // prevent the FileNotFoundException
        {
            // create the XMLInputFactory object
            XMLInputFactory inputFactory = XMLInputFactory.newFactory();
            try
            {
                // create a XMLStreamReader object
                FileReader fileReader =
                    new FileReader(customersPath.toFile());
                XMLStreamReader reader =
                    inputFactory.createXMLStreamReader(fileReader);

                // read the products from the file
                while (reader.hasNext())
                {
                    int eventType = reader.getEventType();
                    switch (eventType)
                    {
                        case XMLStreamConstants.START_ELEMENT:
                            String elementName = reader.getLocalName();
                            if (elementName.equals("Customer"))
                            {
                                c = new Customer();
                                String email = reader.getAttributeValue(0);
                                c.setEmail(email);
                            }
                            if (elementName.equals("FirstName"))
                            {
                                String firstName = reader.getElementText();
                                c.setFirstName(firstName);
                            }
                            if (elementName.equals("LastName"))
                            {
                               String lastName = reader.getElementText();
                                c.setLastName(lastName);
                            }
                            break;
                        case XMLStreamConstants.END_ELEMENT:
                            elementName = reader.getLocalName();
                            if (elementName.equals("Customer"))
                            {
                                customers.add(c);
                            }
                            break;
                        default:
                            break;
                    }
                    reader.next();
                }
            }
            catch (IOException | XMLStreamException e)
            {
                System.out.println(e);
                return null;
            }
        }
        return customers;
    }

    public Customer getCustomer(String email)
    {
        for (Customer c : customers)
        {
            if (c.getEmail().equals(email))
                return c;
        }
        return null;
    }

    public boolean addCustomer(Customer c)
    {
        customers.add(c);
        return this.saveCustomers();
    }

    public boolean deleteCustomer(Customer c)
    {
        customers.remove(c);
        return this.saveCustomers();
    }

    public boolean updateCustomer(Customer newCustomer)
    {
        // get the old product and remove it
        Customer oldCustomer = this.getCustomer(newCustomer.getEmail());
        int i = customers.indexOf(oldCustomer);
        customers.remove(i);

        // add the updated product
        customers.add(i, newCustomer);

        return this.saveCustomers();
    }
}


StringUtils.java


public class StringUtils
{
    public static String padWithSpaces(String s, int length)
    {
        if (s.length() < length)
        {
            StringBuilder sb = new StringBuilder(s);
            while(sb.length() < length)
            {
                sb.append(" ");
            }
            return sb.toString();
        }
        else
        {
            return s.substring(0, length);
        }
    }
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote