From 11f797d01c03fd3b4cc2fcd7eafc0e102ebd53ed Mon Sep 17 00:00:00 2001 From: Florian Meissner <florian.meissner@mailbox.org> Date: Fri, 23 Jun 2023 16:15:22 +0200 Subject: [PATCH] finished printCanteens --- src/main/java/ohm/softa/a11/App.java | 47 +++++++++++++++++++++------- 1 file changed, 36 insertions(+), 11 deletions(-) diff --git a/src/main/java/ohm/softa/a11/App.java b/src/main/java/ohm/softa/a11/App.java index 0c9b75a..8639757 100644 --- a/src/main/java/ohm/softa/a11/App.java +++ b/src/main/java/ohm/softa/a11/App.java @@ -53,27 +53,52 @@ public class App { } private static void printCanteens() { - System.out.print("Fetching canteens ["); - /* TODO fetch all canteens and print them to STDOUT + /* fetch all canteens and print them to STDOUT * at first get a page without an index to be able to extract the required pagination information * afterwards you can iterate the remaining pages * keep in mind that you should await the process as the user has to select canteen with a specific id */ - OpenMensaAPI api = OpenMensaAPIService.getInstance().getOpenMensaAPI(); - var response = api.getCanteens(); + var response = openMensaAPI.getCanteens(); try { var pageInfo = PageInfo.extractFromResponse(response.get()); - var firstCanteenPage = response.get().body(); + var firstPage = response.get().body(); var N = pageInfo.getTotalCountOfPages(); - var canteens = IntStream.range(2, N).parallel() + /*var canteens = IntStream.range(2, N).parallel() .mapToObj((n) -> api.getCanteens(n).join()) .flatMap(Collection::stream) - .collect(Collectors.toList()); - canteens.addAll(0, firstCanteenPage); - canteens.sort(Comparator.comparingInt(Canteen::getId)); - //canteens = canteens.thenCombine(api.getCanteens(Integer.parseInt(pageN.get())), (l1, l2) -> Stream.concat(l1.parallelStream(), l2.parallelStream())) - canteens.forEach((c) -> System.out.println(c.toString())); + .collect(Collectors.toList());*/ + final var id = CompletableFuture.completedFuture(firstPage); + var request = IntStream + .range(2, N + 1) // one-indexed + .mapToObj(openMensaAPI::getCanteens) + .reduce( + id, + (f1, f2) -> f1.thenCombine( + f2, + // lambda combining two lists + // cannot move to variable, because no templating and no type inference for lambdas + // fuck java + (l1, l2) -> Stream + .concat(l1.stream(), l2.stream()) + .collect(Collectors.toList())) + ) + .thenAccept(canteens -> { + canteens.stream() + .sorted(Comparator.comparingInt(Canteen::getId)) + .forEach(System.out::println); + System.out.println(pageInfo.getTotalCountOfItems() + " <- Header | actual -> " + canteens.size()); + }) + .exceptionally(e -> { + do { + System.out.println(e.getMessage()); + e = e.getCause(); + } while (e != null); + return null; + }); + + // lazy -> eager + request.join(); } catch (InterruptedException | ExecutionException | NumberFormatException e) { e.printStackTrace(); System.out.println("WHYYYYYYYYYYy!!!!"); -- GitLab