예제 #1
0
  public void deposit(String accountNum, String depositAmount) {
    // actually deposits the appropriate amount into the account

    double deposit =
        Double.parseDouble(
            depositAmount); // the balance in the Account class is saved as a double so it must be
                            // converted here
    boolean accountFound = customer.addMoney(deposit, accountNum);

    if (accountFound == true) {
      // create the log file
      timestamp = date.getTime();
      String customerID = customer.returnID();
      AdminLog newTransaction =
          new AdminLog(timestamp, transaction_counter, customerID, accountNum, deposit);
      adminLogs.add(newTransaction);

      transaction_counter++;
      add_interest();
      String infoMessage = customer.builderToString();
      jf.displayInfo(infoMessage);
      try {
        saveFile(cust, DBfile);
        saveFile(adminLogs, logFile);
      } catch (IOException e) {
        e.printStackTrace();
      }
    } else {
      jf.errorMessage(
          "We cannot find that account number in our database"); // pops up an error message if the
                                                                 // account was not found
    }
    customer = null; // resets the customer and account after each transaction
    pin = null;
  }
예제 #2
0
  public void withdraw(String withdrawAmount, String accountNum) {
    // actually performs the withdrawal service
    double withdrawal = Double.parseDouble(withdrawAmount);
    boolean accountFound = customer.removeMoney(withdrawal, accountNum);
    if (accountFound == true) {
      // creates the log file
      double logAmount = -withdrawal;
      timestamp = date.getTime();
      String customerID = customer.returnID();
      AdminLog newTransaction =
          new AdminLog(timestamp, transaction_counter, customerID, accountNum, logAmount);
      adminLogs.add(newTransaction);

      transaction_counter++;
      add_interest();
      String infoMessage = customer.builderToString();
      jf.displayInfo(infoMessage);

      try {
        saveFile(cust, DBfile);
        saveFile(adminLogs, logFile);
      } catch (IOException e) {
        e.printStackTrace();
      }
    } else {
      jf.errorMessage(
          "We cannot find that account number in our database"); // pops up an error message if the
                                                                 // account was not found
    }
    customer = null; // resets the customer and account after each transaction
    pin = null;
  }
예제 #3
0
  public void open_account(boolean save) {
    // actually opens the account
    customer.addAccount(
        starting_account_number,
        save); // addAccount will create a new account based on whether it is savings/checkings

    StringBuilder text = new StringBuilder();
    text.append("<html>Account created!<br>");
    String result = customer.returnInfo();
    String subResult = result.substring(6);
    text.append(subResult);
    String infoText = text.toString();
    jf.displayInfo(infoText);

    transaction_counter++;
    add_interest();
    try {
      saveFile(cust, DBfile);
      saveFile(adminLogs, logFile);
    } catch (IOException e) {
      e.printStackTrace();
    }
    customer = null; // resets the customer and account after each transaction
    pin = null;
  }
예제 #4
0
  // Reserve an item.
  @Override
  public boolean reserveCustomer(int id, int customerId, String key, String location, int price) {
    synchronized (syncLock) {
      Customer cust = (Customer) readData(id, Customer.getKey(customerId));
      if (cust == null) {
        Trace.warn(
            "RM::reserveItem("
                + id
                + ", "
                + customerId
                + ", "
                + key
                + ", "
                + location
                + ") failed: customer doesn't exist.");
        return false;
      } else {
        // Do reservation.
        cust.reserve(key, location, price);
        writeData(id, cust.getKey(), cust);

        Trace.warn(
            "RM::reserveItem(" + id + ", " + customerId + ", " + key + ", " + location + ") OK.");
        return true;
      }
    }
  }
예제 #5
0
  public void printAllAccounts(String customerID) {
    // Sorts the customer based on ID, then prints the accounts information

    // change the withdrawal funcitons and deposit functions too
    ajf.dispose();
    ajf = new AdminRunningFrame(this);

    Collections.sort(cust, Customer.CompareIDs);
    String searchString = ajf.getCustomerID();

    StringBuilder stringResults = new StringBuilder();
    String header = header();
    stringResults.append(header);
    for (Customer customer : cust) {
      String id = customer.returnID();
      String name = customer.getName().toUpperCase();
      String pin = customer.returnPin();
      if (searchString.equals(id)) {
        ArrayList<Account> accounts = customer.getAccounts();
        if (!accounts.isEmpty()) {
          for (Account account : accounts) {
            if (account.checkActive()) {
              String accountNumber = account.returnNumber();
              double balance = account.returnBalance();
              String balanceAsString = formatter.format(balance);
              String customerInfo = printAdminInfo(name, id, accountNumber, pin, balanceAsString);
              stringResults.append(customerInfo);
            }
          }
        }
      }
    }
    String resultsAsString = stringResults.toString();
    ajf.printInfo(resultsAsString);
  }
예제 #6
0
 @Override
 public Customer findCustomerById(long customerId) {
   Customer customer = customerRepository.findOne(customerId);
   if (null == customer) throw new CustomerNotFoundException(customerId);
   Hibernate.initialize(customer.getUser());
   return customer;
 }
 /**
  * Lookup a Customer and return it or return a new one if not found.
  *
  * @param name the name of the customer to lookup
  * @return a new or existing Customer associated with this Company
  */
 public Customer lookupOrCreateCustomer(String name) {
   Customer c = (Customer) lnkCustomer.get(name);
   if (c == null) {
     c = new Customer(name);
     lnkCustomer.put(c.getName(), c);
   }
   return c;
 }
예제 #8
0
 public static Customer addOrdersFromDB(Customer c) {
   Customer newCustomer = new Customer(c.getID());
   List<Order> orders = orderDAO.retrieveOrders(c);
   for (Order o : orders) {
     newCustomer.addOrder(o);
   }
   return newCustomer;
 }
예제 #9
0
 public void orderTest3() {
   Customer customer = customerDAO.getCustomerById(2);
   List list = orderService.getOrdersByUsername(customer.getUsername());
   System.out.println("List size :" + list.size());
   for (Object obj : list) {
     System.out.println(obj);
   }
 }
예제 #10
0
  // Deletes customer from the database.
  public boolean deleteCustomer(int id, int customerID) throws RemoteException {
    Trace.info("RM::deleteCustomer(" + id + ", " + customerID + ") called");
    Customer cust = (Customer) readData(id, Customer.getKey(customerID));

    if (cust == null) {
      Trace.warn(
          "RM::deleteCustomer(" + id + ", " + customerID + ") failed--customer doesn't exist");
      return false;
    } else {
      Customer temp = cust.clone();
      // Increase the reserved numbers of all reservable items which the customer reserved.
      RMHashtable reservationHT = cust.getReservations();
      for (Enumeration e = reservationHT.keys(); e.hasMoreElements(); ) {
        String reservedkey = (String) (e.nextElement());
        ReservedItem reserveditem = cust.getReservedItem(reservedkey);
        Trace.info(
            "RM::deleteCustomer("
                + id
                + ", "
                + customerID
                + ") has reserved "
                + reserveditem.getKey()
                + " "
                + reserveditem.getCount()
                + " times");
        ReservableItem item = (ReservableItem) readData(id, reserveditem.getKey());
        Trace.info(
            "RM::deleteCustomer("
                + id
                + ", "
                + customerID
                + ") has reserved "
                + reserveditem.getKey()
                + "which is reserved"
                + item.getReserved()
                + " times and is still available "
                + item.getCount()
                + " times");
        Flight tempItem =
            new Flight(Integer.parseInt(item.getLocation()), item.getCount(), item.getPrice());
        tempItem.setReserved(item.getReserved());
        tempItem.setType(0);
        item.setReserved(item.getReserved() - reserveditem.getCount());
        item.setCount(item.getCount() + reserveditem.getCount());
        if (readDataFromLog(id, item.getKey(), id) == null)
          writeDataToLog(id, item.getKey(), tempItem);
      }

      // remove the customer from the storage
      temp.setType(1);
      if (readDataFromLog(id, cust.getKey(), id) == null) writeDataToLog(id, cust.getKey(), temp);
      removeData(id, cust.getKey());

      Trace.info("RM::deleteCustomer(" + id + ", " + customerID + ") succeeded");
      return true;
    } // if
  }
예제 #11
0
 // Delete customer from the database.
 @Override
 public boolean deleteCustomer(int id, int customerId) {
   Trace.info("RM::deleteCustomer(" + id + ", " + customerId + ") called.");
   synchronized (syncLock) {
     Customer cust = (Customer) readData(id, Customer.getKey(customerId));
     removeData(id, cust.getKey());
     Trace.info("RM::deleteCustomer(" + id + ", " + customerId + ") OK.");
     return true;
   }
 }
예제 #12
0
 @Override
 public Customer removeCustomer(long userId, long customerId) {
   User user = userRepository.findOne(userId);
   Customer customer = customerRepository.findOne(customerId);
   user.getCustomers().remove(customer);
   this.userRepository.save(user);
   customer.setUser(null);
   this.customerRepository.delete(customer);
   return customer;
 }
예제 #13
0
 private static void showPage(String custId, String errMsg) {
   // Obviously this is inefficient -- the list of customer and products never changes,
   // so we could cache it.
   List<Customer> customers = Customer.find("order by name").fetch();
   List<Product> products = Product.find("order by name").fetch();
   Customer currentCustomer;
   if (custId == null || custId.trim().length() == 0) currentCustomer = customers.get(0);
   else currentCustomer = Customer.findById(new Long(custId));
   renderTemplate("Application/index.html", customers, currentCustomer, products, errMsg);
 }
예제 #14
0
  public static void main(String[] args) throws Exception {
    System.out.println("hello from Customer.java");

    EntityManagerFactory factory = Persistence.createEntityManagerFactory("customerPU");
    EntityManager manager = factory.createEntityManager();
    Query q1 = manager.createQuery("SELECT COUNT(c) FROM Customer c");
    Long count = (Long) q1.getSingleResult();
    if (count == 0) {
      // record is empty, read from data.txst
      System.out.println("record empty, read from data.txt...");
      // try {
      FileReader fr = new FileReader("data.txt");
      BufferedReader br = new BufferedReader(fr);
      String s;
      while ((s = br.readLine()) != null) {

        // System.out.println(s);
        // split the string s
        Object[] items = s.split("\\|");
        // store in string list
        // List<String> itemList= new ArrayList<String>(Arrays.asList(items));
        // string list converted to array

        // Object[] itemArray = itemList.toArray();
        // insert data into database table
        manager.getTransaction().begin();
        Customer c = new Customer();

        // add email
        c.setEmail((String) items[0]);

        // add pass
        c.setPass((String) items[1]);

        // add name
        c.setName((String) items[2]);

        // add address
        c.setAddress((String) items[3]);

        // add yob
        c.setYob((String) items[4]);

        // change to managed state
        manager.persist(c);
        manager.getTransaction().commit();
      }
      fr.close();
    }

    // display the records
    Query q2 = manager.createNamedQuery("Customer.findAll");
    List<Customer> customers = q2.getResultList();
    for (Customer c : customers) {
      System.out.println(c.getName() + ", " + c.getEmail());
    }

    manager.close();
    factory.close();
  }
예제 #15
0
 public void model_transfer(String customerID, String customerPIN) {
   // calls the transfer screen from the RunningFrame class
   validate_info(customerID, customerPIN);
   if (customer != null) {
     jf.dispose();
     jf = new RunningFrame(this);
     String result = customer.returnInfo();
     ArrayList<String> allAccounts = customer.getAllAccounts();
     jf.transferScreen(result, allAccounts);
   }
 }
예제 #16
0
  public static void main(String arg[]) {
    Customer customer = new Customer();

    Vector allAccounts = new Vector();

    allAccounts.addElement(new Account("ckc", 120, customer));
    customer.setAllAccounts(allAccounts);
    Client cle = new ClientAdapter(customer);
    for (InternationalAccount a : cle.getAccountsAdapter())
      System.out.println(a.getAccountnumber());
  }
예제 #17
0
 @Override
 public Collection<Customer> loadCustomerAccounts(long userId) {
   List<Customer> customersList = this.customerRepository.findByUserId(userId);
   ArrayList<Customer> customers = new ArrayList<Customer>();
   for (Customer c : customersList) {
     Hibernate.initialize(c);
     User user = new User(userId);
     c.setUser(user);
     customers.add(c);
   }
   return Collections.unmodifiableList(customers);
 }
예제 #18
0
 @Override
 public int newCustomer(int id) {
   Trace.info("INFO: RM::newCustomer(" + id + ") called.");
   // Generate a globally unique Id for the new customer.
   int customerId =
       Integer.parseInt(
           String.valueOf(id)
               + String.valueOf(Calendar.getInstance().get(Calendar.MILLISECOND))
               + String.valueOf(Math.round(Math.random() * 100 + 1)));
   Customer cust = new Customer(customerId);
   writeData(id, cust.getKey(), cust);
   Trace.info("RM::newCustomer(" + id + ") OK: " + customerId);
   return customerId;
 }
예제 #19
0
 public void model_printAllAccounts() {
   ArrayList<String> cusIDs = new ArrayList<String>(100);
   cusIDs.add("Accounts:");
   Collections.sort(cust, Customer.CompareIDs);
   for (Customer c : cust) {
     String id = c.returnID();
     cusIDs.add(id);
   }
   if (ajf != null) {
     ajf.dispose();
   }
   ajf = new AdminRunningFrame(this);
   ajf.showOneCustomerScreen(cusIDs);
 }
예제 #20
0
 private static void processUpdate(String type, String id, String att, String value) {
   if (type == null || type.trim().length() == 0) return;
   if ("Order".equals(type)) {
     PurchaseOrder order = PurchaseOrder.findById(new Long(id));
     if ("paid".equals(att)) {
       Boolean oldValue = order.paid;
       if (oldValue == null) oldValue = Boolean.FALSE;
       order.paid = !oldValue;
       if (oldValue) setCurrentUseCaseName("Order unpaid");
       else setCurrentUseCaseName("Order paid");
     } else if ("customer".equals(att)) {
       if (value == null
           || value.startsWith(
               "- ")) // Do nothing if somehow the "- select a customer -" item was selected
       return;
       Customer customer = Customer.findById(new Long(value));
       order.customer = customer;
       Flash.current().success("The order has been reassigned to customer " + customer.name);
       setCurrentUseCaseName("Order reassigned");
     } else if ("notes".equals(att)) {
       order.notes = value;
       setCurrentUseCaseName("Order notes updated");
     }
     order.save();
   } else if ("Customer".equals(type)) {
     Customer customer = Customer.findById(new Long(id));
     if ("creditLimit".equals(att)) {
       BigDecimal val = NumberFormat.parseMoney(value);
       customer.creditLimit = val;
       setCurrentUseCaseName("Customer credit limit updated");
     }
     customer.save();
   } else if ("LineItem".equals(type)) {
     LineItem lineitem = LineItem.findById(new Long(id));
     if ("quantity".equals(att)) {
       Integer val = NumberFormat.parseNumber(value);
       lineitem.qtyOrdered = val;
       setCurrentUseCaseName("Line Item quantity updated");
     } else if ("unitPrice".equals(att)) {
       BigDecimal val = NumberFormat.parseMoney(value);
       lineitem.productPrice = val;
       setCurrentUseCaseName("Line Item unit price updated");
     } else if ("product".equals(att)) {
       Product product = Product.findById(new Long(value));
       lineitem.product = product;
       setCurrentUseCaseName("Line Item product changed");
     }
     lineitem.save();
   }
 }
예제 #21
0
 // This method makes testing easier.
 @Override
 public boolean newCustomerId(int id, int customerId) {
   Trace.info("INFO: RM::newCustomer(" + id + ", " + customerId + ") called.");
   Customer cust = (Customer) readData(id, Customer.getKey(customerId));
   if (cust == null) {
     cust = new Customer(customerId);
     writeData(id, cust.getKey(), cust);
     Trace.info("INFO: RM::newCustomer(" + id + ", " + customerId + ") OK.");
     return true;
   } else {
     Trace.info(
         "INFO: RM::newCustomer(" + id + ", " + customerId + ") failed: customer already exists.");
     return false;
   }
 }
예제 #22
0
 public void create_account(String name, String newPin) {
   // Actually creates the customer account
   Customer customer = new Customer(starting_customer_number, newPin, name);
   cust.add(customer);
   String newCusID = customer.returnID();
   String idString = String.format("Your new Customer ID is: %s\n", newCusID);
   transaction_counter++;
   add_interest();
   try {
     saveFile(cust, DBfile);
   } catch (IOException e) {
     e.printStackTrace();
   }
   jf.displayInfo(idString);
 }
 public void run() {
   try {
     while (!Thread.interrupted()) {
       Customer customer = customers.take();
       TimeUnit.MILLISECONDS.sleep(customer.getServiceTime());
       synchronized (this) {
         customersServed++;
         while (!servingCustomerLine) wait();
       }
     }
   } catch (InterruptedException e) {
     System.out.println(this + "interrupted");
   }
   System.out.println(this + "terminating");
 }
예제 #24
0
 // return a bill
 public String queryCustomerInfo(int id, int customerID) throws RemoteException {
   Trace.info("RM::queryCustomerInfo(" + id + ", " + customerID + ") called");
   Customer cust = (Customer) readData(id, Customer.getKey(customerID));
   if (cust == null) {
     Trace.warn(
         "RM::queryCustomerInfo(" + id + ", " + customerID + ") failed--customer doesn't exist");
     return ""; // NOTE: don't change this--WC counts on this value indicating a customer does not
                // exist...
   } else {
     String s = cust.printBill();
     Trace.info("RM::queryCustomerInfo(" + id + ", " + customerID + "), bill follows...");
     System.out.println(s);
     return s;
   } // if
 }
예제 #25
0
 // Returns data structure containing customer reservation info. Returns null if the
 //  customer doesn't exist. Returns empty RMHashtable if customer exists but has no
 //  reservations.
 public RMHashtable getCustomerReservations(int id, int customerID) throws RemoteException {
   Trace.info("RM::getCustomerReservations(" + id + ", " + customerID + ") called");
   Customer cust = (Customer) readData(id, Customer.getKey(customerID));
   if (cust == null) {
     Trace.warn(
         "RM::getCustomerReservations failed("
             + id
             + ", "
             + customerID
             + ") failed--customer doesn't exist");
     return null;
   } else {
     return cust.getReservations();
   } // if
 }
예제 #26
0
 public static void addOrderToDB(Order o) {
   Customer customer = CustomerServiceImpl.getCustomer(o.getCustomerID());
   customer.setOrders(OrderServiceImpl.retrieveUnpaidOrders(customer));
   customer.addOrder(o);
   if (customer.getOrders().contains(o)) {
     orderDAO.addOrder(o);
     List<OrderItem> items = o.getItems();
     Inventory inventory = new Inventory(InventoryServiceImpl.getAllAvailableProductsInDB());
     for (OrderItem i : items) {
       Product product = ProductServiceImpl.getProduct(i.getItemSKUNumber());
       InventoryItem inventoryitem = InventoryServiceImpl.getInventoryItem(inventory, product);
       InventoryServiceImpl.deductFromInventory(inventory, inventoryitem, i.getQuantity());
     }
   }
 }
예제 #27
0
 // Adds flight reservation to this customer.
 public ReturnTuple<Boolean> reserveFlight(
     int id, int customerID, int flightNum, Timestamp timestamp)
     throws RemoteException, TransactionAbortedException, InvalidTransactionException {
   if (!isMaster) {
     System.out.println("Slave retransmitting reserveFlight to master");
     return this.getMaster().reserveFlight(id, customerID, flightNum, timestamp);
   } else {
     timestamp.stamp();
     ReserveFlightRMICommand rf =
         new ReserveFlightRMICommand(flightGroup, id, customerID, flightNum);
     rf.setTimestampObject(timestamp);
     ReturnTuple<Boolean> result = null;
     try {
       overseer.validTransaction(id);
       lm.Lock(id, Customer.getKey(customerID), rf.getRequiredLock());
       lm.Lock(id, Flight.getKey(flightNum), rf.getRequiredLock());
       rf.execute();
       result = rf.success;
       if (result.result) overseer.addCommandToTransaction(id, rf);
     } catch (DeadlockException d) {
       timestamp.stamp();
       overseer.abort(id);
       timestamp.stamp();
       throw new TransactionAbortedException(timestamp);
     } catch (TransactionAbortedException tae) {
       tae.t = timestamp;
       throw tae;
     } catch (InvalidTransactionException ite) {
       ite.t = timestamp;
       throw ite;
     }
     result.timestamp.stamp();
     return result;
   }
 }
예제 #28
0
 // Deletes customer from the database.
 public ReturnTuple<Boolean> deleteCustomer(int id, int customerID, Timestamp timestamp)
     throws RemoteException, TransactionAbortedException, InvalidTransactionException {
   if (!isMaster) {
     System.out.println("Slave retransmitting deleteCustomer to master");
     return this.getMaster().deleteCustomer(id, customerID, timestamp);
   } else {
     timestamp.stamp();
     DeleteCustomerRMICommand dc =
         new DeleteCustomerRMICommand(carGroup, flightGroup, roomGroup, id, customerID);
     dc.setTimestampObject(timestamp);
     ReturnTuple<Boolean> result = null;
     try {
       overseer.validTransaction(id);
       lm.Lock(id, Customer.getKey(customerID), dc.getRequiredLock());
       dc.execute();
       result = dc.success;
       if (result.result) overseer.addCommandToTransaction(id, dc);
     } catch (DeadlockException d) {
       timestamp.stamp();
       overseer.abort(id);
       timestamp.stamp();
       throw new TransactionAbortedException(timestamp);
     } catch (TransactionAbortedException tae) {
       tae.t = timestamp;
       throw tae;
     } catch (InvalidTransactionException ite) {
       ite.t = timestamp;
       throw ite;
     }
     result.timestamp.stamp();
     return result;
   }
 }
 public void testFinderThrowsNoResult() throws Exception {
   try {
     Customer.findByNumber(66); // 66 doesn't exist
     fail("EntityNotFoundException expected");
   } catch (javax.persistence.NoResultException ex) {
     // All fine
   }
 }
예제 #30
0
 // Return data structure containing customer reservation info.
 // Returns null if the customer doesn't exist.
 // Returns empty RMHashtable if customer exists but has no reservations.
 public RMHashtable getCustomerReservations(int id, int customerId) {
   Trace.info("RM::getCustomerReservations(" + id + ", " + customerId + ") called.");
   synchronized (syncLock) {
     Customer cust = (Customer) readData(id, Customer.getKey(customerId));
     if (cust == null) {
       Trace.info(
           "RM::getCustomerReservations("
               + id
               + ", "
               + customerId
               + ") failed: customer doesn't exist.");
       return null;
     } else {
       return cust.getReservations();
     }
   }
 }