JAVA-230 · Lesson 12 of 12 · 33 min
Capstone: a data reporting tool
▶ Video coming soon A video version of this lesson is on the way.
Hamza built the capstone in the week of Monday, December 13, 2027, after his other two courses had handed in their projects, and showed it to Odile and Ingrid on Wednesday, December 22. The brief was Odile's chore from the very first week: every month she copied the repair log, the rental bookings and the till's sales into a spreadsheet and spent an evening making the same table. The program, which Hamza called ReportDesk, reads the three CSV exports for a month, checks every line, produces a readable text report and a JSON summary for the website, and lists every problem it found with the file and line number. It uses nearly every topic of the course, and this lesson walks through it in three steps.
Requirements
Odile and Hamza agreed eight requirements before he wrote any code. Writing them down first made it easy to check the finished program, and it is the same habit JAVA-220 practiced with acceptance tests.
| Number | Requirement | Course topics used |
|---|---|---|
| R1 | Read repairs.csv, rentals.csv and sales.csv for one month from the exports folder | NIO, CSV (lessons 7 and 8) |
| R2 | Parse quoted fields correctly, including commas and doubled quotes in descriptions | CSV parsing (lesson 8) |
| R3 | Turn each line into a typed record; never crash on a bad line, but report it with file and line number | Records, lambdas, Optional (lessons 1, 5) |
| R4 | Count repairs by kind with shop minutes, in a fixed order | Collectors, EnumMap, teeing (lesson 4) |
| R5 | Count rentals by bike type, and list late returns and bikes still out | Streams, java.time, Optional (lessons 3, 5, 6) |
| R6 | Total parts sold per code and in dollars, and name the best seller | toMap with merge, Optional (lessons 4, 5) |
| R7 | Print a text report laid out by a template | Text blocks, formatted (lesson 10) |
| R8 | Save the report and a JSON summary safely, without half-written files | Files.move with ATOMIC_MOVE, JSON (lessons 7, 9) |
Step 1: loading the exports
The data model is a small sealed hierarchy: Repair, Rental and Sale records implement a sealed Row interface, and a Problem record holds anything that went wrong. A Rental's return date is an Optional<LocalDate> component here, even though lesson 5 advised against Optional in fields; Hamza and Ingrid discussed it and kept it because the records are short-lived values inside one report, never stored or sent anywhere, and the Optional makes "still out" impossible to forget. One generic method, load, reads a file and applies a converter function to each line, catching any RuntimeException from a bad line and turning it into a Problem. The real exports live on disk; to keep the program self-contained, the example writes November's three files into a temporary folder first, using text blocks that hold exactly what the shop's systems produced, mistakes included.
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.time.*;
import java.time.format.*;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.function.*;
import java.util.stream.*;
public class Main {
enum Kind { FLAT, BRAKES, GEARS, WHEEL_TRUE, TUNE_UP }
sealed interface Row permits Repair, Rental, Sale { }
record Repair(int ticket, LocalDate day, Kind kind, int minutes) implements Row { }
record Rental(int booking, String bike, LocalDate start, LocalDate due, Optional<LocalDate> returned) implements Row {
boolean late() { return returned.map(r -> r.isAfter(due)).orElse(false); }
long days() { return ChronoUnit.DAYS.between(start, returned.orElse(due)) + 1; }
}
record Sale(LocalDate day, String code, String description, int quantity, long priceCents) implements Row {
long amount() { return quantity * priceCents; }
}
record Problem(String file, int line, String message) { }
static final String REPAIRS = """
ticket,date,kind,minutes
601,2027-10-30,FLAT,20
602,2027-11-02,BRAKES,45
603,2027-11-02,FLAT,15
604,2027-11-09,GEARS,60
605,2027-11-11,TUNE_UP,80
606,2027-11-16,FLAT,25
607,2027-11-18,WHEEL_TRUE,40
608,2027-11-23,BRAKES,35
609,2027-11-25,FLATT,20
610,2027-11-30,FLAT,20
""";
static final String RENTALS = """
booking,bike,start,due,returned
1201,CITY-2,2027-11-04,2027-11-05,2027-11-05
1202,CARGO-1,2027-11-06,2027-11-07,2027-11-09
1203,TANDEM-1,2027-11-13,2027-11-14,2027-11-14
1204,CITY-4,2027-11-20,2027-11-27,
1205,CITY-1,2027-11-26,2027-11-28,2027-11-31
""";
static final String SALES = """
date,code,description,quantity,price_cents
2027-11-02,TUBE-700x25,"Tube, 700x25, Presta valve",3,899
2027-11-09,BELL,"Brass bell, ""ding"" sound",1,650
2027-11-16,CHAIN-11,11-speed chain,1,2499
2027-11-23,TUBE-700x25,"Tube, 700x25, Presta valve",2,899
2027-11-30,PAD-ROAD,Road brake pads,2,1299
""";
static List<String> parseLine(String line) {
List<String> fields = new ArrayList<>();
StringBuilder field = new StringBuilder();
boolean inQuotes = false;
for (int i = 0; i < line.length(); i++) {
char c = line.charAt(i);
if (inQuotes) {
if (c == '"' && i + 1 < line.length() && line.charAt(i + 1) == '"') { field.append('"'); i++; }
else if (c == '"') inQuotes = false;
else field.append(c);
} else if (c == '"') inQuotes = true;
else if (c == ',') { fields.add(field.toString()); field.setLength(0); }
else field.append(c);
}
if (inQuotes) throw new IllegalArgumentException("unclosed quote");
fields.add(field.toString());
return fields;
}
static <T> List<T> load(Path file, Function<List<String>, T> toRecord, List<Problem> problems) throws IOException {
List<T> out = new ArrayList<>();
List<String> lines = Files.readAllLines(file, StandardCharsets.UTF_8);
for (int n = 1; n < lines.size(); n++) {
if (lines.get(n).isBlank()) continue;
try {
out.add(toRecord.apply(parseLine(lines.get(n))));
} catch (RuntimeException e) {
problems.add(new Problem(file.getFileName().toString(), n + 1, e.getClass().getSimpleName() + ": " + e.getMessage()));
}
}
return out;
}
static Repair repair(List<String> f) {
return new Repair(Integer.parseInt(f.get(0)), LocalDate.parse(f.get(1)), Kind.valueOf(f.get(2)), Integer.parseInt(f.get(3)));
}
static Rental rental(List<String> f) {
Optional<LocalDate> back = f.size() > 4 && !f.get(4).isBlank() ? Optional.of(LocalDate.parse(f.get(4))) : Optional.empty();
return new Rental(Integer.parseInt(f.get(0)), f.get(1), LocalDate.parse(f.get(2)), LocalDate.parse(f.get(3)), back);
}
static Sale sale(List<String> f) {
return new Sale(LocalDate.parse(f.get(0)), f.get(1), f.get(2), Integer.parseInt(f.get(3)), Long.parseLong(f.get(4)));
}
static Path writeExports() throws IOException {
Path dir = Files.createTempDirectory("exports").resolve("2027-11");
Files.createDirectories(dir);
Files.writeString(dir.resolve("repairs.csv"), REPAIRS);
Files.writeString(dir.resolve("rentals.csv"), RENTALS);
Files.writeString(dir.resolve("sales.csv"), SALES);
return dir;
}
public static void main(String[] args) throws IOException {
Path dir = writeExports();
List<Problem> problems = new ArrayList<>();
List<Repair> repairs = load(dir.resolve("repairs.csv"), Main::repair, problems);
List<Rental> rentals = load(dir.resolve("rentals.csv"), Main::rental, problems);
List<Sale> sales = load(dir.resolve("sales.csv"), Main::sale, problems);
System.out.println("Loaded " + repairs.size() + " repairs, " + rentals.size() + " rentals, " + sales.size() + " sales");
problems.forEach(p -> System.out.println("Problem in " + p.file() + " line " + p.line() + ": " + p.message()));
System.out.println("Still out: " + rentals.stream().filter(r -> r.returned().isEmpty()).map(Rental::bike).toList());
System.out.println("Bell description: " + sales.get(1).description());
}
}Loaded 9 repairs, 4 rentals, 5 sales Problem in repairs.csv line 10: IllegalArgumentException: No enum constant Main.Kind.FLATT Problem in rentals.csv line 6: DateTimeParseException: Text '2027-11-31' could not be parsed: Invalid date 'NOVEMBER 31' Still out: [CITY-4] Bell description: Brass bell, "ding" sound
What this code does
load is written once and used three times, with Main::repair, Main::rental and Main::sale as the converter, so every file gets the same error handling. Ticket 609 has the misspelled kind FLATT and booking 1205 claims a return on November 31, so Kind.valueOf and LocalDate.parse throw, and each becomes a Problem naming the file and the line instead of stopping the program. The quoted bell description keeps its comma and quotes, and CITY-4 shows up as still out because its returned field was empty.
Two problems in fifteen lines is about what the real exports held each month. Before ReportDesk, the misspelled kind would have been silently dropped from Odile's spreadsheet, and the impossible return date would have been typed in as written.
Step 2: the report
The report method does all the counting with streams and collectors, and lays out the result with one text block. Every map that is printed has a defined order: an EnumMap for repair kinds, so they appear in the order the shop thinks of them, and TreeMaps for bike types and part codes. The month is a YearMonth, which makes "is this date in November 2027?" a single comparison, and the title is formatted with an English locale so it reads the same on any computer. Ticket 601 is dated October 30; it is in the file because ShopBook's export starts from the last Saturday of the previous month, and the month filter quietly leaves it out.
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.time.*;
import java.time.format.*;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.function.*;
import java.util.stream.*;
public class Main {
enum Kind { FLAT, BRAKES, GEARS, WHEEL_TRUE, TUNE_UP }
sealed interface Row permits Repair, Rental, Sale { }
record Repair(int ticket, LocalDate day, Kind kind, int minutes) implements Row { }
record Rental(int booking, String bike, LocalDate start, LocalDate due, Optional<LocalDate> returned) implements Row {
boolean late() { return returned.map(r -> r.isAfter(due)).orElse(false); }
long days() { return ChronoUnit.DAYS.between(start, returned.orElse(due)) + 1; }
}
record Sale(LocalDate day, String code, String description, int quantity, long priceCents) implements Row {
long amount() { return quantity * priceCents; }
}
record Problem(String file, int line, String message) { }
static final String REPAIRS = """
ticket,date,kind,minutes
601,2027-10-30,FLAT,20
602,2027-11-02,BRAKES,45
603,2027-11-02,FLAT,15
604,2027-11-09,GEARS,60
605,2027-11-11,TUNE_UP,80
606,2027-11-16,FLAT,25
607,2027-11-18,WHEEL_TRUE,40
608,2027-11-23,BRAKES,35
609,2027-11-25,FLATT,20
610,2027-11-30,FLAT,20
""";
static final String RENTALS = """
booking,bike,start,due,returned
1201,CITY-2,2027-11-04,2027-11-05,2027-11-05
1202,CARGO-1,2027-11-06,2027-11-07,2027-11-09
1203,TANDEM-1,2027-11-13,2027-11-14,2027-11-14
1204,CITY-4,2027-11-20,2027-11-27,
1205,CITY-1,2027-11-26,2027-11-28,2027-11-31
""";
static final String SALES = """
date,code,description,quantity,price_cents
2027-11-02,TUBE-700x25,"Tube, 700x25, Presta valve",3,899
2027-11-09,BELL,"Brass bell, ""ding"" sound",1,650
2027-11-16,CHAIN-11,11-speed chain,1,2499
2027-11-23,TUBE-700x25,"Tube, 700x25, Presta valve",2,899
2027-11-30,PAD-ROAD,Road brake pads,2,1299
""";
static List<String> parseLine(String line) {
List<String> fields = new ArrayList<>();
StringBuilder field = new StringBuilder();
boolean inQuotes = false;
for (int i = 0; i < line.length(); i++) {
char c = line.charAt(i);
if (inQuotes) {
if (c == '"' && i + 1 < line.length() && line.charAt(i + 1) == '"') { field.append('"'); i++; }
else if (c == '"') inQuotes = false;
else field.append(c);
} else if (c == '"') inQuotes = true;
else if (c == ',') { fields.add(field.toString()); field.setLength(0); }
else field.append(c);
}
if (inQuotes) throw new IllegalArgumentException("unclosed quote");
fields.add(field.toString());
return fields;
}
static <T> List<T> load(Path file, Function<List<String>, T> toRecord, List<Problem> problems) throws IOException {
List<T> out = new ArrayList<>();
List<String> lines = Files.readAllLines(file, StandardCharsets.UTF_8);
for (int n = 1; n < lines.size(); n++) {
if (lines.get(n).isBlank()) continue;
try {
out.add(toRecord.apply(parseLine(lines.get(n))));
} catch (RuntimeException e) {
problems.add(new Problem(file.getFileName().toString(), n + 1, e.getClass().getSimpleName() + ": " + e.getMessage()));
}
}
return out;
}
static Repair repair(List<String> f) {
return new Repair(Integer.parseInt(f.get(0)), LocalDate.parse(f.get(1)), Kind.valueOf(f.get(2)), Integer.parseInt(f.get(3)));
}
static Rental rental(List<String> f) {
Optional<LocalDate> back = f.size() > 4 && !f.get(4).isBlank() ? Optional.of(LocalDate.parse(f.get(4))) : Optional.empty();
return new Rental(Integer.parseInt(f.get(0)), f.get(1), LocalDate.parse(f.get(2)), LocalDate.parse(f.get(3)), back);
}
static Sale sale(List<String> f) {
return new Sale(LocalDate.parse(f.get(0)), f.get(1), f.get(2), Integer.parseInt(f.get(3)), Long.parseLong(f.get(4)));
}
static Path writeExports() throws IOException {
Path dir = Files.createTempDirectory("exports").resolve("2027-11");
Files.createDirectories(dir);
Files.writeString(dir.resolve("repairs.csv"), REPAIRS);
Files.writeString(dir.resolve("rentals.csv"), RENTALS);
Files.writeString(dir.resolve("sales.csv"), SALES);
return dir;
}
static final YearMonth MONTH = YearMonth.of(2027, 11);
static boolean inMonth(LocalDate d) { return YearMonth.from(d).equals(MONTH); }
static String money(long cents) { return String.format("%,.2f", cents / 100.0); }
static String report(String shop, List<Repair> repairs, List<Rental> rentals, List<Sale> sales, List<Problem> problems) {
List<Repair> month = repairs.stream().filter(r -> inMonth(r.day())).toList();
record KindRow(long count, int minutes) { }
Map<Kind, KindRow> byKind = month.stream().collect(Collectors.groupingBy(Repair::kind,
() -> new EnumMap<>(Kind.class),
Collectors.teeing(Collectors.counting(), Collectors.summingInt(Repair::minutes), KindRow::new)));
StringBuilder kinds = new StringBuilder();
byKind.forEach((k, row) -> kinds.append(String.format(" %-11s %3d %6d%n", k, row.count(), row.minutes())));
int minutes = month.stream().mapToInt(Repair::minutes).sum();
List<Rental> rentalsInMonth = rentals.stream().filter(r -> inMonth(r.start())).toList();
Map<String, Long> byType = rentalsInMonth.stream().collect(Collectors.groupingBy(
r -> r.bike().split("-")[0], TreeMap::new, Collectors.counting()));
List<Integer> late = rentalsInMonth.stream().filter(Rental::late).map(Rental::booking).toList();
List<String> out = rentalsInMonth.stream().filter(r -> r.returned().isEmpty()).map(Rental::bike).toList();
Map<String, Integer> units = sales.stream().filter(s -> inMonth(s.day()))
.collect(Collectors.toMap(Sale::code, Sale::quantity, Integer::sum, TreeMap::new));
long partsCents = sales.stream().filter(s -> inMonth(s.day())).mapToLong(Sale::amount).sum();
Optional<String> topPart = units.entrySet().stream().max(Map.Entry.comparingByValue()).map(Map.Entry::getKey);
DateTimeFormatter title = DateTimeFormatter.ofPattern("MMMM yyyy", Locale.ENGLISH);
return """
%s: monthly report for %s
========================================
Repairs: %d (%d min of shop time)
Kind Count Minutes
%s
Rentals: %d %s
Returned late: %s
Still out: %s
Parts sold: %d units, %s dollars before tax
Units by part: %s
Best seller: %s
Problems in the exports: %d
""".formatted(shop, MONTH.format(title), month.size(), minutes, kinds.toString().stripTrailing(),
rentalsInMonth.size(), byType, late, out,
units.values().stream().mapToInt(Integer::intValue).sum(), money(partsCents), units,
topPart.orElse("none"), problems.size());
}
public static void main(String[] args) throws IOException {
Path dir = writeExports();
List<Problem> problems = new ArrayList<>();
List<Repair> repairs = load(dir.resolve("repairs.csv"), Main::repair, problems);
List<Rental> rentals = load(dir.resolve("rentals.csv"), Main::rental, problems);
List<Sale> sales = load(dir.resolve("sales.csv"), Main::sale, problems);
System.out.print(report("Second Gear Cycles, Columbus", repairs, rentals, sales, problems));
}
}Second Gear Cycles, Columbus: monthly report for November 2027
========================================
Repairs: 8 (320 min of shop time)
Kind Count Minutes
FLAT 3 60
BRAKES 2 80
GEARS 1 60
WHEEL_TRUE 1 40
TUNE_UP 1 80
Rentals: 4 {CARGO=1, CITY=2, TANDEM=1}
Returned late: [1202]
Still out: [CITY-4]
Parts sold: 9 units, 102.42 dollars before tax
Units by part: {BELL=1, CHAIN-11=1, PAD-ROAD=2, TUBE-700x25=5}
Best seller: TUBE-700x25
Problems in the exports: 2What this code does
The repair table comes from one groupingBy with an EnumMap and teeing, so each kind's count and minutes are computed in a single pass; ticket 609 is missing because it failed to load, and ticket 601 is left out because it is in October. Rentals are grouped by the text before the dash in the bike code, booking 1202 is late because CARGO-1 came back two days after its due date, and CITY-4 is still out. The parts totals use toMap with Integer::sum to merge the two tube sales, and the best seller comes from an Optional returned by max.
Odile read the printout and asked for one change on the spot: the late list should show bikes, not booking numbers, because she phones people by what they rented. That became the first exercise below.
Step 3: saving the outputs
The last step writes two files into a reports folder next to the month's exports: the text report for Odile and a JSON summary for the website, whose volunteer wanted the month's totals and problem count for a small dashboard. Both are written to a temporary name and moved into place atomically. The JSON is produced with the escaping helper from lesson 9, because the shop's build for this tool deliberately had no dependencies; in the secondgear Gradle build, the same summary is written with Jackson.
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.time.*;
import java.time.format.*;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.function.*;
import java.util.stream.*;
public class Main {
enum Kind { FLAT, BRAKES, GEARS, WHEEL_TRUE, TUNE_UP }
sealed interface Row permits Repair, Rental, Sale { }
record Repair(int ticket, LocalDate day, Kind kind, int minutes) implements Row { }
record Rental(int booking, String bike, LocalDate start, LocalDate due, Optional<LocalDate> returned) implements Row {
boolean late() { return returned.map(r -> r.isAfter(due)).orElse(false); }
long days() { return ChronoUnit.DAYS.between(start, returned.orElse(due)) + 1; }
}
record Sale(LocalDate day, String code, String description, int quantity, long priceCents) implements Row {
long amount() { return quantity * priceCents; }
}
record Problem(String file, int line, String message) { }
static final String REPAIRS = """
ticket,date,kind,minutes
601,2027-10-30,FLAT,20
602,2027-11-02,BRAKES,45
603,2027-11-02,FLAT,15
604,2027-11-09,GEARS,60
605,2027-11-11,TUNE_UP,80
606,2027-11-16,FLAT,25
607,2027-11-18,WHEEL_TRUE,40
608,2027-11-23,BRAKES,35
609,2027-11-25,FLATT,20
610,2027-11-30,FLAT,20
""";
static final String RENTALS = """
booking,bike,start,due,returned
1201,CITY-2,2027-11-04,2027-11-05,2027-11-05
1202,CARGO-1,2027-11-06,2027-11-07,2027-11-09
1203,TANDEM-1,2027-11-13,2027-11-14,2027-11-14
1204,CITY-4,2027-11-20,2027-11-27,
1205,CITY-1,2027-11-26,2027-11-28,2027-11-31
""";
static final String SALES = """
date,code,description,quantity,price_cents
2027-11-02,TUBE-700x25,"Tube, 700x25, Presta valve",3,899
2027-11-09,BELL,"Brass bell, ""ding"" sound",1,650
2027-11-16,CHAIN-11,11-speed chain,1,2499
2027-11-23,TUBE-700x25,"Tube, 700x25, Presta valve",2,899
2027-11-30,PAD-ROAD,Road brake pads,2,1299
""";
static List<String> parseLine(String line) {
List<String> fields = new ArrayList<>();
StringBuilder field = new StringBuilder();
boolean inQuotes = false;
for (int i = 0; i < line.length(); i++) {
char c = line.charAt(i);
if (inQuotes) {
if (c == '"' && i + 1 < line.length() && line.charAt(i + 1) == '"') { field.append('"'); i++; }
else if (c == '"') inQuotes = false;
else field.append(c);
} else if (c == '"') inQuotes = true;
else if (c == ',') { fields.add(field.toString()); field.setLength(0); }
else field.append(c);
}
if (inQuotes) throw new IllegalArgumentException("unclosed quote");
fields.add(field.toString());
return fields;
}
static <T> List<T> load(Path file, Function<List<String>, T> toRecord, List<Problem> problems) throws IOException {
List<T> out = new ArrayList<>();
List<String> lines = Files.readAllLines(file, StandardCharsets.UTF_8);
for (int n = 1; n < lines.size(); n++) {
if (lines.get(n).isBlank()) continue;
try {
out.add(toRecord.apply(parseLine(lines.get(n))));
} catch (RuntimeException e) {
problems.add(new Problem(file.getFileName().toString(), n + 1, e.getClass().getSimpleName() + ": " + e.getMessage()));
}
}
return out;
}
static Repair repair(List<String> f) {
return new Repair(Integer.parseInt(f.get(0)), LocalDate.parse(f.get(1)), Kind.valueOf(f.get(2)), Integer.parseInt(f.get(3)));
}
static Rental rental(List<String> f) {
Optional<LocalDate> back = f.size() > 4 && !f.get(4).isBlank() ? Optional.of(LocalDate.parse(f.get(4))) : Optional.empty();
return new Rental(Integer.parseInt(f.get(0)), f.get(1), LocalDate.parse(f.get(2)), LocalDate.parse(f.get(3)), back);
}
static Sale sale(List<String> f) {
return new Sale(LocalDate.parse(f.get(0)), f.get(1), f.get(2), Integer.parseInt(f.get(3)), Long.parseLong(f.get(4)));
}
static Path writeExports() throws IOException {
Path dir = Files.createTempDirectory("exports").resolve("2027-11");
Files.createDirectories(dir);
Files.writeString(dir.resolve("repairs.csv"), REPAIRS);
Files.writeString(dir.resolve("rentals.csv"), RENTALS);
Files.writeString(dir.resolve("sales.csv"), SALES);
return dir;
}
static final YearMonth MONTH = YearMonth.of(2027, 11);
static boolean inMonth(LocalDate d) { return YearMonth.from(d).equals(MONTH); }
static String money(long cents) { return String.format("%,.2f", cents / 100.0); }
static String report(String shop, List<Repair> repairs, List<Rental> rentals, List<Sale> sales, List<Problem> problems) {
List<Repair> month = repairs.stream().filter(r -> inMonth(r.day())).toList();
record KindRow(long count, int minutes) { }
Map<Kind, KindRow> byKind = month.stream().collect(Collectors.groupingBy(Repair::kind,
() -> new EnumMap<>(Kind.class),
Collectors.teeing(Collectors.counting(), Collectors.summingInt(Repair::minutes), KindRow::new)));
StringBuilder kinds = new StringBuilder();
byKind.forEach((k, row) -> kinds.append(String.format(" %-11s %3d %6d%n", k, row.count(), row.minutes())));
int minutes = month.stream().mapToInt(Repair::minutes).sum();
List<Rental> rentalsInMonth = rentals.stream().filter(r -> inMonth(r.start())).toList();
Map<String, Long> byType = rentalsInMonth.stream().collect(Collectors.groupingBy(
r -> r.bike().split("-")[0], TreeMap::new, Collectors.counting()));
List<Integer> late = rentalsInMonth.stream().filter(Rental::late).map(Rental::booking).toList();
List<String> out = rentalsInMonth.stream().filter(r -> r.returned().isEmpty()).map(Rental::bike).toList();
Map<String, Integer> units = sales.stream().filter(s -> inMonth(s.day()))
.collect(Collectors.toMap(Sale::code, Sale::quantity, Integer::sum, TreeMap::new));
long partsCents = sales.stream().filter(s -> inMonth(s.day())).mapToLong(Sale::amount).sum();
Optional<String> topPart = units.entrySet().stream().max(Map.Entry.comparingByValue()).map(Map.Entry::getKey);
DateTimeFormatter title = DateTimeFormatter.ofPattern("MMMM yyyy", Locale.ENGLISH);
return """
%s: monthly report for %s
========================================
Repairs: %d (%d min of shop time)
Kind Count Minutes
%s
Rentals: %d %s
Returned late: %s
Still out: %s
Parts sold: %d units, %s dollars before tax
Units by part: %s
Best seller: %s
Problems in the exports: %d
""".formatted(shop, MONTH.format(title), month.size(), minutes, kinds.toString().stripTrailing(),
rentalsInMonth.size(), byType, late, out,
units.values().stream().mapToInt(Integer::intValue).sum(), money(partsCents), units,
topPart.orElse("none"), problems.size());
}
static String str(String s) {
return "\"" + s.replace("\\", "\\\\").replace("\"", "\\\"").replace("\n", "\\n") + "\"";
}
static String json(List<Repair> repairs, List<Sale> sales, List<Problem> problems) {
long count = repairs.stream().filter(r -> inMonth(r.day())).count();
int minutes = repairs.stream().filter(r -> inMonth(r.day())).mapToInt(Repair::minutes).sum();
long parts = sales.stream().filter(s -> inMonth(s.day())).mapToLong(Sale::amount).sum();
String problemList = problems.stream()
.map(p -> "{\"file\":" + str(p.file()) + ",\"line\":" + p.line() + ",\"message\":" + str(p.message()) + "}")
.collect(Collectors.joining(",", "[", "]"));
return "{\"month\":" + str(MONTH.toString()) + ",\"repairs\":" + count + ",\"shopMinutes\":" + minutes
+ ",\"partsCents\":" + parts + ",\"problems\":" + problemList + "}";
}
static void save(Path dir, String name, String text) throws IOException {
Path tmp = dir.resolve(name + ".tmp");
Files.writeString(tmp, text, StandardCharsets.UTF_8);
Files.move(tmp, dir.resolve(name), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);
}
public static void main(String[] args) throws IOException {
Path dir = writeExports();
List<Problem> problems = new ArrayList<>();
List<Repair> repairs = load(dir.resolve("repairs.csv"), Main::repair, problems);
List<Rental> rentals = load(dir.resolve("rentals.csv"), Main::rental, problems);
List<Sale> sales = load(dir.resolve("sales.csv"), Main::sale, problems);
Path reports = Files.createDirectories(dir.getParent().resolve("reports"));
save(reports, "2027-11-report.txt", report("Second Gear Cycles, Columbus", repairs, rentals, sales, problems));
save(reports, "2027-11-summary.json", json(repairs, sales, problems));
try (Stream<Path> files = Files.list(reports)) {
files.map(p -> p.getFileName().toString()).sorted().forEach(n -> System.out.println("Wrote " + n));
}
System.out.println(Files.readString(reports.resolve("2027-11-summary.json")));
long reportLines;
try (Stream<String> lines = Files.lines(reports.resolve("2027-11-report.txt"))) {
reportLines = lines.count();
}
System.out.println("Report lines: " + reportLines);
}
}Wrote 2027-11-report.txt
Wrote 2027-11-summary.json
{"month":"2027-11","repairs":8,"shopMinutes":320,"partsCents":10242,"problems":[{"file":"repairs.csv","line":10,"message":"IllegalArgumentException: No enum constant Main.Kind.FLATT"},{"file":"rentals.csv","line":6,"message":"DateTimeParseException: Text '2027-11-31' could not be parsed: Invalid date 'NOVEMBER 31'"}]}
Report lines: 18What this code does
save writes each file under a .tmp name and then moves it into place in one step, so Odile's spreadsheet can never open half a report. The JSON summary is built with the escaping helper from lesson 9 and lists both problems with their files and line numbers, so the website volunteer's script can show them too. The final count reads the saved report back with Files.lines inside try-with-resources, which proves the file on disk is complete.
The summary's problem messages include the exception class names. Ingrid suggested friendlier wording for the website, and Hamza noted it in the project's issue list rather than changing it during the demo.
Review and what came next
The review on December 22 checked each requirement against a run on the real November exports. All eight passed. Ingrid's review comments were about the code rather than the results: the CSV parser should move into the secondgear core module and be replaced by Commons CSV for outside files, the money formatting should use the Money class from JAVA-102 rather than a double, and load deserved a test for a file with only a header line. Odile's comment was shorter: she would not be spending the first evening of January making a table.
| Requirement | How it was checked | Result |
|---|---|---|
| R1 | Run on the real November folder | passed |
| R2 | Descriptions with commas and quotes compared with the till screen | passed |
| R3 | Two known bad lines reported with file and line number | passed |
| R4 | Repair counts compared with Tamsin's paper log | passed |
| R5 | Late and outstanding bikes compared with the rental board | passed |
| R6 | Parts total compared with the till's own monthly total | passed |
| R7 | Report opened and read by Odile | passed |
| R8 | Report and summary present after an interrupted run test | passed |
ReportDesk ran for the first time on its own on Monday, January 3, 2028, for December's exports. The next course, JAVA-240, would make it run three reports at once, and JAVA-250 would read the data straight from the database instead of from CSV files.
Try it yourself
Late returns by bike
Odile asked for the late list to show bikes, not booking numbers. Change the stream so it maps each late rental to its bike instead of its booking.
The program should print Returned late: [CARGO-1, CITY-3].
import java.time.*;
import java.util.*;
public class Main {
record Rental(int booking, String bike, LocalDate due, Optional<LocalDate> returned) {
boolean late() { return returned.map(r -> r.isAfter(due)).orElse(false); }
}
public static void main(String[] args) {
List<Rental> rentals = List.of(
new Rental(1201, "CITY-2", LocalDate.of(2027, 11, 5), Optional.of(LocalDate.of(2027, 11, 5))),
new Rental(1202, "CARGO-1", LocalDate.of(2027, 11, 7), Optional.of(LocalDate.of(2027, 11, 9))),
new Rental(1204, "CITY-4", LocalDate.of(2027, 11, 27), Optional.empty()),
new Rental(1206, "CITY-3", LocalDate.of(2027, 11, 29), Optional.of(LocalDate.of(2027, 11, 30))));
List<Integer> late = rentals.stream().filter(Rental::late).map(Rental::booking).toList();
System.out.println("Returned late: " + late);
}
}Try it yourself
Busiest repair day
Group the repairs by day with groupingBy and counting, using a TreeMap, then find the day with the most repairs with max on the entries. Print it as Busiest day: 2027-11-02 (2 repairs).
If two days tie, the TreeMap's order means max keeps the later one, so this data has a single busiest day.
import java.time.*;
import java.util.*;
import java.util.stream.*;
public class Main {
record Repair(int ticket, LocalDate day, int minutes) { }
public static void main(String[] args) {
List<Repair> repairs = List.of(
new Repair(602, LocalDate.of(2027, 11, 2), 45), new Repair(603, LocalDate.of(2027, 11, 2), 15),
new Repair(604, LocalDate.of(2027, 11, 9), 60), new Repair(605, LocalDate.of(2027, 11, 11), 80),
new Repair(606, LocalDate.of(2027, 11, 16), 25));
System.out.println("Busiest day: ?");
}
}Common mistakes
MistakeWriting a separate error-handling loop for each file.
InsteadWrite one generic loader that takes a converter function and collects problems.
MistakeStopping the whole report at the first bad line.
InsteadTurn each bad line into a problem with its file and line number, and carry on.
MistakePrinting maps whose order depends on hashing.
InsteadUse EnumMap or TreeMap so the report reads the same every month.
MistakeWriting the report straight over last month's file.
InsteadWrite to a temporary name and move it into place atomically.
MistakeStarting to code before agreeing what the report must contain.
InsteadWrite numbered requirements first, then check each one at the end.
Summary and key terms
- ReportDesk brings the course together: numbered requirements agreed first; NIO to read three CSV exports; a quote-aware parser; a sealed hierarchy of records for repairs, rentals and sales, with Optional for a missing return date; one generic loader that takes a converter function and turns bad lines into problems with file and line numbers; streams and collectors, including groupingBy with EnumMap and TreeMap, teeing and toMap with a merge function, to summarize the month; java.time's YearMonth and DAYS.between for dates; a text block template for the report; a hand-written JSON summary with proper escaping; and atomic moves so no half-written file is ever seen.
- The review checked each requirement against real data and produced follow-up work for the next courses.
- Requirement
- A numbered statement of what the program must do, agreed before coding and checked at the end.
- Converter function
- A function passed to a loader that turns one parsed line into a record.
- Problem report
- A list of bad input lines with their file, line number and reason.
- YearMonth
- A java.time type for a month of a particular year, such as 2027-11.
- Atomic save
- Writing to a temporary file and moving it into place in one step.
- Defined order
- An order for printed results that does not depend on hashing, such as enum order or sorted keys.
- Self-contained program
- A program that needs nothing outside itself to run, such as the example that writes its own sample exports.
Practice problems
Work each problem on paper first, then reveal the answer to check.
Why does load take a Function<List<String>, T>?
Show answer
So one method can read any of the three files, given a converter for each.
What happens to ticket 609 with the kind FLATT?
Show answer
Kind.valueOf throws, and load records a problem with the file and line number.
Why is the repair table built with an EnumMap?
Show answer
So the kinds print in the order they are declared, the same every month.
Why is ticket 601 not in the November report?
Show answer
It is dated October 30, and the month filter leaves it out.
How does ReportDesk avoid half-written report files?
Show answer
It writes each file under a temporary name and moves it into place with ATOMIC_MOVE.
Lesson quiz · 5 questions
Score 60% or more to complete this lesson.
Create a free account to save your progress, take quizzes and earn a certificate.