Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: adds chukwumaibezim folder with CsvLoader class #315

Merged
merged 2 commits into from Mar 28, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion lesson_10/README.md
Expand Up @@ -22,7 +22,7 @@

In this assignment, you will be given starting implementations for the `Library`, `Book`, and `Patron` classes. You will need to add the following enhancements to support new functionality:

* We now want to support the concept of a `Librarian`. A librarian should be able to check out or check in books just like other patrons. Books can no longer be added or removed from the `Library` without a librarian.
* We now want to support the concept of a `Librarian`. A librarian should be able to check out or check in items just like other patrons. Items can no longer be added or removed from the `Library` without a librarian.
* We also want to support other types of media formats, including `Dvd`, `Magazine`, and `Newspaper` types. Patrons cannot check out `Magazine` or `Newspaper` items.
* [Optional Stretch] Add the ability to search for items in the library by title, ISBN, author, or type. Extra credit will not be assigned unless the previous requirements have been met.
* [Optional Stretch] Add the ability for patrons to be members of multiple libraries. See previous note on extra credit.
Expand Down
@@ -0,0 +1,101 @@
package com.codedifferently.lesson12.factory.chukwumaibezim;

import com.codedifferently.lesson12.factory.LibraryCsvDataLoader;
import com.codedifferently.lesson12.models.CheckoutModel;
import com.codedifferently.lesson12.models.LibraryDataModel;
import com.codedifferently.lesson12.models.LibraryGuestModel;
import com.codedifferently.lesson12.models.MediaItemModel;
import com.opencsv.CSVReader;
import com.opencsv.exceptions.CsvValidationException;
import java.io.FileReader;
import java.io.IOException;
import java.time.Instant;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;

@Service
public class CsvLoader implements LibraryCsvDataLoader {

@Override
public LibraryDataModel loadData() {
LibraryDataModel libraryDataModel = new LibraryDataModel();
try {
libraryDataModel.mediaItems = readMediaItemsFromCsv("csv/media_items.csv");
libraryDataModel.guests = readGuestsFromCsv("csv/guests.csv");
populateGuestsWithCheckouts("csv/checked_out_items.csv", libraryDataModel.guests);
} catch (IOException e) {
throw new RuntimeException("Failed to load data from CSV files", e);
} catch (CsvValidationException ex) {
}
return libraryDataModel;
}

private List<MediaItemModel> readMediaItemsFromCsv(String filePath)
throws IOException, CsvValidationException {
List<MediaItemModel> mediaItems = new ArrayList<>();
try (CSVReader reader =
new CSVReader(new FileReader(new ClassPathResource(filePath).getFile()))) {
reader.skip(1); // Skip header
String[] line;
while ((line = reader.readNext()) != null) {
MediaItemModel mediaItem = new MediaItemModel();
mediaItem.type = line[0];
mediaItem.id = UUID.fromString(line[1]);
mediaItem.title = line[2];
mediaItem.isbn = line[3];
mediaItem.authors = List.of(line[4].split("\\s*,\\s*"));
mediaItem.pages = line[5].isEmpty() ? 0 : Integer.parseInt(line[5]);
mediaItem.runtime = line[6].isEmpty() ? 0 : Integer.parseInt(line[6]);
mediaItem.edition = line[7];
mediaItems.add(mediaItem);
}
}
return mediaItems;
}

private List<LibraryGuestModel> readGuestsFromCsv(String filePath)
throws IOException, CsvValidationException {
List<LibraryGuestModel> guests = new ArrayList<>();
try (CSVReader reader =
new CSVReader(new FileReader(new ClassPathResource(filePath).getFile()))) {
reader.skip(1); // Skip header
String[] line;
while ((line = reader.readNext()) != null) {
LibraryGuestModel guest = new LibraryGuestModel();
guest.type = line[0];
guest.name = line[1];
guest.email = line[2];
guests.add(guest);
}
}
return guests;
}

private void populateGuestsWithCheckouts(String filePath, List<LibraryGuestModel> guests)
throws IOException, CsvValidationException {
Map<String, List<CheckoutModel>> checkoutsByGuestEmail = new HashMap<>();
try (CSVReader reader =
new CSVReader(new FileReader(new ClassPathResource(filePath).getFile()))) {
reader.skip(1); // Skip header
String[] line;
while ((line = reader.readNext()) != null) {
String email = line[0];
CheckoutModel checkout = new CheckoutModel();
checkout.itemId = UUID.fromString(line[1]);
checkout.dueDate = Instant.parse(line[2]);
checkoutsByGuestEmail.computeIfAbsent(email, k -> new ArrayList<>()).add(checkout);
}
}
// Assign checked-out items to respective guests
for (LibraryGuestModel guest : guests) {
List<CheckoutModel> checkouts =
checkoutsByGuestEmail.getOrDefault(guest.email, new ArrayList<>());
guest.checkedOutItems = checkouts;
}
}
}
27 changes: 27 additions & 0 deletions lesson_13/README.md
@@ -0,0 +1,27 @@
# Lesson 13

## Homework

* Complete [Applying SOLID principles](#applying-solid-principles-bank-atm) exercise.

## Applying SOLID Principles (Bank ATM)

Your task for this assignment is add enhancements to an ATM simulator. The [BankAtm][bankatm-file] is at the center of the model, allowing us to add one or more `CheckingAccount` instances and make withdrawals or deposits via cash or check. You will need to implement at least two of the following functional enhancements to the `BankAtm` class WITHOUT adding a new method. Note that you can update existing methods, however.

### Functional Requirements

* We want to support a `SavingsAccount` that works just like the `CheckingAccount`, but doesn't allow you to write checks against the account.
* We want the `BankAtm` class to support the concept of a `BusinessCheckingAccount`. A business account requires that at least one of the owning accounts is a business.
* In addition to supporting checks and cash, we also want to support the concept of another monetary instrument called a `MoneyOrder`. Unlike a `Check`, a `MoneyOrder` withdraws funds from a source account immediately on creation for the purposes of this simulation..
* For traceability, all of the transactions in the `BankAtm` class should logged. Create an `AuditLog` class that keeps a record of all debits and credits to any account and integrate it with the `BankAtm` class.
* For the `depositFunds` method that accepts a cash amount, we'd like the ability to deposit funds in a variety of currencies. Add a parameter that accepts a currency type and a new object that encapsulates the currency converter logic for converting a cash amount to the account currency type.

### Technical Requirements

* You must integrate new features into the `BankAtm` without adding a new public method. Existing public methods may be modified without breaking existing functionality.
* You must update the `BankAtm` tests and may modify or add other applicable tests.
* Feel free to add the minimal number of classes, interfaces, or abstract classes needed to fulfill each requirement.
* You must update existing javadocs and may add new documentation for new types and methods you introduce.

[bank-folder]: ./bank/
[bankatm-file]: ./bank/bank_app/src/main/java/com/codedifferently/lesson13/bank/BankAtm.java
9 changes: 9 additions & 0 deletions lesson_13/bank/.gitattributes
@@ -0,0 +1,9 @@
#
# https://help.github.com/articles/dealing-with-line-endings/
#
# Linux start script should use lf
/gradlew text eol=lf

# These are Windows script files and should use crlf
*.bat text eol=crlf

5 changes: 5 additions & 0 deletions lesson_13/bank/.gitignore
@@ -0,0 +1,5 @@
# Ignore Gradle project-specific cache directory
.gradle

# Ignore Gradle build output directory
build
64 changes: 64 additions & 0 deletions lesson_13/bank/bank_app/build.gradle.kts
@@ -0,0 +1,64 @@
plugins {
// Apply the application plugin to add support for building a CLI application in Java.
application
eclipse
id("com.diffplug.spotless") version "6.25.0"
id("org.springframework.boot") version "3.2.2"
id("com.adarshr.test-logger") version "4.0.0"
}

apply(plugin = "io.spring.dependency-management")

repositories {
// Use Maven Central for resolving dependencies.
mavenCentral()
}

dependencies {
// Use JUnit Jupiter for testing.
testImplementation("com.codedifferently.instructional:instructional-lib")
testImplementation("org.junit.jupiter:junit-jupiter:5.9.1")
testImplementation("org.springframework.boot:spring-boot-starter-test")
testImplementation("org.assertj:assertj-core:3.25.1")
testImplementation("at.favre.lib:bcrypt:0.10.2")

// This dependency is used by the application.
implementation("com.codedifferently.instructional:instructional-lib")
implementation("com.google.guava:guava:31.1-jre")
implementation("com.google.code.gson:gson:2.10.1")
implementation("org.projectlombok:lombok:1.18.30")
implementation("org.springframework.boot:spring-boot-starter")
}

application {
// Define the main class for the application.
mainClass.set("com.codedifferently.lesson13.Lesson13")
}

tasks.named<Test>("test") {
// Use JUnit Platform for unit tests.
useJUnitPlatform()
}


configure<com.diffplug.gradle.spotless.SpotlessExtension> {

format("misc", {
// define the files to apply `misc` to
target("*.gradle", ".gitattributes", ".gitignore")

// define the steps to apply to those files
trimTrailingWhitespace()
indentWithTabs() // or spaces. Takes an integer argument if you don't like 4
endWithNewline()
})

java {
// don't need to set target, it is inferred from java

// apply a specific flavor of google-java-format
googleJavaFormat()
// fix formatting of type annotations
formatAnnotations()
}
}
@@ -0,0 +1,15 @@
package com.codedifferently.lesson13;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Configuration;

@Configuration
@SpringBootApplication(scanBasePackages = "com.codedifferently")
public class Lesson13 {

public static void main(String[] args) {
var application = new SpringApplication(Lesson13.class);
application.run(args);
}
}
@@ -0,0 +1,87 @@
package com.codedifferently.lesson13.bank;

import com.codedifferently.lesson13.bank.exceptions.AccountNotFoundException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

/** Represents a bank ATM. */
public class BankAtm {
private final Map<UUID, Customer> customerById = new HashMap<>();
private final Map<String, CheckingAccount> accountByNumber = new HashMap<>();

/**
* Adds a checking account to the bank.
*
* @param account The account to add.
*/
public void addAccount(CheckingAccount account) {
accountByNumber.put(account.getAccountNumber(), account);
account
.getOwners()
.forEach(
owner -> {
customerById.put(owner.getId(), owner);
});
}

/**
* Finds all accounts owned by a customer.
*
* @param customerId The ID of the customer.
* @return The unique set of accounts owned by the customer.
*/
public Set<CheckingAccount> findAccountsByCustomerId(UUID customerId) {
return customerById.containsKey(customerId)
? customerById.get(customerId).getAccounts()
: Set.of();
}

/**
* Deposits funds into an account.
*
* @param accountNumber The account number.
* @param amount The amount to deposit.
*/
public void depositFunds(String accountNumber, double amount) {
CheckingAccount account = getAccountOrThrow(accountNumber);
account.deposit(amount);
}

/**
* Deposits funds into an account using a check.
*
* @param accountNumber The account number.
* @param check The check to deposit.
*/
public void depositFunds(String accountNumber, Check check) {
CheckingAccount account = getAccountOrThrow(accountNumber);
check.depositFunds(account);
}

/**
* Withdraws funds from an account.
*
* @param accountNumber
* @param amount
*/
public void withdrawFunds(String accountNumber, double amount) {
CheckingAccount account = getAccountOrThrow(accountNumber);
account.withdraw(amount);
}

/**
* Gets an account by its number or throws an exception if not found.
*
* @param accountNumber The account number.
* @return The account.
*/
private CheckingAccount getAccountOrThrow(String accountNumber) {
CheckingAccount account = accountByNumber.get(accountNumber);
if (account == null || account.isClosed()) {
throw new AccountNotFoundException("Account not found");
}
return account;
}
}