Developing ECommerce Application using Java



§  Business Requirements
Develop POS (Point Of Sales) system which will be used by Shop Operator and will support below  functionality for Phase - 1,
  1. Based on the Item purchased by Customer, the Operator can select that item from the Item list displayed on the Terminal screen
  2. For each Customer, the system will keep record of all items per transaction and finally persist the transaction information to external file for future use.
  3. Display Total sell amount at any point of time
§  Requirements Analysis
  1. After authorized Operator starts the system, she will be displayed with all available Item Numbers and Description, 
  2. Based on the Items presented by Customer, the Operator will record each item to the system
  3. System will record each transaction which should contains following information (TransactionId, Date[ddmmyyyy], Time[HH:min:sec], OperatorId, MachineId, CustomerId,  ItemId, ItemPriceAmount)
  4. Persist all transactions to external file : alltransactions.csv
  5. Reporting function to display total sale information 
  6. Maintain Item information in external file : itemmaster.csv
  • File Specifications
    • alltransactions.csv
      • TransactionId : (T1)
      • Date[ddmmyyyy] : (20120721) 
      • Time[HH:min:sec] : (17:21:45)
      • OperatorId : (A007)
      • MachineId : (M1)
      • CustomerId : (C1)
      • ItemId : (I1) 
      • ItemPriceAmount : (250)
      • ItemPriceCurrency : (JPY)
    • itemmaster.csv
      • ItemId : (I1)
      • ItemDescription : (Milk)
      • ItemPriceAmount : (250)
      • ItemPriceCurrency : (JPY)
TODO : Add authentication, add logging and auditing, add Internationalization to display UI based on the system language (For Japanese system display UI in Japanese Language, Similarly for other languages)

§  Domain Model


§  Implementation in Java
  • Project Structure
  • Source code
[itemmaster.csv]
i1,Milk,250,jpy
i2,Bread,170,jpy
i3,Water,100,jpy



[POSApp.java]

import java.util.HashMap;
import java.util.Iterator;
import model.Item;
import controller.ItemManager;
import controller.ShoppingCart;

public class POSApp {

 public static void main(String[] args) {
  //Load list of available item list for Operator's reference
  ItemManager itemManager = new ItemManager();
  HashMap<String, Item> itemMap = itemManager.getAllItems();

  Iterator<String> iterator = itemMap.keySet().iterator();

  System.out.println("-----List of Available Items------[Item#, Description, Price, Currency]");

  while (iterator.hasNext()) {
   Item item = itemMap.get(iterator.next()); 
   System.out.println(item.printStatus());
  }

  System.out.println("-------------------------------");

  ShoppingCart cart = new ShoppingCart();
  cart.start();
  cart.checkOut();

  System.out.println("Thank you for using POS, Have a nice day !!! ");
 }
}

[ItemManager.java]

package controller;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Scanner;
import model.Item;
import model.Price;

public class ItemManager {

 /**
  * Method to return all available Item information after reading from underlying data source, such as file.
  * @return Map of Items in key/value pair, where key is itemId and value is other item details
  */
 public HashMap<String, Item> getAllItems() {
 
  HashMap<String, Item> itemMap = new HashMap<String, Item>();
 
  //create file object from the external file
  File itemFile = new File("itemmaster.csv");
 
  //When reading a file it is necessary to catch Exception, 
  //such as FileNotFoundException by using try-catch block.
  try {
   //Use Scanner to read external file : itemmaster.csv
   Scanner scanner = new Scanner(itemFile);
  
   //continue the loop till the end of file
   while (scanner.hasNext()) {
   
    //Read record from the external file line by line
    String fileRecord = scanner.nextLine();

    //split the record based on the comma (,) delimiter
    //comma delimiter to split the string record 
    //into separate string and set to array String[]

    String[] fileRecordSplit = fileRecord.split(",");  
   
    //Populate item object from the split record read from the file
    Item item = new Item();
    item.setId(fileRecordSplit[0]);
    item.setDescription(fileRecordSplit[1]);
   
    //create price object to be set later into item object
    Price price = new Price();
    price.setAmount(Double.parseDouble(fileRecordSplit[2]));
    price.setCurrency(fileRecordSplit[3]);

    item.setPrice(price);
   
    itemMap.put(item.getId(), item); //key is ItemId and Value is entire item Object
   }
  } catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }

  return itemMap;
 }
}


[ShoppingCart.java]
package controller;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Scanner;
import model.Customer;
import model.Item;
import model.Machine;
import model.Operator;
import model.Transaction;
import dao.ShoppingCartDao;

public class ShoppingCart {

 ShoppingCartDao cartDao = new ShoppingCartDao();

 /**
  * Method to start Shopping process
  */
 public void start() {
 
  int choice = 0;
 
  Scanner scanner  = new Scanner(System.in);
 
  do {
   System.out.println("Enter [1 = Add, 2 = Delete, 0 = Exit]");
   choice = scanner.nextInt();
  
   switch(choice) {
    case 1 : 
     add();
     break;
    case 2 :
     Scanner sc = new Scanner(System.in);
     System.out.println("Enter Item id to be removed = ");
     String itemId = sc.next();
     delete(itemId);
     break;
    case 0 :
     break;
    default:
    System.out.println("Invalid choice.");

   }
  } while (choice != 0);
 }

 //DAO = Data Access object
 //csv = Comma Separate Value
 public void add() {
  //TODO: do validation if any
  cartDao.create();
 }

 /**
  * Method to prepare final transaction details and print the receipt on the screen
  */
 public void checkOut() {
  //TODO: do validation if any
  ArrayList<String> itemIds = cartDao.read();
 
  //Create details of each item based on the item id
  ArrayList<Item> purchaseditems = cartDao.loadItemDetails(itemIds);

  double total = 0;
 
  System.out.println("++++++ List of items purchased ++++++");
 
  for (Item item : purchaseditems) {
    total = total + item.getPrice().getAmount();
    System.out.println(item.printStatus());
  }

  System.out.println("-----------------------------------");
  System.out.println("Total amount : " + total);
  System.out.println("+++++++++++++++++++++++++++++++++++");
 
  //record the transaction to external persistent file
  recordTransaction(purchaseditems);
 }

 //method to persist transaction details to external file for further usage
 private void recordTransaction(ArrayList<Item> purchaseditems) {
  //create Transaction
  Transaction transaction = new Transaction();
  transaction.setId("T-788"); //TODO: write a method to generate unique Id for each transaction
 
  SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
  transaction.setDate(dateFormat.format(new Date()));
 
  Operator operator = new Operator();
  operator.setId("O-005");
  transaction.setOperator(operator);
 
  Machine machine = new Machine();
  machine.setId("M-101");
  transaction.setMachine(machine);
 
  //create and set customer
  Customer customer = new Customer();
  customer.setId("C-101"); //TODO: write a method to generate unique Customer Id for each customer transaction  
  transaction.setCustomer(customer); 

  //Convert from ArrayList of item to the Array of item objects
  Item[] items = purchaseditems.toArray(new Item[purchaseditems.size()]);
  transaction.setItems(items);
 
  //save transaction to external file
   try {
             FileWriter writer = new FileWriter("alltransaction.csv", true); //set true for append mode
             BufferedWriter bufferedWriter =new BufferedWriter(writer);
             
             for (Item item : items) {             
              bufferedWriter.write(transaction.getId());
              bufferedWriter.write(",");
              bufferedWriter.write(transaction.getDate());
              bufferedWriter.write(",");
              bufferedWriter.write(transaction.getOperator().getId());
              bufferedWriter.write(",");
              bufferedWriter.write(transaction.getMachine().getId());
              bufferedWriter.write(",");
              bufferedWriter.write(transaction.getCustomer().getId());
              bufferedWriter.write(",");
              bufferedWriter.write(item.getId());
              bufferedWriter.write(",");
              //convert double to string before writing to file              
              bufferedWriter.write(String.valueOf(item.getPrice().getAmount())); 
              bufferedWriter.write("\n");
             }
             
             bufferedWriter.flush();
             bufferedWriter.close();
             writer.close();
         } catch (IOException e) {
             e.printStackTrace();
         }
 }

 public void delete(String itemId) {
  //TODO: do validation if any
  cartDao.delete(itemId);
 }
}


[ShoppingCartDao.java]
package dao;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
import model.Item;
import controller.ItemManager;

public class ShoppingCartDao {
 //CRUD , Create, Read, Update, Delete
 //Data Source

 //Load items to in memory storage using ArrayList
 static ArrayList<String> itemIdList = new ArrayList<String>();

 /**
  * Add item id to itemIdList ArrayList
  */
 public void create() {
  Scanner scanner = new Scanner(System.in);
  String itemId = "0";
 
  do {
   //Prompt to Operator !!!
   System.out.println("Enter ItemId, [0 = Exit] : ");
   itemId = scanner.next();
   //do not add itemId as 0 (zero)
   if (!itemId.equals("0")) {
    itemIdList.add(itemId);
   }
  
  } while (!itemId.equals("0"));
 }

 /**
  * Return list of Item ids of the items purchased by customers
  * @return array list of item ids
  */
 public ArrayList<String> read() {
  return itemIdList;
 }

 /**
  * TODO : Implement this method if necessary
  */
 public void update() {
 }

 /**
  * Delete item id from the itemIdList 
  * @param itemid the id to be removed from the list
  */
 public void delete(String itemid) {
  itemIdList.remove(itemid);
 }

 /**
  * Method to create item objects based on list of item Ids
  * @param itemIds ids of the item to be populated with all necessary details such as Description, Price 
  * @return items with details 
  */
 public ArrayList<Item> loadItemDetails(ArrayList<String> itemIds) {
 
  ArrayList<Item> purchasedItemList = new ArrayList<Item>();
 
  //read all the available item map
  ItemManager itemManager = new ItemManager();
  HashMap<String,Item> allItems = itemManager.getAllItems();
 
  for (int i = 0; i < itemIds.size(); i++) {
   purchasedItemList.add(allItems.get(itemIds.get(i)));
  }
  return purchasedItemList;
 }
}


[Customer.java]
package model;

public class Customer {
 private String id;

 public String getId() {
  return id;
 }

 public void setId(String id) {
  this.id = id;
 }
}

[Item.java]
package model;

public class Item {

 private Price price;
 private String id;
 private String description;

 public Price getPrice() {
  return price;
 }
 public void setPrice(Price price) {
  this.price = price;
 }
 public String getId() {
  return id;
 }
 public void setId(String id) {
  this.id = id;
 }
 public String getDescription() {
  return description;
 }
 public void setDescription(String description) {
  this.description = description;
 }

 /**
  * Method to return current state of this Object instance 
  * (can be also achieved by overriding toString() method of Object class) 
  * @return current state of this object properties
  */
 public String printStatus() {
  return  id + ","
    description + "," +
    price.getAmount() + ","
    price.getCurrency()
    ;
 }
}

[Machine.java]
package model;

public class Machine {
 private String id;
 private String model;
 private String vendor;

 public String getId() {
  return id;
 }
 public void setId(String id) {
  this.id = id;
 }
 public String getModel() {
  return model;
 }
 public void setModel(String model) {
  this.model = model;
 }
 public String getVendor() {
  return vendor;
 }
 public void setVendor(String vendor) {
  this.vendor = vendor;
 }
}

[Operator.java]
package model;

public class Operator {
 private String id;

 public String getId() {
  return id;
 }

 public void setId(String id) {
  this.id = id;
 }
}

[Price.java]
package model;

public class Price {

 private double amount;
 private String currency;// JPY, USD

 public double getAmount() {
  return amount;
 }
 public void setAmount(double amount) {
  this.amount = amount;
 }
 public String getCurrency() {
  return currency;
 }
 public void setCurrency(String currency) {
  this.currency = currency;
 }

}

[Transaction.java]
package model;

public class Transaction {

 private String id;
 private Operator operator;
 private Machine machine;
 private Customer customer;
 private String date;
 private Item[] items;

 public String getDate() {
  return date;
 }
 public void setDate(String date) {
  this.date = date;
 }
 public Item[] getItems() {
  return items;
 }
 public void setItems(Item[] items) {
  this.items = items;
 }
 public String getId() {
  return id;
 }
 public void setId(String id) {
  this.id = id;
 }
 public Operator getOperator() {
  return operator;
 }
 public void setOperator(Operator operator) {
  this.operator = operator;
 }
 public Machine getMachine() {
  return machine;
 }
 public void setMachine(Machine machine) {
  this.machine = machine;
 }
 public Customer getCustomer() {
  return customer;
 }
 public void setCustomer(Customer customer) {
  this.customer = customer;
 }
}
================================================

  • Finally, run POSApp application and provide values as shown in green colour below, it will also generate alltransactions.csv file.


Output

-----List of Available Items------[Item#, Description, Price, Currency]
i3,Water,100.0,jpy
i2,Bread,170.0,jpy
i1,Milk,250.0,jpy
-------------------------------
Enter [1 = Add, 2 = Delete, 0 = Exit]
1
Enter ItemId, [0 = Exit] : 
i2
Enter ItemId, [0 = Exit] : 
i3
Enter ItemId, [0 = Exit] : 
i2
Enter ItemId, [0 = Exit] : 
i1
Enter ItemId, [0 = Exit] : 
0
Enter [1 = Add, 2 = Delete, 0 = Exit]
0
++++++ List of items purchased ++++++
i2,Bread,170.0,jpy
i3,Water,100.0,jpy
i2,Bread,170.0,jpy
i1,Milk,250.0,jpy
-----------------------------------
Total amount : 690.0
+++++++++++++++++++++++++++++++++++
Thank you for using POS, Have a nice day !!!

================================================
For Source Download Please check link at top of this blog.
================================================