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: Implement data loading for books in CsvDataLoader #306

Closed
wants to merge 5 commits into from
Closed
Changes from 3 commits
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
@@ -0,0 +1,60 @@
package com.codedifferently.lesson12.factory.kevinmason;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import org.springframework.stereotype.Service;

import com.codedifferently.lesson12.factory.LibraryDataLoader;
import com.codedifferently.lesson12.models.LibraryDataModel;
import com.codedifferently.lesson12.models.MediaItemModel;

/**
* A concrete implementation of the LibraryDataLoader interface that loads data from CSV files in
* the app's resources/csv directory.
*/
@Service // Annotation for Spring to recognize this class as a service component
public class CsvDataLoader implements LibraryDataLoader {

// CSV file path
private static final String CSV_FILE_PATH = "src/main/resources/csv/data.csv";

@Override
public LibraryDataModel loadData() throws IOException {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks like you're on the right track, just need to finish.

LibraryDataModel libraryDataModel = new LibraryDataModel();
libraryDataModel.mediaItems = loadMediaItemsFromCsv();
// Load other data if needed
return libraryDataModel;
}

// Method to load media items from CSV
private List<MediaItemModel> loadMediaItemsFromCsv() throws IOException {
List<MediaItemModel> mediaItems = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(CSV_FILE_PATH))) {
String line;
// Skip header line if present
br.readLine();
while ((line = br.readLine()) != null) {
String[] data = line.split(",");
MediaItemModel mediaItem = createMediaItemFromCsvData(data);
mediaItems.add(mediaItem);
}
}
return mediaItems;
}

// Method to create a MediaItemModel object from CSV data
private MediaItemModel createMediaItemFromCsvData(String[] data) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great idea pulling this method. Good use of the single responsibility principle.

MediaItemModel mediaItem = new MediaItemModel();
mediaItem.type = data[0];
mediaItem.id = UUID.fromString(data[1]);
mediaItem.title = data[2];
mediaItem.isbn = data[3];
// Set other attributes as needed
return mediaItem;
}
}