This repository acts as a personal archive for my solutions to EdX course *Data Structures and Software Design* from PennX.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

65 lines
2.0 KiB

  1. /*
  2. * SD2x Homework #8
  3. * This class represents the Data Tier in the three-tier architecture.
  4. * Implement the appropriate methods for this tier below.
  5. */
  6. import java.io.BufferedReader;
  7. import java.io.IOException;
  8. import java.nio.charset.Charset;
  9. import java.nio.file.Path;
  10. import java.nio.file.Paths;
  11. import java.nio.file.Files;
  12. import java.util.Set;
  13. import java.util.HashSet;
  14. public class DataTier {
  15. private String fileName; // the name of the file to read
  16. public DataTier(String inputSource) {
  17. fileName = inputSource;
  18. }
  19. private boolean isSanitized(String str){
  20. if(str == null) return false;
  21. if(str.isEmpty()) return false;
  22. char start = str.charAt(0);
  23. char end = str.charAt(str.length() - 1);
  24. return end != '"' && end != '#' && start != '"';
  25. }
  26. private String sanitize(String str){
  27. if(str.isEmpty()) return "";
  28. String sanitized = str;
  29. char start = str.charAt(0);
  30. char end = str.charAt(str.length() - 1);
  31. if(start == '"') sanitized = str.substring(1,str.length());
  32. if(end == '#' || end == '"') sanitized = str.substring(0,str.length() - 1);
  33. if(!isSanitized(sanitized)) sanitized = sanitize(sanitized);
  34. return sanitized;
  35. }
  36. private Book parseBook(String line){
  37. String[] items = line.split("\t");
  38. return new Book(sanitize(items[0]), sanitize(items[1]), Integer.valueOf(items[2]));
  39. }
  40. public Set<Book> getAllBooks(){
  41. Path file = Paths.get(fileName);
  42. Set<Book> books = new HashSet<Book>();
  43. Charset charset = Charset.forName("US-ASCII");
  44. try (BufferedReader reader = Files.newBufferedReader(file, charset)) {
  45. String line = null;
  46. while ((line = reader.readLine()) != null) {
  47. if(line.isEmpty()) continue;
  48. books.add(parseBook(line));
  49. }
  50. } catch (IOException x) {
  51. System.err.format("IOException: %s%n", x);
  52. }
  53. return books;
  54. }
  55. }