\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.config/CorsConfig.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.config/CorsConfig.html
new file mode 100644
index 0000000..9584a6d
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.config/CorsConfig.html
@@ -0,0 +1 @@
+CorsConfig
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.config/CorsConfig.java.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.config/CorsConfig.java.html
new file mode 100644
index 0000000..49f9243
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.config/CorsConfig.java.html
@@ -0,0 +1,28 @@
+CorsConfig.java
package io.github.js0ny.ilp_coursework.config;
+
+import org.springframework.context.annotation.Configuration;
+import org.springframework.web.servlet.config.annotation.CorsRegistry;
+import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
+
+/**
+ * Global CORS configuration so the frontend running on a different port can call the REST API.
+ */
+@Configuration
+public class CorsConfig implements WebMvcConfigurer {
+
+ private static final String[] ALLOWED_ORIGINS = new String[] {
+ "http://localhost:4173",
+ "http://127.0.0.1:4173",
+ "http://localhost:5173",
+ "http://127.0.0.1:5173"
+ };
+
+ @Override
+ public void addCorsMappings(CorsRegistry registry) {
+ registry.addMapping("/**")
+ .allowedOrigins(ALLOWED_ORIGINS)
+ .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS", "HEAD", "PATCH")
+ .allowedHeaders("*");
+ }
+}
+
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.config/index.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.config/index.html
new file mode 100644
index 0000000..ee51bcf
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.config/index.html
@@ -0,0 +1 @@
+io.github.js0ny.ilp_coursework.config
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.config/index.source.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.config/index.source.html
new file mode 100644
index 0000000..dbeaa8a
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.config/index.source.html
@@ -0,0 +1 @@
+io.github.js0ny.ilp_coursework.config
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.controller/ApiController.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.controller/ApiController.html
new file mode 100644
index 0000000..c7adf67
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.controller/ApiController.html
@@ -0,0 +1 @@
+ApiController
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.controller/ApiController.java.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.controller/ApiController.java.html
new file mode 100644
index 0000000..1713c63
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.controller/ApiController.java.html
@@ -0,0 +1,114 @@
+ApiController.java
package io.github.js0ny.ilp_coursework.controller;
+
+import io.github.js0ny.ilp_coursework.data.common.Angle;
+import io.github.js0ny.ilp_coursework.data.common.LngLat;
+import io.github.js0ny.ilp_coursework.data.common.Region;
+import io.github.js0ny.ilp_coursework.data.request.DistanceRequest;
+import io.github.js0ny.ilp_coursework.data.request.MovementRequest;
+import io.github.js0ny.ilp_coursework.data.request.RegionCheckRequest;
+import io.github.js0ny.ilp_coursework.service.GpsCalculationService;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+/**
+ * Main REST Controller for the ILP Coursework 1 application.
+ *
+ * <p>This class handles incoming HTTP requests for the API under {@code /api/v1} path (defined in
+ * CW1) This is responsible for mapping requests to the appropriate service method and returning the
+ * results as responses. The business logic is delegated to {@link GpsCalculationService}
+ */
+@RestController
+@RequestMapping("/api/v1")
+public class ApiController {
+
+ private static final Logger log = LoggerFactory.getLogger(ApiController.class);
+
+ private final GpsCalculationService gpsService;
+
+ /**
+ * Constructor of the {@code ApiController} with the business logic dependency {@code
+ * GpsCalculationService}
+ *
+ * @param gpsService The service component that contains all business logic, injected by
+ * Spring's DI.
+ */
+ public ApiController(GpsCalculationService gpsService) {
+ this.gpsService = gpsService;
+ }
+
+ /**
+ * Handles GET requests to retrieve the student's Unique ID
+ *
+ * @return A string representing the student ID starting with s
+ */
+ @GetMapping("/uid")
+ public String getUid() {
+ log.info("GET /api/v1/uid");
+ return "s2522255";
+ }
+
+ /**
+ * Handles POST requests to get the distance between two positions
+ *
+ * @param request A {@link DistanceRequest} containing the two coordinates
+ * @return A {@code double} representing the calculated distance
+ */
+ @PostMapping("/distanceTo")
+ public double getDistance(@RequestBody DistanceRequest request) {
+ LngLat position1 = request.position1();
+ LngLat position2 = request.position2();
+ log.info("POST /api/v1/distanceTo position1={} position2={}", position1, position2);
+ return gpsService.calculateDistance(position1, position2);
+ }
+
+ /**
+ * Handles POST requests to check if the two coordinates are close to each other
+ *
+ * @param request A {@link DistanceRequest} containing the two coordinates
+ * @return {@code true} if the distance is less than the predefined threshold, {@code false}
+ * otherwise
+ */
+ @PostMapping("/isCloseTo")
+ public boolean getIsCloseTo(@RequestBody DistanceRequest request) {
+ LngLat position1 = request.position1();
+ LngLat position2 = request.position2();
+ log.info("POST /api/v1/isCloseTo position1={} position2={}", position1, position2);
+ return gpsService.isCloseTo(position1, position2);
+ }
+
+ /**
+ * Handles POST requests to get the next position after an angle of movement
+ *
+ * @param request A {@link MovementRequest} containing the start coordinate and angle of the
+ * movement.
+ * @return A {@link LngLat} representing the destination
+ */
+ @PostMapping("/nextPosition")
+ public LngLat getNextPosition(@RequestBody MovementRequest request) {
+ LngLat start = request.start();
+ Angle angle = new Angle(request.angle());
+ log.info("POST /api/v1/nextPosition start={} angle={}", start, angle);
+ return gpsService.nextPosition(start, angle);
+ }
+
+ /**
+ * Handles POST requests to check if a point is inside a given region
+ *
+ * @param request A {@link RegionCheckRequest} containing the coordinate and the region
+ * @return {@code true} if the coordinate is inside the region, {@code false} otherwise
+ */
+ @PostMapping("/isInRegion")
+ public boolean getIsInRegion(@RequestBody RegionCheckRequest request) {
+ LngLat position = request.position();
+ Region region = request.region();
+ log.info("POST /api/v1/isInRegion position={} region={}", position, region);
+ return gpsService.checkIsInRegion(position, region);
+ }
+}
+
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.controller/DroneController.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.controller/DroneController.html
new file mode 100644
index 0000000..042330f
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.controller/DroneController.html
@@ -0,0 +1 @@
+DroneController
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.controller/DroneController.java.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.controller/DroneController.java.html
new file mode 100644
index 0000000..6caf7ae
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.controller/DroneController.java.html
@@ -0,0 +1,128 @@
+DroneController.java
package io.github.js0ny.ilp_coursework.controller;
+
+import io.github.js0ny.ilp_coursework.data.external.Drone;
+import io.github.js0ny.ilp_coursework.data.request.AttrQueryRequest;
+import io.github.js0ny.ilp_coursework.data.request.MedDispatchRecRequest;
+import io.github.js0ny.ilp_coursework.data.response.DeliveryPathResponse;
+import io.github.js0ny.ilp_coursework.service.DroneAttrComparatorService;
+import io.github.js0ny.ilp_coursework.service.DroneInfoService;
+import io.github.js0ny.ilp_coursework.service.PathFinderService;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.*;
+
+import java.util.List;
+
+/**
+ * Main Rest Controller for the ILP Coursework 2 application.
+ *
+ * <p>This class handles incoming HTTP requests for the API under {@code /api/v1} path (defined in
+ * CW2) The business logic is delegated to {@link DroneInfoService}
+ */
+@RestController
+@RequestMapping("/api/v1")
+public class DroneController {
+
+ private static final Logger log = LoggerFactory.getLogger(DroneController.class);
+
+ private final DroneInfoService droneInfoService;
+ private final DroneAttrComparatorService droneAttrComparatorService;
+ private final PathFinderService pathFinderService;
+
+ /**
+ * Constructor of the {@code DroneController} with the business logic dependency {@code
+ * DroneInfoService}
+ *
+ * <p>We handle the {@code baseUrl} here. Use a predefined URL if the environment variable
+ * {@code ILP_ENDPOINT} is not given.
+ *
+ * @param droneService The service component that contains all business logic
+ */
+ public DroneController(
+ DroneInfoService droneService,
+ DroneAttrComparatorService droneAttrComparatorService,
+ PathFinderService pathFinderService) {
+ this.droneInfoService = droneService;
+ this.droneAttrComparatorService = droneAttrComparatorService;
+ this.pathFinderService = pathFinderService;
+ }
+
+ /**
+ * Handles GET requests to retrieve an array of drones (identified by id) that has the
+ * capability of cooling
+ *
+ * @param state The path variable that indicates the return should have or not have the
+ * capability
+ * @return An array of drone id with cooling capability.
+ */
+ @GetMapping("/dronesWithCooling/{state}")
+ public List<String> getDronesWithCoolingCapability(@PathVariable boolean state) {
+ log.info("GET /api/v1/dronesWithCooling/{}", state);
+ return droneInfoService.dronesWithCooling(state);
+ }
+
+ /**
+ * Handles GET requests to retrieve the drone detail identified by id
+ *
+ * @param id The id of the drone to be queried.
+ * @return 200 with {@link Drone}-style json if success, 404 if {@code id} not found, 400
+ * otherwise
+ */
+ @GetMapping("/droneDetails/{id}")
+ public ResponseEntity<Drone> getDroneDetail(@PathVariable String id) {
+ try {
+ log.info("GET /api/v1/droneDetails/{}", id);
+ Drone drone = droneInfoService.droneDetail(id);
+ return ResponseEntity.ok(drone);
+ } catch (IllegalArgumentException ex) {
+ log.warn("GET /api/v1/droneDetails/{} not found", id);
+ return ResponseEntity.notFound().build();
+ }
+ }
+
+ /**
+ * Handles GET requests to retrieve an array of drone ids that {@code capability.attrName =
+ * attrVal}
+ *
+ * @param attrName The name of the attribute to be queried
+ * @param attrVal The value of the attribute to be queried
+ * @return An array of drone id that matches the attribute name and value
+ */
+ @GetMapping("/queryAsPath/{attrName}/{attrVal}")
+ public List<String> getIdByAttrMap(
+ @PathVariable String attrName, @PathVariable String attrVal) {
+ log.info("GET /api/v1/queryAsPath/{}/{}", attrName, attrVal);
+ return droneAttrComparatorService.dronesWithAttribute(attrName, attrVal);
+ }
+
+ @PostMapping("/query")
+ public List<String> getIdByAttrMapPost(@RequestBody AttrQueryRequest[] attrComparators) {
+ int count = attrComparators == null ? 0 : attrComparators.length;
+ log.info("POST /api/v1/query comparators={}", count);
+ return droneAttrComparatorService.dronesSatisfyingAttributes(attrComparators);
+ }
+
+ @PostMapping("/queryAvailableDrones")
+ public List<String> queryAvailableDrones(@RequestBody MedDispatchRecRequest[] records) {
+ int count = records == null ? 0 : records.length;
+ log.info("POST /api/v1/queryAvailableDrones records={}", count);
+ return droneInfoService.dronesMatchesRequirements(records);
+ }
+
+ @PostMapping("/calcDeliveryPath")
+ public DeliveryPathResponse calculateDeliveryPath(@RequestBody MedDispatchRecRequest[] record) {
+ int count = record == null ? 0 : record.length;
+ log.info("POST /api/v1/calcDeliveryPath records={}", count);
+ return pathFinderService.calculateDeliveryPath(record);
+ }
+
+ @PostMapping("/calcDeliveryPathAsGeoJson")
+ public String calculateDeliveryPathAsGeoJson(@RequestBody MedDispatchRecRequest[] record) {
+ int count = record == null ? 0 : record.length;
+ log.info("POST /api/v1/calcDeliveryPathAsGeoJson records={}", count);
+ return pathFinderService.calculateDeliveryPathAsGeoJson(record);
+ }
+}
+
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.controller/MapMetaController.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.controller/MapMetaController.html
new file mode 100644
index 0000000..cde3d28
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.controller/MapMetaController.html
@@ -0,0 +1 @@
+MapMetaController
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.controller/MapMetaController.java.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.controller/MapMetaController.java.html
new file mode 100644
index 0000000..884eb16
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.controller/MapMetaController.java.html
@@ -0,0 +1,39 @@
+MapMetaController.java
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.controller/index.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.controller/index.html
new file mode 100644
index 0000000..c903120
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.controller/index.html
@@ -0,0 +1 @@
+io.github.js0ny.ilp_coursework.controller
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.controller/index.source.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.controller/index.source.html
new file mode 100644
index 0000000..1a0d4a0
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.controller/index.source.html
@@ -0,0 +1 @@
+io.github.js0ny.ilp_coursework.controller
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.common/AltitudeRange.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.common/AltitudeRange.html
new file mode 100644
index 0000000..f4053eb
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.common/AltitudeRange.html
@@ -0,0 +1 @@
+AltitudeRange
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.common/AltitudeRange.java.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.common/AltitudeRange.java.html
new file mode 100644
index 0000000..43a5e94
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.common/AltitudeRange.java.html
@@ -0,0 +1,13 @@
+AltitudeRange.java
package io.github.js0ny.ilp_coursework.data.common;
+
+import io.github.js0ny.ilp_coursework.data.external.RestrictedArea;
+
+/**
+ * Represents a range of altitude values (that is a fly-zone in {@link RestrictedArea}).
+ *
+ * @param lower The lower bound of the altitude range.
+ * @param upper The upper bound of the altitude range. If {@code upper = -1}, then the region is not
+ * a fly zone.
+ */
+public record AltitudeRange(double lower, double upper) {}
+
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.common/Angle.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.common/Angle.html
new file mode 100644
index 0000000..96f1046
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.common/Angle.html
@@ -0,0 +1 @@
+Angle
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.common/Angle.java.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.common/Angle.java.html
new file mode 100644
index 0000000..ecc1bb4
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.common/Angle.java.html
@@ -0,0 +1,65 @@
+Angle.java
package io.github.js0ny.ilp_coursework.data.common;
+
+/**
+ * Represents the data transfer object for angle
+ *
+ * @param val value of the angle in degrees
+ */
+public record Angle(double degrees) {
+ private static final double STEP = 22.5;
+ private static final double EPSILON = 1e-10;
+
+ public Angle {
+ if (degrees < 0 || degrees >= 360) {
+ throw new IllegalArgumentException("Angle must be in range [0, 360). Got: " + degrees);
+ }
+
+ // Should be a multiple of 22.5 (one of the 16 major directions)
+ double remainder = degrees % STEP;
+
+ // Floating point modulo may have tiny errors, e.g. 45.0 % 22.5 could be 0.0 or
+ // 1.0e-15
+ // So we need to check if the remainder is small enough, or close enough to STEP
+ // (handling negative errors)
+ if (Math.abs(remainder) > EPSILON && Math.abs(remainder - STEP) > EPSILON) {
+ throw new IllegalArgumentException(
+ "Angle must be a multiple of 22.5 (one of the 16 major directions). Got: "
+ + degrees);
+ }
+ }
+
+ public static Angle fromIndex(int index) {
+ if (index < 0 || index > 15) {
+ throw new IllegalArgumentException("Direction index must be between 0 and 15");
+ }
+ return new Angle(index * STEP);
+ }
+
+ public static Angle snap(double rawAngle) {
+ double normalized = normalize(rawAngle);
+ double snapped = Math.round(normalized / STEP) * STEP;
+ return new Angle(normalize(snapped));
+ }
+
+ public Angle offset(int increments) {
+ double rotated = degrees + increments * STEP;
+ return new Angle(normalize(rotated));
+ }
+
+ private static double normalize(double angle) {
+ double normalized = angle % 360;
+ if (normalized < 0) {
+ normalized += 360;
+ }
+ return normalized;
+ }
+
+ public static double toRadians(double degrees) {
+ return Math.toRadians(degrees);
+ }
+
+ public double toRadians() {
+ return Math.toRadians(degrees);
+ }
+}
+
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.common/DroneAvailability.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.common/DroneAvailability.html
new file mode 100644
index 0000000..1d36e6c
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.common/DroneAvailability.html
@@ -0,0 +1 @@
+DroneAvailability
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.common/DroneAvailability.java.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.common/DroneAvailability.java.html
new file mode 100644
index 0000000..428590a
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.common/DroneAvailability.java.html
@@ -0,0 +1,21 @@
+DroneAvailability.java
package io.github.js0ny.ilp_coursework.data.common;
+
+import java.time.DayOfWeek;
+import java.time.LocalTime;
+
+public record DroneAvailability(String id, TimeWindow[] availability) {
+
+ public boolean checkAvailability(DayOfWeek day, LocalTime time) {
+
+ for (var a : availability) {
+ if (a.dayOfWeek().equals(day)) {
+ if (!time.isBefore(a.from()) && !time.isAfter(a.until())) {
+ return true;
+ }
+ }
+ }
+
+ return false;
+ }
+}
+
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.common/DroneCapability.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.common/DroneCapability.html
new file mode 100644
index 0000000..36eea0d
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.common/DroneCapability.html
@@ -0,0 +1 @@
+DroneCapability
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.common/DroneCapability.java.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.common/DroneCapability.java.html
new file mode 100644
index 0000000..534b6ba
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.common/DroneCapability.java.html
@@ -0,0 +1,11 @@
+DroneCapability.java
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.common/DroneEvent.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.common/DroneEvent.html
new file mode 100644
index 0000000..416b2f9
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.common/DroneEvent.html
@@ -0,0 +1 @@
+DroneEvent
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.common/DroneEvent.java.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.common/DroneEvent.java.html
new file mode 100644
index 0000000..5e12da0
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.common/DroneEvent.java.html
@@ -0,0 +1,93 @@
+DroneEvent.java
package io.github.js0ny.ilp_coursework.data.common;
+
+import java.time.LocalDateTime;
+import java.util.List;
+import java.util.Map;
+
+import io.github.js0ny.ilp_coursework.data.response.DeliveryPathResponse;
+
+// Corresponding in Go
+//
+
+/*
+ * type DroneEvent struct {
+ * DroneID string `json:"drone_id"`
+ * Latitude float64 `json:"latitude"`
+ * Longitude float64 `json:"longitude"`
+ * Timestamp string `json:"timestamp"`
+ * }
+ */
+
+public record DroneEvent(
+ String droneId,
+ double latitude,
+ double longitude,
+ String timestamp) {
+
+ final static int STEP = 1; // seconds between events
+ // Helper method that converts from DeliveryPathResponse to List<DroneEvent>
+
+ public static List<DroneEvent> fromPathResponse(DeliveryPathResponse resp) {
+ List<DroneEvent> events = new java.util.ArrayList<>();
+ for (var p : resp.dronePaths()) {
+ String id = p.droneId() + "";
+ for (var d : p.deliveries()) {
+ for (var coord : d.flightPath()) {
+ String timestamp = java.time.Instant.now().toString();
+ events.add(new DroneEvent(
+ id,
+ coord.lat(),
+ coord.lng(),
+ timestamp));
+ }
+ }
+ }
+ return events;
+ }
+
+ // Helper method that converts from DeliveryPathResponse to List<DroneEvent>
+ // with base timestamp
+ public static List<DroneEvent> fromPathResponseWithTimestamp(DeliveryPathResponse resp,
+ LocalDateTime baseTimestamp) {
+ List<DroneEvent> events = new java.util.ArrayList<>();
+ java.time.LocalDateTime timestamp = baseTimestamp;
+ for (var p : resp.dronePaths()) {
+ String id = String.valueOf(p.droneId());
+ for (var d : p.deliveries()) {
+ for (var coord : d.flightPath()) {
+ events.add(new DroneEvent(
+ id,
+ coord.lat(),
+ coord.lng(),
+ timestamp.toString()));
+ timestamp = timestamp.plusSeconds(STEP); // Increment timestamp for each event
+ }
+ }
+ }
+ return events;
+ }
+
+ public static List<DroneEvent> fromPathResponseWithTimestamps(
+ DeliveryPathResponse resp, Map<Integer, LocalDateTime> deliveryTimestamps) {
+ List<DroneEvent> events = new java.util.ArrayList<>();
+ for (var p : resp.dronePaths()) {
+ String id = String.valueOf(p.droneId());
+ for (var d : p.deliveries()) {
+ LocalDateTime timestamp = deliveryTimestamps.get(d.deliveryId());
+ // Fallback to current time if the delivery does not carry a timestamp.
+ System.out.println("Generated event for drone " + id + " at " + timestamp.toString());
+ LocalDateTime current = timestamp != null ? timestamp : LocalDateTime.now();
+ for (var coord : d.flightPath()) {
+ events.add(new DroneEvent(
+ id,
+ coord.lat(),
+ coord.lng(),
+ current.toString()));
+ current = current.plusSeconds(STEP);
+ }
+ }
+ }
+ return events;
+ }
+}
+
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.common/LngLat.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.common/LngLat.html
new file mode 100644
index 0000000..8efbf8c
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.common/LngLat.html
@@ -0,0 +1 @@
+LngLat
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.common/LngLat.java.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.common/LngLat.java.html
new file mode 100644
index 0000000..528127d
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.common/LngLat.java.html
@@ -0,0 +1,36 @@
+LngLat.java
package io.github.js0ny.ilp_coursework.data.common;
+
+/**
+ * Represents the data transfer object for a point or coordinate that defines by a longitude and
+ * latitude
+ *
+ * @param lng longitude of the coordinate/point
+ * @param lat latitude of the coordinate/point
+ */
+public record LngLat(double lng, double lat) {
+ private static final double EPSILON = 1e-9;
+
+ public LngLat {
+ if (lat < -90 || lat > 90) {
+ throw new IllegalArgumentException(
+ "Latitude must be between -90 and +90 degrees. Got: " + lat);
+ }
+
+ if (lng < -180 || lng > 180) {
+ throw new IllegalArgumentException(
+ "Longitude must be between -180 and +180 degrees. Got: " + lng);
+ }
+ }
+
+ public LngLat(LngLatAlt coord) {
+ this(coord.lng(), coord.lat());
+ }
+
+ public boolean isSamePoint(LngLat other) {
+ if (other == null) {
+ return false;
+ }
+ return (Math.abs(lng - other.lng()) < EPSILON && Math.abs(lat - other.lat()) < EPSILON);
+ }
+}
+
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.common/LngLatAlt.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.common/LngLatAlt.html
new file mode 100644
index 0000000..2f6fb6a
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.common/LngLatAlt.html
@@ -0,0 +1 @@
+LngLatAlt
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.common/LngLatAlt.java.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.common/LngLatAlt.java.html
new file mode 100644
index 0000000..e8df375
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.common/LngLatAlt.java.html
@@ -0,0 +1,12 @@
+LngLatAlt.java
package io.github.js0ny.ilp_coursework.data.common;
+
+/**
+ * Represents the data transfer object for a point or coordinate that defines by a longitude and
+ * latitude
+ *
+ * @param lng longitude of the coordinate/point
+ * @param lat latitude of the coordinate/point
+ * @param alt altitude of the coordinate/point
+ */
+public record LngLatAlt(double lng, double lat, double alt) {}
+
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.common/Region.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.common/Region.html
new file mode 100644
index 0000000..931fe40
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.common/Region.html
@@ -0,0 +1 @@
+Region
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.common/Region.java.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.common/Region.java.html
new file mode 100644
index 0000000..6bd8d45
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.common/Region.java.html
@@ -0,0 +1,76 @@
+Region.java
package io.github.js0ny.ilp_coursework.data.common;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+import io.github.js0ny.ilp_coursework.data.request.RegionCheckRequest;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+
+/**
+ * Represents the data transfer object for a region definition
+ *
+ * <p>This record encapsulates the data for calculating if a coordinate is inside the region
+ *
+ * <p>A built-in method {@code isClosedTo} is defined to check this DTO is valid or not in the mean
+ * of closing polygon
+ *
+ * @param name The human-readable name for the region
+ * @param vertices list of coordinates that forms a polygon as a region.
+ * <p>In order to define a valid region, the last element of the list should be the same as the
+ * first, or known as closed
+ * @see RegionCheckRequest
+ * @see io.github.js0ny.ilp_coursework.service.GpsCalculationService#checkIsInRegion(LngLat, Region)
+ */
+public record Region(String name, List<LngLat> vertices) {
+ /**
+ * Magic number 4: For a polygon, 3 edges is required.
+ *
+ * <p>In this dto, edges + 1 vertices is required.
+ */
+ private static final int MINIMUM_VERTICES = 4;
+
+ /**
+ * Method to check if the region has a valid polygon by checking if the {@code vertices} forms a
+ * closed polygon
+ *
+ * @return {@code true} if the {@code vertices} are able to form a polygon and form a closed
+ * polygon
+ */
+ public boolean isClosed() {
+ if (vertices == null || vertices.size() < MINIMUM_VERTICES) {
+ return false;
+ }
+ LngLat first = vertices.getFirst();
+ LngLat last = vertices.getLast();
+ return Objects.equals(last, first);
+ }
+
+ public Map<String, Object> toGeoJson() {
+ try {
+ ObjectMapper mapper = new ObjectMapper();
+
+ List<List<Double>> ring =
+ vertices.stream().map(v -> List.of(v.lng(), v.lat())).toList();
+
+ return Map.of("type", "Polygon", "coordinates", List.of(ring));
+
+ } catch (Exception e) {
+ throw new RuntimeException("Failed to generate GeoJSON", e);
+ }
+ }
+
+ public String toGeoJsonString() {
+ try {
+ ObjectMapper mapper = new ObjectMapper();
+
+ var geoJson = toGeoJson();
+
+ return mapper.writeValueAsString(geoJson);
+ } catch (Exception e) {
+ throw new RuntimeException("Failed to generate GeoJSON", e);
+ }
+ }
+}
+
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.common/TimeWindow.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.common/TimeWindow.html
new file mode 100644
index 0000000..4ab08a8
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.common/TimeWindow.html
@@ -0,0 +1 @@
+TimeWindow
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.common/TimeWindow.java.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.common/TimeWindow.java.html
new file mode 100644
index 0000000..e45992b
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.common/TimeWindow.java.html
@@ -0,0 +1,7 @@
+TimeWindow.java
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.common/index.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.common/index.html
new file mode 100644
index 0000000..4dba206
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.common/index.html
@@ -0,0 +1 @@
+io.github.js0ny.ilp_coursework.data.common
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.common/index.source.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.common/index.source.html
new file mode 100644
index 0000000..dad0625
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.common/index.source.html
@@ -0,0 +1 @@
+io.github.js0ny.ilp_coursework.data.common
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.external/Drone.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.external/Drone.html
new file mode 100644
index 0000000..c8a20c2
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.external/Drone.html
@@ -0,0 +1 @@
+Drone
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.external/Drone.java.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.external/Drone.java.html
new file mode 100644
index 0000000..e91d4d3
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.external/Drone.java.html
@@ -0,0 +1,16 @@
+Drone.java
package io.github.js0ny.ilp_coursework.data.external;
+
+import io.github.js0ny.ilp_coursework.data.common.DroneCapability;
+
+/** Represents the data transfer object for a drone, gained from the endpoints */
+public record Drone(String name, String id, DroneCapability capability) {
+
+ public int parseId() {
+ try {
+ return Integer.parseInt(id);
+ } catch (NumberFormatException e) {
+ return id.hashCode();
+ }
+ }
+}
+
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.external/RestrictedArea.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.external/RestrictedArea.html
new file mode 100644
index 0000000..450134d
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.external/RestrictedArea.html
@@ -0,0 +1 @@
+RestrictedArea
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.external/RestrictedArea.java.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.external/RestrictedArea.java.html
new file mode 100644
index 0000000..0620dd6
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.external/RestrictedArea.java.html
@@ -0,0 +1,20 @@
+RestrictedArea.java
package io.github.js0ny.ilp_coursework.data.external;
+
+import io.github.js0ny.ilp_coursework.data.common.AltitudeRange;
+import io.github.js0ny.ilp_coursework.data.common.LngLat;
+import io.github.js0ny.ilp_coursework.data.common.LngLatAlt;
+import io.github.js0ny.ilp_coursework.data.common.Region;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public record RestrictedArea(String name, int id, AltitudeRange limits, LngLatAlt[] vertices) {
+ public Region toRegion() {
+ List<LngLat> vertices2D = new ArrayList<>();
+ for (var vertex : vertices) {
+ vertices2D.add(new LngLat(vertex.lng(), vertex.lat()));
+ }
+ return new Region(name, vertices2D);
+ }
+}
+
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.external/ServicePoint.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.external/ServicePoint.html
new file mode 100644
index 0000000..85119f3
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.external/ServicePoint.html
@@ -0,0 +1 @@
+ServicePoint
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.external/ServicePoint.java.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.external/ServicePoint.java.html
new file mode 100644
index 0000000..04585da
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.external/ServicePoint.java.html
@@ -0,0 +1,6 @@
+ServicePoint.java
package io.github.js0ny.ilp_coursework.data.external;
+
+import io.github.js0ny.ilp_coursework.data.common.LngLatAlt;
+
+public record ServicePoint(String name, int id, LngLatAlt location) {}
+
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.external/ServicePointDrones.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.external/ServicePointDrones.html
new file mode 100644
index 0000000..da27104
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.external/ServicePointDrones.html
@@ -0,0 +1 @@
+ServicePointDrones
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.external/ServicePointDrones.java.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.external/ServicePointDrones.java.html
new file mode 100644
index 0000000..85c43b3
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.external/ServicePointDrones.java.html
@@ -0,0 +1,19 @@
+ServicePointDrones.java
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.external/index.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.external/index.html
new file mode 100644
index 0000000..afe6240
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.external/index.html
@@ -0,0 +1 @@
+io.github.js0ny.ilp_coursework.data.external
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.external/index.source.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.external/index.source.html
new file mode 100644
index 0000000..b1a15a6
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.external/index.source.html
@@ -0,0 +1 @@
+io.github.js0ny.ilp_coursework.data.external
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.request/AttrQueryRequest.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.request/AttrQueryRequest.html
new file mode 100644
index 0000000..e4c0539
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.request/AttrQueryRequest.html
@@ -0,0 +1 @@
+AttrQueryRequest
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.request/AttrQueryRequest.java.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.request/AttrQueryRequest.java.html
new file mode 100644
index 0000000..91373be
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.request/AttrQueryRequest.java.html
@@ -0,0 +1,7 @@
+AttrQueryRequest.java
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.request/DistanceRequest.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.request/DistanceRequest.html
new file mode 100644
index 0000000..13f2d9c
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.request/DistanceRequest.html
@@ -0,0 +1 @@
+DistanceRequest
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.request/DistanceRequest.java.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.request/DistanceRequest.java.html
new file mode 100644
index 0000000..d91a5d2
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.request/DistanceRequest.java.html
@@ -0,0 +1,15 @@
+DistanceRequest.java
package io.github.js0ny.ilp_coursework.data.request;
+
+import io.github.js0ny.ilp_coursework.data.common.LngLat;
+
+/**
+ * Represents the data transfer object for a distance operation request.
+ *
+ * <p>This record encapsulates the data for several endpoints that involves two {@code LngLatDto}
+ * and serves as the data contract for those API operation
+ *
+ * @param position1 Nested object of {@link LngLat}
+ * @param position2 Nested object of {@link LngLat}
+ */
+public record DistanceRequest(LngLat position1, LngLat position2) {}
+
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.request/MedDispatchRecRequest$MedRequirement.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.request/MedDispatchRecRequest$MedRequirement.html
new file mode 100644
index 0000000..e107076
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.request/MedDispatchRecRequest$MedRequirement.html
@@ -0,0 +1 @@
+MedDispatchRecRequest.MedRequirement
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.request/MedDispatchRecRequest.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.request/MedDispatchRecRequest.html
new file mode 100644
index 0000000..a5f0555
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.request/MedDispatchRecRequest.html
@@ -0,0 +1 @@
+MedDispatchRecRequest
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.request/MedDispatchRecRequest.java.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.request/MedDispatchRecRequest.java.html
new file mode 100644
index 0000000..47d26da
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.request/MedDispatchRecRequest.java.html
@@ -0,0 +1,16 @@
+MedDispatchRecRequest.java
package io.github.js0ny.ilp_coursework.data.request;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+
+import io.github.js0ny.ilp_coursework.data.common.LngLat;
+
+import java.time.LocalDate;
+import java.time.LocalTime;
+
+@JsonIgnoreProperties(ignoreUnknown = true)
+public record MedDispatchRecRequest(
+ int id, LocalDate date, LocalTime time, MedRequirement requirements, LngLat delivery) {
+ @JsonIgnoreProperties(ignoreUnknown = true)
+ public record MedRequirement(float capacity, boolean cooling, boolean heating, float maxCost) {}
+}
+
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.request/MovementRequest.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.request/MovementRequest.html
new file mode 100644
index 0000000..2189b6d
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.request/MovementRequest.html
@@ -0,0 +1 @@
+MovementRequest
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.request/MovementRequest.java.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.request/MovementRequest.java.html
new file mode 100644
index 0000000..ba0a54a
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.request/MovementRequest.java.html
@@ -0,0 +1,17 @@
+MovementRequest.java
package io.github.js0ny.ilp_coursework.data.request;
+
+import io.github.js0ny.ilp_coursework.data.common.LngLat;
+
+/**
+ * Represents the data transfer object for a movement action request.
+ *
+ * <p>This record encapsulates the data for endpoint /api/v1/nextPosition and serves as the data
+ * contract for this API operation
+ *
+ * @param start The starting coordinate of the movement
+ * @param angle The angle to movement in degree. This corresponds to compass directions. For
+ * example: 0 for East, 90 for North
+ * @see io.github.js0ny.ilp_coursework.controller.ApiController#getNextPosition(MovementRequest)
+ */
+public record MovementRequest(LngLat start, double angle) {}
+
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.request/RegionCheckRequest.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.request/RegionCheckRequest.html
new file mode 100644
index 0000000..f94bf44
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.request/RegionCheckRequest.html
@@ -0,0 +1 @@
+RegionCheckRequest
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.request/RegionCheckRequest.java.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.request/RegionCheckRequest.java.html
new file mode 100644
index 0000000..84d6587
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.request/RegionCheckRequest.java.html
@@ -0,0 +1,19 @@
+RegionCheckRequest.java
package io.github.js0ny.ilp_coursework.data.request;
+
+import io.github.js0ny.ilp_coursework.data.common.LngLat;
+import io.github.js0ny.ilp_coursework.data.common.Region;
+
+/**
+ * Represents the data transfer object for a region check request.
+ *
+ * <p>This record encapsulates the data for endpoint /api/v1/isInRegion and serves as the data
+ * contract for this API operation
+ *
+ * <p>
+ *
+ * @param position The coordinate to be checked
+ * @param region The region for the check. This is a nested object represented by {@link Region}
+ * @see io.github.js0ny.ilp_coursework.controller.ApiController#getIsInRegion(RegionCheckRequest)
+ */
+public record RegionCheckRequest(LngLat position, Region region) {}
+
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.request/index.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.request/index.html
new file mode 100644
index 0000000..01aab12
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.request/index.html
@@ -0,0 +1 @@
+io.github.js0ny.ilp_coursework.data.request
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.request/index.source.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.request/index.source.html
new file mode 100644
index 0000000..37fecfc
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.request/index.source.html
@@ -0,0 +1 @@
+io.github.js0ny.ilp_coursework.data.request
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.response/DeliveryPathResponse$DronePath$Delivery.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.response/DeliveryPathResponse$DronePath$Delivery.html
new file mode 100644
index 0000000..22d6eef
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.response/DeliveryPathResponse$DronePath$Delivery.html
@@ -0,0 +1 @@
+DeliveryPathResponse.DronePath.Delivery
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.response/DeliveryPathResponse$DronePath.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.response/DeliveryPathResponse$DronePath.html
new file mode 100644
index 0000000..9896b43
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.response/DeliveryPathResponse$DronePath.html
@@ -0,0 +1 @@
+DeliveryPathResponse.DronePath
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.response/DeliveryPathResponse.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.response/DeliveryPathResponse.html
new file mode 100644
index 0000000..225bab9
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.response/DeliveryPathResponse.html
@@ -0,0 +1 @@
+DeliveryPathResponse
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.response/DeliveryPathResponse.java.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.response/DeliveryPathResponse.java.html
new file mode 100644
index 0000000..909f21c
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.response/DeliveryPathResponse.java.html
@@ -0,0 +1,12 @@
+DeliveryPathResponse.java
package io.github.js0ny.ilp_coursework.data.response;
+
+import io.github.js0ny.ilp_coursework.data.common.LngLat;
+
+import java.util.List;
+
+public record DeliveryPathResponse(float totalCost, int totalMoves, DronePath[] dronePaths) {
+ public record DronePath(int droneId, List<Delivery> deliveries) {
+ public record Delivery(int deliveryId, List<LngLat> flightPath) {}
+ }
+}
+
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.response/index.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.response/index.html
new file mode 100644
index 0000000..9042fa1
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.response/index.html
@@ -0,0 +1 @@
+io.github.js0ny.ilp_coursework.data.response
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.response/index.source.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.response/index.source.html
new file mode 100644
index 0000000..516aad9
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.data.response/index.source.html
@@ -0,0 +1 @@
+io.github.js0ny.ilp_coursework.data.response
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.exception/GlobalExceptionHandler.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.exception/GlobalExceptionHandler.html
new file mode 100644
index 0000000..1ae45e4
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.exception/GlobalExceptionHandler.html
@@ -0,0 +1 @@
+GlobalExceptionHandler
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.exception/GlobalExceptionHandler.java.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.exception/GlobalExceptionHandler.java.html
new file mode 100644
index 0000000..a3b0e93
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.exception/GlobalExceptionHandler.java.html
@@ -0,0 +1,53 @@
+GlobalExceptionHandler.java
package io.github.js0ny.ilp_coursework.exception;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.converter.HttpMessageNotReadableException;
+import org.springframework.web.bind.annotation.ExceptionHandler;
+import org.springframework.web.bind.annotation.ResponseStatus;
+import org.springframework.web.bind.annotation.RestControllerAdvice;
+
+import java.util.Map;
+import java.util.Optional;
+
+/** Class that handles exception or failed request. Map all error requests to 400. */
+@RestControllerAdvice
+public class GlobalExceptionHandler {
+
+ /// Use a logger to save logs instead of passing them to user
+ private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
+ private final Map<String, String> badRequestMap =
+ Map.of("status", "400", "error", "Bad Request");
+
+ @ExceptionHandler(HttpMessageNotReadableException.class)
+ @ResponseStatus(HttpStatus.BAD_REQUEST)
+ public Map<String, String> handleHttpMessageNotReadable(HttpMessageNotReadableException ex) {
+ log.warn("Malformed JSON received: {}", ex.getMessage());
+ return badRequestMap;
+ }
+
+ @ExceptionHandler(IllegalArgumentException.class)
+ @ResponseStatus(HttpStatus.BAD_REQUEST)
+ public Map<String, String> handleIllegalArgument(IllegalArgumentException ex) {
+ String errorMessage =
+ Optional.ofNullable(ex.getMessage()).orElse("Invalid argument provided.");
+ log.warn("Illegal argument in request: {}", errorMessage);
+ return badRequestMap;
+ }
+
+ @ExceptionHandler(NullPointerException.class)
+ @ResponseStatus(HttpStatus.BAD_REQUEST)
+ public Map<String, String> handleNullPointerException(Exception ex) {
+ log.error("NullPointerException occurred. Return 400 by default.", ex);
+ return badRequestMap;
+ }
+
+ @ExceptionHandler(Exception.class)
+ @ResponseStatus(HttpStatus.BAD_REQUEST)
+ public Map<String, String> handleGeneralException(Exception ex) {
+ log.error("Fallback exception received: {}", ex.getMessage());
+ return badRequestMap;
+ }
+}
+
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.exception/index.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.exception/index.html
new file mode 100644
index 0000000..b00d425
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.exception/index.html
@@ -0,0 +1 @@
+io.github.js0ny.ilp_coursework.exception
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.exception/index.source.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.exception/index.source.html
new file mode 100644
index 0000000..f61e5e3
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.exception/index.source.html
@@ -0,0 +1 @@
+io.github.js0ny.ilp_coursework.exception
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.service/DroneAttrComparatorService.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.service/DroneAttrComparatorService.html
new file mode 100644
index 0000000..b536de8
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.service/DroneAttrComparatorService.html
@@ -0,0 +1 @@
+DroneAttrComparatorService
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.service/DroneAttrComparatorService.java.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.service/DroneAttrComparatorService.java.html
new file mode 100644
index 0000000..f877a38
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.service/DroneAttrComparatorService.java.html
@@ -0,0 +1,130 @@
+DroneAttrComparatorService.java
package io.github.js0ny.ilp_coursework.service;
+
+import static io.github.js0ny.ilp_coursework.util.AttrComparator.isValueMatched;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+import io.github.js0ny.ilp_coursework.data.external.Drone;
+import io.github.js0ny.ilp_coursework.data.request.AttrQueryRequest;
+import io.github.js0ny.ilp_coursework.util.AttrOperator;
+
+import org.springframework.stereotype.Service;
+import org.springframework.web.client.RestTemplate;
+
+import java.net.URI;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+@Service
+public class DroneAttrComparatorService {
+
+ private final String baseUrl;
+ private final String dronesEndpoint = "drones";
+ private final RestTemplate restTemplate = new RestTemplate();
+
+ /** Constructor, handles the base url here. */
+ public DroneAttrComparatorService() {
+ String baseUrl = System.getenv("ILP_ENDPOINT");
+ if (baseUrl == null || baseUrl.isBlank()) {
+ this.baseUrl = "https://ilp-rest-2025-bvh6e9hschfagrgy.ukwest-01.azurewebsites.net/";
+ } else {
+ // Defensive: Add '/' to the end of the URL
+ if (!baseUrl.endsWith("/")) {
+ baseUrl += "/";
+ }
+ this.baseUrl = baseUrl;
+ }
+ }
+
+ /**
+ * Return an array of ids of drones with a given attribute name and value.
+ *
+ * <p>Associated service method with {@code /queryAsPath/{attrName}/{attrVal}}
+ *
+ * @param attrName the attribute name to filter on
+ * @param attrVal the attribute value to filter on
+ * @return array of drone ids matching the attribute name and value
+ * @see #dronesWithAttributeCompared(String, String, AttrOperator)
+ * @see io.github.js0ny.ilp_coursework.controller.DroneController#getIdByAttrMap
+ */
+ public List<String> dronesWithAttribute(String attrName, String attrVal) {
+ // Call the helper with EQ operator
+ return dronesWithAttributeCompared(attrName, attrVal, AttrOperator.EQ);
+ }
+
+ /**
+ * Return an array of ids of drones which matches all given complex comparing rules
+ *
+ * @param attrComparators The filter rule with Name, Value and Operator
+ * @return array of drone ids that matches all rules
+ */
+ public List<String> dronesSatisfyingAttributes(AttrQueryRequest[] attrComparators) {
+ Set<String> matchingDroneIds = null;
+ for (var comparator : attrComparators) {
+ String attribute = comparator.attribute();
+ String operator = comparator.operator();
+ String value = comparator.value();
+ AttrOperator op = AttrOperator.fromString(operator);
+ List<String> ids = dronesWithAttributeCompared(attribute, value, op);
+ if (matchingDroneIds == null) {
+ matchingDroneIds = new HashSet<>(ids);
+ } else {
+ matchingDroneIds.retainAll(ids);
+ }
+ }
+ if (matchingDroneIds == null) {
+ return new ArrayList<>();
+ }
+ return matchingDroneIds.stream().toList();
+ }
+
+ /**
+ * Helper that wraps the dynamic querying with different comparison operators
+ *
+ * <p>This method act as a concatenation of {@link
+ * io.github.js0ny.ilp_coursework.util.AttrComparator#isValueMatched(JsonNode, String,
+ * AttrOperator)}
+ *
+ * @param attrName the attribute name to filter on
+ * @param attrVal the attribute value to filter on
+ * @param op the comparison operator
+ * @return array of drone ids matching the attribute name and value (filtered by {@code op})
+ * @see io.github.js0ny.ilp_coursework.util.AttrComparator#isValueMatched(JsonNode, String,
+ * AttrOperator)
+ */
+ private List<String> dronesWithAttributeCompared(
+ String attrName, String attrVal, AttrOperator op) {
+ URI droneUrl = URI.create(baseUrl).resolve(dronesEndpoint);
+ // This is required to make sure the response is valid
+ Drone[] drones = restTemplate.getForObject(droneUrl, Drone[].class);
+
+ if (drones == null) {
+ return new ArrayList<>();
+ }
+
+ // Use Jackson's ObjectMapper to convert DroneDto to JsonNode for dynamic
+ // querying
+ ObjectMapper mapper = new ObjectMapper();
+
+ return Arrays.stream(drones)
+ .filter(
+ drone -> {
+ JsonNode node = mapper.valueToTree(drone);
+ JsonNode attrNode = node.findValue(attrName);
+ if (attrNode != null) {
+ // Manually handle different types of JsonNode
+ return isValueMatched(attrNode, attrVal, op);
+ } else {
+ return false;
+ }
+ })
+ .map(Drone::id)
+ .collect(Collectors.toList());
+ }
+}
+
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.service/DroneInfoService.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.service/DroneInfoService.html
new file mode 100644
index 0000000..462797c
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.service/DroneInfoService.html
@@ -0,0 +1 @@
+DroneInfoService
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.service/DroneInfoService.java.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.service/DroneInfoService.java.html
new file mode 100644
index 0000000..38df0f0
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.service/DroneInfoService.java.html
@@ -0,0 +1,271 @@
+DroneInfoService.java
package io.github.js0ny.ilp_coursework.service;
+
+import io.github.js0ny.ilp_coursework.data.common.LngLat;
+import io.github.js0ny.ilp_coursework.data.external.Drone;
+import io.github.js0ny.ilp_coursework.data.external.RestrictedArea;
+import io.github.js0ny.ilp_coursework.data.external.ServicePoint;
+import io.github.js0ny.ilp_coursework.data.external.ServicePointDrones;
+import io.github.js0ny.ilp_coursework.data.request.MedDispatchRecRequest;
+
+import org.springframework.lang.Nullable;
+import org.springframework.stereotype.Service;
+import org.springframework.web.client.RestTemplate;
+
+import java.net.URI;
+import java.time.DayOfWeek;
+import java.time.LocalDate;
+import java.time.LocalTime;
+import java.util.*;
+import java.util.stream.Collectors;
+
+@Service
+public class DroneInfoService {
+
+ private final String baseUrl;
+ private final String dronesForServicePointsEndpoint = "drones-for-service-points";
+ public static final String servicePointsEndpoint = "service-points";
+ public static final String restrictedAreasEndpoint = "restricted-areas";
+
+ private final RestTemplate restTemplate;
+
+ /** Constructor, handles the base url here. */
+ public DroneInfoService() {
+ this(new RestTemplate());
+ }
+
+ public DroneInfoService(RestTemplate restTemplate) {
+ this.restTemplate = restTemplate;
+ String baseUrl = System.getenv("ILP_ENDPOINT");
+ if (baseUrl == null || baseUrl.isBlank()) {
+ this.baseUrl = "https://ilp-rest-2025-bvh6e9hschfagrgy.ukwest-01.azurewebsites.net/";
+ } else {
+ // Defensive: Add '/' to the end of the URL
+ if (!baseUrl.endsWith("/")) {
+ baseUrl += "/";
+ }
+ this.baseUrl = baseUrl;
+ }
+ }
+
+ /**
+ * Return an array of ids of drones with/without cooling capability
+ *
+ * <p>Associated service method with {@code /dronesWithCooling/{state}}
+ *
+ * @param state determines the capability filtering
+ * @return if {@code state} is true, return ids of drones with cooling capability, else without
+ * cooling
+ * @see
+ * io.github.js0ny.ilp_coursework.controller.DroneController#getDronesWithCoolingCapability(boolean)
+ */
+ public List<String> dronesWithCooling(boolean state) {
+ // URI droneUrl = URI.create(baseUrl).resolve(dronesEndpoint);
+ // Drone[] drones = restTemplate.getForObject(droneUrl, Drone[].class);
+ List<Drone> drones = fetchAllDrones();
+
+ if (drones == null) {
+ return new ArrayList<>();
+ }
+
+ return drones.stream()
+ .filter(drone -> drone.capability().cooling() == state)
+ .map(Drone::id)
+ .collect(Collectors.toList());
+ }
+
+ /**
+ * Return a {@link Drone}-style json data structure with the given {@code id}
+ *
+ * <p>Associated service method with {@code /droneDetails/{id}}
+ *
+ * @param id The id of the drone
+ * @return drone json body of given id
+ * @throws NullPointerException when cannot fetch available drones from remote
+ * @throws IllegalArgumentException when drone with given {@code id} cannot be found this should
+ * lead to a 404
+ * @see io.github.js0ny.ilp_coursework.controller.DroneController#getDroneDetail(String)
+ */
+ public Drone droneDetail(String id) {
+ List<Drone> drones = fetchAllDrones();
+
+ for (var drone : drones) {
+ if (drone.id().equals(id)) {
+ return drone;
+ }
+ }
+
+ // This will result in 404
+ throw new IllegalArgumentException("drone with that ID cannot be found");
+ }
+
+ /**
+ * Return an array of ids of drones that match all the requirements in the medical dispatch
+ * records
+ *
+ * <p>Associated service method with
+ *
+ * @param rec array of medical dispatch records
+ * @return List of drone ids that match all the requirements
+ * @see io.github.js0ny.ilp_coursework.controller.DroneController#queryAvailableDrones
+ */
+ public List<String> dronesMatchesRequirements(MedDispatchRecRequest[] rec) {
+ List<Drone> drones = fetchAllDrones();
+
+ if (rec == null || rec.length == 0) {
+ return drones.stream()
+ .filter(Objects::nonNull)
+ .map(Drone::id)
+ .collect(Collectors.toList());
+ }
+
+ /*
+ * Traverse and filter drones, pass every record's requirement to helper
+ */
+ return drones.stream()
+ .filter(d -> d != null && d.capability() != null)
+ .filter(
+ d ->
+ Arrays.stream(rec)
+ .filter(r -> r != null && r.requirements() != null)
+ .allMatch(r -> droneMatchesRequirement(d, r)))
+ .map(Drone::id)
+ .collect(Collectors.toList());
+ }
+
+ /**
+ * Helper to check if a drone meets the requirement of a medical dispatch.
+ *
+ * @param drone the drone to be checked
+ * @param record the medical dispatch record containing the requirement
+ * @return true if the drone meets the requirement, false otherwise
+ * @throws IllegalArgumentException when record requirements or drone capability is invalid
+ * (capacity and id cannot be null in {@code MedDispathRecDto})
+ */
+ public boolean droneMatchesRequirement(Drone drone, MedDispatchRecRequest record) {
+ var requirements = record.requirements();
+ if (requirements == null) {
+ throw new IllegalArgumentException("requirements cannot be null");
+ }
+ var capability = drone.capability();
+ if (capability == null) {
+ throw new IllegalArgumentException("drone capability cannot be null");
+ }
+
+ float requiredCapacity = requirements.capacity();
+ if (requiredCapacity <= 0 || capability.capacity() < requiredCapacity) {
+ return false;
+ }
+
+ // Use boolean wrapper to allow null (not specified) values
+ boolean requiredCooling = requirements.cooling();
+ boolean requiredHeating = requirements.heating();
+
+ // Case 1: required is null: We don't care about it
+ // Case 2: required is false: We don't care about it (high capability adapts to
+ // low requirements)
+ // Case 3: capability is true: Then always matches
+ // See: https://piazza.com/class/me9vp64lfgf4sn/post/100
+ boolean matchesCooling = !requiredCooling || capability.cooling();
+ boolean matchesHeating = !requiredHeating || capability.heating();
+
+ // Conditions: All requirements matched + availability matched, use helper
+ // For minimal privilege, only pass drone id to check availability
+ return (matchesCooling && matchesHeating && checkAvailability(drone.id(), record)); // &&
+ // checkCost(drone, record) // checkCost is more expensive than
+ // checkAvailability
+ }
+
+ /**
+ * Helper to check if a drone is available at the required date and time
+ *
+ * @param droneId the id of the drone to be checked
+ * @param record the medical dispatch record containing the required date and time
+ * @return true if the drone is available, false otherwise
+ */
+ private boolean checkAvailability(String droneId, MedDispatchRecRequest record) {
+ URI droneUrl = URI.create(baseUrl).resolve(dronesForServicePointsEndpoint);
+ ServicePointDrones[] servicePoints =
+ restTemplate.getForObject(droneUrl, ServicePointDrones[].class);
+
+ LocalDate requiredDate = record.date();
+ DayOfWeek requiredDay = requiredDate.getDayOfWeek();
+ LocalTime requiredTime = record.time();
+
+ assert servicePoints != null;
+ for (var servicePoint : servicePoints) {
+ var drone = servicePoint.locateDroneById(droneId); // Nullable
+ if (drone != null) {
+ return drone.checkAvailability(requiredDay, requiredTime);
+ }
+ }
+
+ return false;
+ }
+
+ private LngLat queryServicePointLocationByDroneId(String droneId) {
+ URI droneUrl = URI.create(baseUrl).resolve(dronesForServicePointsEndpoint);
+ ServicePointDrones[] servicePoints =
+ restTemplate.getForObject(droneUrl, ServicePointDrones[].class);
+
+ assert servicePoints != null;
+ for (var sp : servicePoints) {
+ var drone = sp.locateDroneById(droneId); // Nullable
+ if (drone != null) {
+ return queryServicePointLocation(sp.servicePointId());
+ }
+ }
+
+ return null;
+ }
+
+ @Nullable
+ private LngLat queryServicePointLocation(int id) {
+ URI servicePointUrl = URI.create(baseUrl).resolve(servicePointsEndpoint);
+
+ ServicePoint[] servicePoints =
+ restTemplate.getForObject(servicePointUrl, ServicePoint[].class);
+
+ assert servicePoints != null;
+ for (var sp : servicePoints) {
+ if (sp.id() == id) {
+ // We dont consider altitude
+ return new LngLat(sp.location());
+ }
+ }
+ return null;
+ }
+
+ public List<Drone> fetchAllDrones() {
+ System.out.println("fetchAllDrones called");
+ String dronesEndpoint = "drones";
+ URI droneUrl = URI.create(baseUrl).resolve(dronesEndpoint);
+ System.out.println("Fetching from URL: " + droneUrl);
+ Drone[] drones = restTemplate.getForObject(droneUrl, Drone[].class);
+ return drones == null ? new ArrayList<>() : Arrays.asList(drones);
+ }
+
+ public List<RestrictedArea> fetchRestrictedAreas() {
+ URI restrictedUrl = URI.create(baseUrl).resolve(restrictedAreasEndpoint);
+ RestrictedArea[] restrictedAreas =
+ restTemplate.getForObject(restrictedUrl, RestrictedArea[].class);
+ assert restrictedAreas != null;
+ return Arrays.asList(restrictedAreas);
+ }
+
+ public List<ServicePoint> fetchServicePoints() {
+ URI servicePointUrl = URI.create(baseUrl).resolve(servicePointsEndpoint);
+ ServicePoint[] servicePoints =
+ restTemplate.getForObject(servicePointUrl, ServicePoint[].class);
+ assert servicePoints != null;
+ return Arrays.asList(servicePoints);
+ }
+
+ public List<ServicePointDrones> fetchDronesForServicePoints() {
+ URI servicePointDronesUrl = URI.create(baseUrl).resolve(dronesForServicePointsEndpoint);
+ ServicePointDrones[] servicePointDrones =
+ restTemplate.getForObject(servicePointDronesUrl, ServicePointDrones[].class);
+ assert servicePointDrones != null;
+ return Arrays.asList(servicePointDrones);
+ }
+}
+
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.service/GpsCalculationService.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.service/GpsCalculationService.html
new file mode 100644
index 0000000..8156724
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.service/GpsCalculationService.html
@@ -0,0 +1 @@
+GpsCalculationService
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.service/GpsCalculationService.java.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.service/GpsCalculationService.java.html
new file mode 100644
index 0000000..3c47c3f
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.service/GpsCalculationService.java.html
@@ -0,0 +1,190 @@
+GpsCalculationService.java
package io.github.js0ny.ilp_coursework.service;
+
+import io.github.js0ny.ilp_coursework.data.common.Angle;
+import io.github.js0ny.ilp_coursework.data.common.LngLat;
+import io.github.js0ny.ilp_coursework.data.common.Region;
+import io.github.js0ny.ilp_coursework.data.request.DistanceRequest;
+import io.github.js0ny.ilp_coursework.data.request.MovementRequest;
+import io.github.js0ny.ilp_coursework.data.request.RegionCheckRequest;
+
+import org.springframework.stereotype.Service;
+
+import java.util.List;
+
+/**
+ * Class that handles calculations about Coordinates
+ *
+ * @see LngLat
+ * @see Region
+ */
+@Service
+public class GpsCalculationService {
+
+ /**
+ * Given step size
+ *
+ * @see #nextPosition(LngLat, double)
+ */
+ private static final double STEP = 0.00015;
+
+ /**
+ * Given threshold to judge if two points are close to each other
+ *
+ * @see #isCloseTo(LngLat, LngLat)
+ */
+ private static final double CLOSE_THRESHOLD = 0.00015;
+
+ /**
+ * Calculate the Euclidean distance between {@code position1} and {@code position2}, which are
+ * coordinates defined as {@link LngLat}
+ *
+ * @param position1 The coordinate of the first position
+ * @param position2 The coordinate of the second position
+ * @return The Euclidean distance between {@code position1} and {@code position2}
+ * @see io.github.js0ny.ilp_coursework.controller.ApiController#getDistance(DistanceRequest)
+ */
+ public double calculateDistance(LngLat position1, LngLat position2) {
+ double lngDistance = position2.lng() - position1.lng();
+ double latDistance = position2.lat() - position1.lat();
+ // Euclidean: \sqrt{a^2 + b^2}
+ return Math.sqrt(lngDistance * lngDistance + latDistance * latDistance);
+ }
+
+ public double calculateSteps(LngLat position1, LngLat position2) {
+ double distance = calculateDistance(position1, position2);
+ return distance / STEP;
+ }
+
+ /**
+ * Check if {@code position1} and {@code position2} are close to each other, the threshold is <
+ * 0.00015
+ *
+ * <p>Note that = 0.00015 will be counted as not close to and will return {@code false}
+ *
+ * @param position1 The coordinate of the first position
+ * @param position2 The coordinate of the second position
+ * @return {@code true} if {@code position1} and {@code position2} are close to each other
+ * @see #CLOSE_THRESHOLD
+ * @see io.github.js0ny.ilp_coursework.controller.ApiController#getIsCloseTo(DistanceRequest)
+ */
+ public boolean isCloseTo(LngLat position1, LngLat position2) {
+ double distance = calculateDistance(position1, position2);
+ return distance < CLOSE_THRESHOLD;
+ }
+
+ /**
+ * Returns the next position moved from {@code start} in the direction with {@code angle}, with
+ * step size 0.00015
+ *
+ * @param start The coordinate of the original start point.
+ * @param angle The direction to be moved in angle.
+ * @return The next position moved from {@code start}
+ * @see #STEP
+ * @see io.github.js0ny.ilp_coursework.controller.ApiController#getNextPosition(MovementRequest)
+ */
+ public LngLat nextPosition(LngLat start, Angle angle) {
+ double rad = angle.toRadians();
+ double newLng = Math.cos(rad) * STEP + start.lng();
+ double newLat = Math.sin(rad) * STEP + start.lat();
+ return new LngLat(newLng, newLat);
+ }
+
+ /**
+ * Used to check if the given {@code position} is inside the {@code region}, on edge and vertex
+ * is considered as inside.
+ *
+ * @param position The coordinate of the position.
+ * @param region A {@link Region} that contains name and a list of {@code LngLatDto}
+ * @return {@code true} if {@code position} is inside the {@code region}.
+ * @throws IllegalArgumentException If {@code region} is not closed
+ * @see
+ * io.github.js0ny.ilp_coursework.controller.ApiController#getIsInRegion(RegionCheckRequest)
+ * @see Region#isClosed()
+ */
+ public boolean checkIsInRegion(LngLat position, Region region) throws IllegalArgumentException {
+ if (!region.isClosed()) {
+ // call method from RegionDto to check if not closed
+ throw new IllegalArgumentException("Region is not closed.");
+ }
+ return rayCasting(position, region.vertices());
+ }
+
+ /**
+ * Helper function to {@code checkIsInRegion}, use of ray-casting algorithm to check if inside
+ * the polygon
+ *
+ * @param point The point to check
+ * @param polygon The region that forms a polygon to check if {@code point} sits inside.
+ * @return If the {@code point} sits inside the {@code polygon} then return {@code true}
+ * @see #isPointOnEdge(LngLat, LngLat, LngLat)
+ * @see #checkIsInRegion(LngLat, Region)
+ */
+ private boolean rayCasting(LngLat point, List<LngLat> polygon) {
+ int intersections = 0;
+ int n = polygon.size();
+ for (int i = 0; i < n; ++i) {
+ LngLat a = polygon.get(i);
+ LngLat b = polygon.get((i + 1) % n); // Next vertex
+
+ if (isPointOnEdge(point, a, b)) {
+ return true;
+ }
+
+ // Ensure that `a` is norther than `b`, in order to easy classification
+ if (a.lat() > b.lat()) {
+ LngLat temp = a;
+ a = b;
+ b = temp;
+ }
+
+ // The point is not between a and b in latitude mean, skip this loop
+ if (point.lat() < a.lat() || point.lat() >= b.lat()) {
+ continue;
+ }
+
+ // Skip the case of horizontal edge, already handled in `isPointOnEdge`:w
+ if (a.lat() == b.lat()) {
+ continue;
+ }
+
+ double xIntersection =
+ a.lng() + ((point.lat() - a.lat()) * (b.lng() - a.lng())) / (b.lat() - a.lat());
+
+ if (xIntersection > point.lng()) {
+ ++intersections;
+ }
+ }
+ // If intersections are odd, ray-casting returns true, which the point sits
+ // inside the polygon;
+ // If intersections are even, the point does not sit inside the polygon.
+ return intersections % 2 == 1;
+ }
+
+ /**
+ * Helper function from {@code rayCasting} that used to simply calculation <br>
+ * Used to check if point {@code p} is on the edge formed by {@code a} and {@code b}
+ *
+ * @param p point to be checked on the edge
+ * @param a point that forms the edge
+ * @param b point that forms the edge
+ * @return {@code true} if {@code p} is on {@code ab}
+ * @see #rayCasting(LngLat, List)
+ */
+ private boolean isPointOnEdge(LngLat p, LngLat a, LngLat b) {
+ // Cross product: (p - a) × (b - a)
+ double crossProduct =
+ (p.lng() - a.lng()) * (b.lat() - a.lat())
+ - (p.lat() - a.lat()) * (b.lng() - a.lng());
+ if (Math.abs(crossProduct) > 1e-9) {
+ return false;
+ }
+
+ boolean isWithinLng =
+ p.lng() >= Math.min(a.lng(), b.lng()) && p.lng() <= Math.max(a.lng(), b.lng());
+ boolean isWithinLat =
+ p.lat() >= Math.min(a.lat(), b.lat()) && p.lat() <= Math.max(a.lat(), b.lat());
+
+ return isWithinLng && isWithinLat;
+ }
+}
+
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.service/PathFinderService$PathSegment.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.service/PathFinderService$PathSegment.html
new file mode 100644
index 0000000..e32e797
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.service/PathFinderService$PathSegment.html
@@ -0,0 +1 @@
+PathFinderService.PathSegment
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.service/PathFinderService$TripResult.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.service/PathFinderService$TripResult.html
new file mode 100644
index 0000000..22f68f0
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.service/PathFinderService$TripResult.html
@@ -0,0 +1 @@
+PathFinderService.TripResult
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.service/PathFinderService.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.service/PathFinderService.html
new file mode 100644
index 0000000..c8644ef
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.service/PathFinderService.html
@@ -0,0 +1 @@
+PathFinderService
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.service/PathFinderService.java.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.service/PathFinderService.java.html
new file mode 100644
index 0000000..f8c2f97
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.service/PathFinderService.java.html
@@ -0,0 +1,550 @@
+PathFinderService.java
package io.github.js0ny.ilp_coursework.service;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.SerializationFeature;
+import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
+
+import io.github.js0ny.ilp_coursework.controller.DroneController;
+import io.github.js0ny.ilp_coursework.data.common.Angle;
+import io.github.js0ny.ilp_coursework.data.common.DroneAvailability;
+import io.github.js0ny.ilp_coursework.data.common.LngLat;
+import io.github.js0ny.ilp_coursework.data.common.Region;
+import io.github.js0ny.ilp_coursework.data.external.Drone;
+import io.github.js0ny.ilp_coursework.data.external.RestrictedArea;
+import io.github.js0ny.ilp_coursework.data.external.ServicePoint;
+import io.github.js0ny.ilp_coursework.data.external.ServicePointDrones;
+import io.github.js0ny.ilp_coursework.data.request.MedDispatchRecRequest;
+import io.github.js0ny.ilp_coursework.data.response.DeliveryPathResponse;
+import io.github.js0ny.ilp_coursework.data.response.DeliveryPathResponse.DronePath;
+import io.github.js0ny.ilp_coursework.data.response.DeliveryPathResponse.DronePath.Delivery;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+
+import java.time.LocalDateTime;
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+
+/**
+ * Class that handles calculations about deliverypath
+ *
+ * @see DroneInfoService
+ * @see DroneController
+ * @see DeliveryPathResponse
+ */
+@Service
+public class PathFinderService {
+
+ /**
+ * Hard stop on how many pathfinding iterations we attempt for a single segment before bailing,
+ * useful for preventing infinite loops caused by precision quirks or unexpected map data.
+ *
+ * @see #computePath(LngLat, LngLat)
+ */
+ private static final int MAX_SEGMENT_ITERATIONS = 8_000;
+
+ // Services
+ private final GpsCalculationService gpsCalculationService;
+ private final DroneInfoService droneInfoService;
+ private final ObjectMapper objectMapper;
+ private final List<Drone> drones;
+ private final Map<String, Drone> droneById;
+ private final Map<String, Integer> droneServicePointMap;
+ private final Map<Integer, LngLat> servicePointLocations;
+ private final List<Region> restrictedRegions;
+
+ @Autowired(required = false)
+ private TelemetryService telemetryService;
+
+ /**
+ * Constructor for PathFinderService. The dependencies are injected by Spring and the
+ * constructor pre-computes reference maps used throughout the request lifecycle.
+ *
+ * @param gpsCalculationService Service handling geometric operations.
+ * @param droneInfoService Service that exposes drone metadata and capability information.
+ */
+ public PathFinderService(
+ GpsCalculationService gpsCalculationService, DroneInfoService droneInfoService) {
+ this.gpsCalculationService = gpsCalculationService;
+ this.droneInfoService = droneInfoService;
+ this.objectMapper = new ObjectMapper();
+ objectMapper.registerModule(new JavaTimeModule());
+ objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
+ objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
+
+ this.drones = droneInfoService.fetchAllDrones();
+ List<ServicePoint> servicePoints = droneInfoService.fetchServicePoints();
+ List<ServicePointDrones> servicePointAssignments =
+ droneInfoService.fetchDronesForServicePoints();
+ List<RestrictedArea> restrictedAreas = droneInfoService.fetchRestrictedAreas();
+
+ this.droneById = this.drones.stream().collect(Collectors.toMap(Drone::id, drone -> drone));
+
+ this.droneServicePointMap = new HashMap<>();
+ for (ServicePointDrones assignment : servicePointAssignments) {
+ if (assignment == null || assignment.drones() == null) {
+ continue;
+ }
+ for (DroneAvailability availability : assignment.drones()) {
+ if (availability == null || availability.id() == null) {
+ continue;
+ }
+ droneServicePointMap.put(availability.id(), assignment.servicePointId());
+ }
+ }
+
+ this.servicePointLocations =
+ servicePoints.stream()
+ .collect(
+ Collectors.toMap(
+ ServicePoint::id, sp -> new LngLat(sp.location())));
+
+ this.restrictedRegions = restrictedAreas.stream().map(RestrictedArea::toRegion).toList();
+ }
+
+ /**
+ * Produce a delivery plan for the provided dispatch records. Deliveries are grouped per
+ * compatible drone and per trip to satisfy each drone move limit.
+ *
+ * @param records Dispatch records to be fulfilled.
+ * @return Aggregated path response with cost and move totals.
+ * @see #calculateDeliveryPathAsGeoJson(MedDispatchRecRequest[])
+ */
+ public DeliveryPathResponse calculateDeliveryPath(MedDispatchRecRequest[] records) {
+ if (records == null || records.length == 0) {
+ return new DeliveryPathResponse(0f, 0, new DronePath[0]);
+ }
+
+ Map<Integer, LocalDateTime> deliveryTimestamps = new HashMap<>();
+ for (var r : records) {
+ if (isRestricted(r.delivery())) {
+ throw new IllegalStateException(
+ "Delivery "
+ + r.id()
+ + " is located within a restricted area and cannot be fulfilled");
+ }
+ if (r.date() != null && r.time() != null) {
+ deliveryTimestamps.put(r.id(), LocalDateTime.of(r.date(), r.time()));
+ }
+ }
+
+ Map<String, List<MedDispatchRecRequest>> assigned = assignDeliveries(records);
+
+ List<DronePath> paths = new ArrayList<>();
+ float totalCost = 0f;
+ int totalMoves = 0;
+
+ for (Map.Entry<String, List<MedDispatchRecRequest>> entry : assigned.entrySet()) {
+ String droneId = entry.getKey();
+ Drone drone = droneById.get(droneId);
+ if (drone == null) {
+ continue;
+ }
+ Integer spId = droneServicePointMap.get(droneId);
+ if (spId == null) {
+ continue;
+ }
+ LngLat servicePointLocation = servicePointLocations.get(spId);
+ if (servicePointLocation == null) {
+ continue;
+ }
+
+ List<MedDispatchRecRequest> sortedDeliveries =
+ entry.getValue().stream()
+ .sorted(
+ Comparator.comparingDouble(
+ rec ->
+ gpsCalculationService.calculateDistance(
+ servicePointLocation, rec.delivery())))
+ .toList();
+
+ List<List<MedDispatchRecRequest>> trips =
+ splitTrips(sortedDeliveries, drone, servicePointLocation);
+
+ for (List<MedDispatchRecRequest> trip : trips) {
+ TripResult result = buildTrip(drone, servicePointLocation, trip);
+ if (result != null) {
+ totalCost += result.cost();
+ totalMoves += result.moves();
+ paths.add(result.path());
+ }
+ }
+ }
+
+ var resp = new DeliveryPathResponse(totalCost, totalMoves, paths.toArray(new DronePath[0]));
+
+ if (telemetryService != null) {
+ telemetryService.sendEventAsyncByPathResponse(resp, deliveryTimestamps);
+ }
+
+ return resp;
+ }
+
+ /*
+ * Convenience wrapper around {@link #calculateDeliveryPath} that serializes the
+ * result into a
+ * GeoJSON FeatureCollection suitable for mapping visualization.
+ *
+ * @param records Dispatch records to be fulfilled.
+ *
+ * @return GeoJSON payload representing every delivery flight path.
+ *
+ * @throws IllegalStateException When the payload cannot be serialized.
+ */
+ public String calculateDeliveryPathAsGeoJson(MedDispatchRecRequest[] records) {
+ DeliveryPathResponse response = calculateDeliveryPath(records);
+ Map<String, Object> featureCollection = new LinkedHashMap<>();
+ featureCollection.put("type", "FeatureCollection");
+ List<Map<String, Object>> features = new ArrayList<>();
+
+ if (response != null && response.dronePaths() != null) {
+ for (DronePath dronePath : response.dronePaths()) {
+ if (dronePath == null || dronePath.deliveries() == null) {
+ continue;
+ }
+ for (Delivery delivery : dronePath.deliveries()) {
+ Map<String, Object> feature = new LinkedHashMap<>();
+ feature.put("type", "Feature");
+
+ Map<String, Object> properties = new LinkedHashMap<>();
+ properties.put("droneId", dronePath.droneId());
+ properties.put("deliveryId", delivery.deliveryId());
+ feature.put("properties", properties);
+
+ Map<String, Object> geometry = new LinkedHashMap<>();
+ geometry.put("type", "LineString");
+
+ List<List<Double>> coordinates = new ArrayList<>();
+ if (delivery.flightPath() != null) {
+ for (LngLat point : delivery.flightPath()) {
+ coordinates.add(List.of(point.lng(), point.lat()));
+ }
+ }
+ geometry.put("coordinates", coordinates);
+ feature.put("geometry", geometry);
+ features.add(feature);
+ }
+ }
+ }
+
+ featureCollection.put("features", features);
+
+ try {
+ return objectMapper.writeValueAsString(featureCollection);
+ } catch (JsonProcessingException e) {
+ throw new IllegalStateException("Failed to generate GeoJSON payload", e);
+ }
+ }
+
+ /**
+ * Group dispatch records by their assigned drone, ensuring every record is routed through
+ * {@link #findBestDrone(MedDispatchRecRequest)} exactly once and discarding invalid entries.
+ *
+ * @param records Dispatch records to be grouped.
+ * @return Map keyed by drone ID with the deliveries it should service.
+ */
+ private Map<String, List<MedDispatchRecRequest>> assignDeliveries(
+ MedDispatchRecRequest[] records) {
+ Map<String, List<MedDispatchRecRequest>> assignments = new LinkedHashMap<>();
+ for (MedDispatchRecRequest record : records) {
+ if (record == null || record.delivery() == null) {
+ continue;
+ }
+ String droneId = findBestDrone(record);
+ assignments.computeIfAbsent(droneId, id -> new ArrayList<>()).add(record);
+ }
+ return assignments;
+ }
+
+ /**
+ * Choose the best drone for the provided record. Currently that equates to picking the closest
+ * compatible drone to the delivery location.
+ *
+ * @param record Dispatch record that needs fulfillment.
+ * @return Identifier of the drone that should fly the mission.
+ * @throws IllegalStateException If no available drone can serve the request.
+ */
+ private String findBestDrone(MedDispatchRecRequest record) {
+ double bestScore = Double.MAX_VALUE;
+ String bestDrone = null;
+
+ for (Drone drone : drones) {
+ if (!droneInfoService.droneMatchesRequirement(drone, record)) {
+ continue;
+ }
+ String droneId = drone.id();
+ Integer servicePointId = droneServicePointMap.get(droneId);
+ if (servicePointId == null) {
+ continue;
+ }
+ LngLat servicePointLocation = servicePointLocations.get(servicePointId);
+ if (servicePointLocation == null) {
+ continue;
+ }
+
+ double distance =
+ gpsCalculationService.calculateDistance(
+ servicePointLocation, record.delivery());
+
+ if (distance < bestScore) {
+ bestScore = distance;
+ bestDrone = droneId;
+ }
+ }
+ if (bestDrone == null) {
+ throw new IllegalStateException("No available drone for delivery " + record.id());
+ }
+ return bestDrone;
+ }
+
+ /**
+ * Break a sequence of deliveries into several trips that each respect the drone move limit. The
+ * deliveries should already be ordered by proximity for sensible grouping.
+ *
+ * @param deliveries Deliveries assigned to a drone.
+ * @param drone Drone that will service the deliveries.
+ * @param servicePoint Starting and ending point of every trip.
+ * @return Partitioned trips with at least one delivery each.
+ * @throws IllegalStateException If a single delivery exceeds the drone's move limit.
+ */
+ private List<List<MedDispatchRecRequest>> splitTrips(
+ List<MedDispatchRecRequest> deliveries, Drone drone, LngLat servicePoint) {
+ List<List<MedDispatchRecRequest>> trips = new ArrayList<>();
+ List<MedDispatchRecRequest> currentTrip = new ArrayList<>();
+ for (MedDispatchRecRequest delivery : deliveries) {
+ currentTrip.add(delivery);
+ int requiredMoves = estimateTripMoves(servicePoint, currentTrip);
+ if (requiredMoves > drone.capability().maxMoves()) {
+ currentTrip.remove(currentTrip.size() - 1);
+ if (currentTrip.isEmpty()) {
+ throw new IllegalStateException(
+ "Delivery "
+ + delivery.id()
+ + " exceeds drone "
+ + drone.id()
+ + " move limit");
+ }
+ trips.add(new ArrayList<>(currentTrip));
+ currentTrip.clear();
+ currentTrip.add(delivery);
+ }
+ }
+ if (!currentTrip.isEmpty()) {
+ int requiredMoves = estimateTripMoves(servicePoint, currentTrip);
+ if (requiredMoves > drone.capability().maxMoves()) {
+ throw new IllegalStateException(
+ "Delivery plan exceeds move limit for drone " + drone.id());
+ }
+ trips.add(new ArrayList<>(currentTrip));
+ }
+ return trips;
+ }
+
+ /**
+ * Build a single trip for the provided drone, including the entire flight path to every
+ * delivery and back home. The resulting structure contains the {@link DronePath} representation
+ * as well as cost and moves consumed.
+ *
+ * @param drone Drone executing the trip.
+ * @param servicePoint Starting/ending location of the trip.
+ * @param deliveries Deliveries to include in the trip in execution order.
+ * @return Trip information or {@code null} if no deliveries are provided.
+ * @see DeliveryPathResponse.DronePath
+ */
+ private TripResult buildTrip(
+ Drone drone, LngLat servicePoint, List<MedDispatchRecRequest> deliveries) {
+ if (deliveries == null || deliveries.isEmpty()) {
+ return null;
+ }
+ List<Delivery> flightPlans = new ArrayList<>();
+ LngLat current = servicePoint;
+ int moves = 0;
+
+ for (int i = 0; i < deliveries.size(); i++) {
+ MedDispatchRecRequest delivery = deliveries.get(i);
+ PathSegment toDelivery = computePath(current, delivery.delivery());
+ List<LngLat> flightPath = new ArrayList<>(toDelivery.positions());
+ if (!flightPath.isEmpty()) {
+ LngLat last = flightPath.get(flightPath.size() - 1);
+ if (!last.isSamePoint(delivery.delivery())) {
+ flightPath.add(delivery.delivery());
+ }
+ } else {
+ flightPath.add(current);
+ flightPath.add(delivery.delivery());
+ }
+ flightPath.add(delivery.delivery());
+ moves += toDelivery.moves();
+
+ if (i == deliveries.size() - 1) {
+ PathSegment backHome = computePath(delivery.delivery(), servicePoint);
+ backHome.appendSkippingStart(flightPath);
+ moves += backHome.moves();
+ current = servicePoint;
+ } else {
+ current = delivery.delivery();
+ }
+ flightPlans.add(new Delivery(delivery.id(), flightPath));
+ }
+
+ float cost =
+ drone.capability().costInitial()
+ + drone.capability().costFinal()
+ + (float) (drone.capability().costPerMove() * moves);
+
+ DronePath path = new DronePath(drone.parseId(), flightPlans);
+
+ return new TripResult(path, moves, cost);
+ }
+
+ /**
+ * Estimate the number of moves a prospective trip would need by replaying the path calculation
+ * without mutating any persistent state.
+ *
+ * @param servicePoint Trip origin.
+ * @param deliveries Deliveries that would compose the trip.
+ * @return Total moves required to fly the proposed itinerary.
+ */
+ private int estimateTripMoves(LngLat servicePoint, List<MedDispatchRecRequest> deliveries) {
+ if (deliveries.isEmpty()) {
+ return 0;
+ }
+ int moves = 0;
+ LngLat current = servicePoint;
+ for (MedDispatchRecRequest delivery : deliveries) {
+ PathSegment segment = computePath(current, delivery.delivery());
+ moves += segment.moves();
+ current = delivery.delivery();
+ }
+ moves += computePath(current, servicePoint).moves();
+ return moves;
+ }
+
+ /**
+ * Build a path between {@code start} and {@code target} by repeatedly moving in snapped
+ * increments while avoiding restricted zones.
+ *
+ * @param start Start coordinate.
+ * @param target Destination coordinate.
+ * @return Sequence of visited coordinates and move count.
+ * @see #nextPosition(LngLat, LngLat)
+ */
+ private PathSegment computePath(LngLat start, LngLat target) {
+ List<LngLat> positions = new ArrayList<>();
+ if (start == null || target == null) {
+ return new PathSegment(positions, 0);
+ }
+ positions.add(start);
+ LngLat current = start;
+ int iterations = 0;
+ while (!gpsCalculationService.isCloseTo(current, target)
+ && iterations < MAX_SEGMENT_ITERATIONS) {
+ LngLat next = nextPosition(current, target);
+ if (next.isSamePoint(current)) {
+ break;
+ }
+ positions.add(next);
+ current = next;
+ iterations++;
+ }
+ if (!positions.get(positions.size() - 1).isSamePoint(target)) {
+ positions.add(target);
+ }
+ return new PathSegment(positions, Math.max(0, positions.size() - 1));
+ }
+
+ /**
+ * Determine the next position on the path from {@code current} toward {@code target},
+ * preferring the snapped angle closest to the desired heading that does not infiltrate a
+ * restricted region.
+ *
+ * @param current Current coordinate.
+ * @param target Destination coordinate.
+ * @return Next admissible coordinate or the original point if none can be found.
+ */
+ private LngLat nextPosition(LngLat current, LngLat target) {
+ double desiredAngle =
+ Math.toDegrees(
+ Math.atan2(target.lat() - current.lat(), target.lng() - current.lng()));
+ List<Angle> candidateAngles = buildAngleCandidates(desiredAngle);
+ for (Angle angle : candidateAngles) {
+ LngLat next = gpsCalculationService.nextPosition(current, angle);
+ if (!isRestricted(next)) {
+ return next;
+ }
+ }
+ return current;
+ }
+
+ /**
+ * Build a sequence of candidate angles centered on the desired heading, expanding symmetrically
+ * clockwise and counter-clockwise to explore alternative headings if the primary path is
+ * blocked.
+ *
+ * @param desiredAngle Bearing in degrees between current and target positions.
+ * @return Ordered list of candidate snapped angles.
+ * @see Angle#snap(double)
+ */
+ private List<Angle> buildAngleCandidates(double desiredAngle) {
+ List<Angle> angles = new LinkedList<>();
+ Angle snapped = Angle.snap(desiredAngle);
+ angles.add(snapped);
+ for (int offset = 1; offset <= 8; offset++) {
+ angles.add(snapped.offset(offset));
+ angles.add(snapped.offset(-offset));
+ }
+ return angles;
+ }
+
+ /**
+ * Check whether the provided coordinate falls inside any restricted region.
+ *
+ * @param position Coordinate to inspect.
+ * @return {@code true} if the position intersects a restricted area.
+ * @see #restrictedRegions
+ */
+ private boolean isRestricted(LngLat position) {
+ for (Region region : restrictedRegions) {
+ if (gpsCalculationService.checkIsInRegion(position, region)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Representation of a computed path segment wrapping the visited positions and the number of
+ * moves taken to traverse them.
+ *
+ * @param positions Ordered coordinates that describe the path.
+ * @param moves Number of moves consumed by the path.
+ */
+ private record PathSegment(List<LngLat> positions, int moves) {
+ /**
+ * Append the positions from this segment to {@code target}, skipping the first coordinate
+ * as it is already represented by the last coordinate in the consumer path.
+ *
+ * @param target Mutable list to append to.
+ */
+ private void appendSkippingStart(List<LngLat> target) {
+ for (int i = 1; i < positions.size(); i++) {
+ target.add(positions.get(i));
+ }
+ }
+ }
+
+ /**
+ * Bundle containing the calculated {@link DronePath}, total moves and financial cost for a
+ * single trip.
+ */
+ private record TripResult(DronePath path, int moves, float cost) {}
+}
+
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.service/TelemetryService.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.service/TelemetryService.html
new file mode 100644
index 0000000..61e8b7a
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.service/TelemetryService.html
@@ -0,0 +1 @@
+TelemetryService
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.service/TelemetryService.java.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.service/TelemetryService.java.html
new file mode 100644
index 0000000..c00865f
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.service/TelemetryService.java.html
@@ -0,0 +1,80 @@
+TelemetryService.java
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.service/index.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.service/index.html
new file mode 100644
index 0000000..8292c5b
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.service/index.html
@@ -0,0 +1 @@
+io.github.js0ny.ilp_coursework.service
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.service/index.source.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.service/index.source.html
new file mode 100644
index 0000000..47cf431
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.service/index.source.html
@@ -0,0 +1 @@
+io.github.js0ny.ilp_coursework.service
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.util/AttrComparator.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.util/AttrComparator.html
new file mode 100644
index 0000000..57b10b4
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.util/AttrComparator.html
@@ -0,0 +1 @@
+AttrComparator
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.util/AttrComparator.java.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.util/AttrComparator.java.html
new file mode 100644
index 0000000..2ab72ba
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.util/AttrComparator.java.html
@@ -0,0 +1,64 @@
+AttrComparator.java
package io.github.js0ny.ilp_coursework.util;
+
+import com.fasterxml.jackson.databind.JsonNode;
+
+import java.math.BigDecimal;
+
+/**
+ * Comparator for attribute values in {@code JsonNode}.
+ *
+ * <p>This is a helper for dynamic querying.
+ */
+public class AttrComparator {
+ /**
+ * Helper for dynamic querying, to compare the json value with given value in {@code String}.
+ *
+ * @param node The {@code JsonNode} to be compared
+ * @param attrVal The Value passed, in {@code String}
+ * @param op The comparison operator
+ * @return {@code true} if given values are equal, otherwise false.
+ */
+ public static boolean isValueMatched(JsonNode node, String attrVal, AttrOperator op) {
+ if (node.isTextual()) {
+ return compareStrings(node.asText(), attrVal, op);
+ } else if (node.isNumber()) {
+ // return Double.compare(node.asDouble(), Double.parseDouble(attrVal)) == 0;
+ return compareNumbers(node.decimalValue(), new BigDecimal(attrVal), op);
+ } else if (node.isBoolean()) {
+ return compareBooleans(node.asBoolean(), Boolean.parseBoolean(attrVal), op);
+ } else {
+ return false;
+ }
+ }
+
+ private static boolean compareNumbers(BigDecimal nodeVal, BigDecimal attrVal, AttrOperator op) {
+ int comparison = nodeVal.compareTo(attrVal);
+ return switch (op) {
+ case EQ -> comparison == 0;
+ case GT -> comparison > 0;
+ case LT -> comparison < 0;
+ case NE -> comparison != 0;
+ };
+ }
+
+ private static boolean compareStrings(String nodeVal, String attrVal, AttrOperator op) {
+ return switch (op) {
+ case EQ -> nodeVal.equals(attrVal);
+ default -> !nodeVal.equals(attrVal);
+ // case NE -> !nodeVal.equals(attrVal);
+ // case GT -> !nodeVal.equals(attrVal);// > 0;
+ // case LT -> !nodeVal.equals(attrVal);// < 0;
+ };
+ }
+
+ private static boolean compareBooleans(boolean nodeVal, boolean attrVal, AttrOperator op) {
+ return switch (op) {
+ case EQ -> nodeVal == attrVal;
+ default -> nodeVal != attrVal;
+ // case NE -> nodeVal != attrVal;
+ // case GT -> !nodeVal && attrVal; // false < true
+ // case LT -> nodeVal && !attrVal; // true > false
+ };
+ }
+}
+
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.util/AttrOperator.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.util/AttrOperator.html
new file mode 100644
index 0000000..7981259
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.util/AttrOperator.html
@@ -0,0 +1 @@
+AttrOperator
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.util/AttrOperator.java.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.util/AttrOperator.java.html
new file mode 100644
index 0000000..3927cca
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.util/AttrOperator.java.html
@@ -0,0 +1,24 @@
+AttrOperator.java
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.util/index.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.util/index.html
new file mode 100644
index 0000000..419fdab
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.util/index.html
@@ -0,0 +1 @@
+io.github.js0ny.ilp_coursework.util
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.util/index.source.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.util/index.source.html
new file mode 100644
index 0000000..eb58565
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework.util/index.source.html
@@ -0,0 +1 @@
+io.github.js0ny.ilp_coursework.util
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework/IlpCourseworkApplication.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework/IlpCourseworkApplication.html
new file mode 100644
index 0000000..970275d
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework/IlpCourseworkApplication.html
@@ -0,0 +1 @@
+IlpCourseworkApplication
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework/IlpCourseworkApplication.java.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework/IlpCourseworkApplication.java.html
new file mode 100644
index 0000000..1469779
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework/IlpCourseworkApplication.java.html
@@ -0,0 +1,13 @@
+IlpCourseworkApplication.java
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework/index.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework/index.html
new file mode 100644
index 0000000..9b13bd4
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework/index.html
@@ -0,0 +1 @@
+io.github.js0ny.ilp_coursework
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework/index.source.html b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework/index.source.html
new file mode 100644
index 0000000..ff17d40
--- /dev/null
+++ b/docs/reports/jacoco/test/html/io.github.js0ny.ilp_coursework/index.source.html
@@ -0,0 +1 @@
+io.github.js0ny.ilp_coursework
\ No newline at end of file
diff --git a/docs/reports/jacoco/test/html/jacoco-resources/branchfc.gif b/docs/reports/jacoco/test/html/jacoco-resources/branchfc.gif
new file mode 100644
index 0000000..989b46d
Binary files /dev/null and b/docs/reports/jacoco/test/html/jacoco-resources/branchfc.gif differ
diff --git a/docs/reports/jacoco/test/html/jacoco-resources/branchnc.gif b/docs/reports/jacoco/test/html/jacoco-resources/branchnc.gif
new file mode 100644
index 0000000..1933e07
Binary files /dev/null and b/docs/reports/jacoco/test/html/jacoco-resources/branchnc.gif differ
diff --git a/docs/reports/jacoco/test/html/jacoco-resources/branchpc.gif b/docs/reports/jacoco/test/html/jacoco-resources/branchpc.gif
new file mode 100644
index 0000000..cbf711b
Binary files /dev/null and b/docs/reports/jacoco/test/html/jacoco-resources/branchpc.gif differ
diff --git a/docs/reports/jacoco/test/html/jacoco-resources/bundle.gif b/docs/reports/jacoco/test/html/jacoco-resources/bundle.gif
new file mode 100644
index 0000000..fca9c53
Binary files /dev/null and b/docs/reports/jacoco/test/html/jacoco-resources/bundle.gif differ
diff --git a/docs/reports/jacoco/test/html/jacoco-resources/class.gif b/docs/reports/jacoco/test/html/jacoco-resources/class.gif
new file mode 100644
index 0000000..eb348fb
Binary files /dev/null and b/docs/reports/jacoco/test/html/jacoco-resources/class.gif differ
diff --git a/docs/reports/jacoco/test/html/jacoco-resources/down.gif b/docs/reports/jacoco/test/html/jacoco-resources/down.gif
new file mode 100644
index 0000000..440a14d
Binary files /dev/null and b/docs/reports/jacoco/test/html/jacoco-resources/down.gif differ
diff --git a/docs/reports/jacoco/test/html/jacoco-resources/greenbar.gif b/docs/reports/jacoco/test/html/jacoco-resources/greenbar.gif
new file mode 100644
index 0000000..0ba6567
Binary files /dev/null and b/docs/reports/jacoco/test/html/jacoco-resources/greenbar.gif differ
diff --git a/docs/reports/jacoco/test/html/jacoco-resources/group.gif b/docs/reports/jacoco/test/html/jacoco-resources/group.gif
new file mode 100644
index 0000000..a4ea580
Binary files /dev/null and b/docs/reports/jacoco/test/html/jacoco-resources/group.gif differ
diff --git a/docs/reports/jacoco/test/html/jacoco-resources/method.gif b/docs/reports/jacoco/test/html/jacoco-resources/method.gif
new file mode 100644
index 0000000..7d24707
Binary files /dev/null and b/docs/reports/jacoco/test/html/jacoco-resources/method.gif differ
diff --git a/docs/reports/jacoco/test/html/jacoco-resources/package.gif b/docs/reports/jacoco/test/html/jacoco-resources/package.gif
new file mode 100644
index 0000000..131c28d
Binary files /dev/null and b/docs/reports/jacoco/test/html/jacoco-resources/package.gif differ
diff --git a/docs/reports/jacoco/test/html/jacoco-resources/prettify.css b/docs/reports/jacoco/test/html/jacoco-resources/prettify.css
new file mode 100644
index 0000000..be5166e
--- /dev/null
+++ b/docs/reports/jacoco/test/html/jacoco-resources/prettify.css
@@ -0,0 +1,13 @@
+/* Pretty printing styles. Used with prettify.js. */
+
+.str { color: #2A00FF; }
+.kwd { color: #7F0055; font-weight:bold; }
+.com { color: #3F5FBF; }
+.typ { color: #606; }
+.lit { color: #066; }
+.pun { color: #660; }
+.pln { color: #000; }
+.tag { color: #008; }
+.atn { color: #606; }
+.atv { color: #080; }
+.dec { color: #606; }
diff --git a/docs/reports/jacoco/test/html/jacoco-resources/prettify.js b/docs/reports/jacoco/test/html/jacoco-resources/prettify.js
new file mode 100644
index 0000000..b2766fe
--- /dev/null
+++ b/docs/reports/jacoco/test/html/jacoco-resources/prettify.js
@@ -0,0 +1,1510 @@
+// Copyright (C) 2006 Google Inc.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+
+/**
+ * @fileoverview
+ * some functions for browser-side pretty printing of code contained in html.
+ *
+ *
+ * For a fairly comprehensive set of languages see the
+ * README
+ * file that came with this source. At a minimum, the lexer should work on a
+ * number of languages including C and friends, Java, Python, Bash, SQL, HTML,
+ * XML, CSS, Javascript, and Makefiles. It works passably on Ruby, PHP and Awk
+ * and a subset of Perl, but, because of commenting conventions, doesn't work on
+ * Smalltalk, Lisp-like, or CAML-like languages without an explicit lang class.
+ *
+ * Usage:
+ *
include this source file in an html page via
+ * {@code }
+ *
define style rules. See the example page for examples.
+ *
mark the {@code
} and {@code } tags in your source with
+ * {@code class=prettyprint.}
+ * You can also use the (html deprecated) {@code } tag, but the pretty
+ * printer needs to do more substantial DOM manipulations to support that, so
+ * some css styles may not be preserved.
+ *
+ * That's it. I wanted to keep the API as simple as possible, so there's no
+ * need to specify which language the code is in, but if you wish, you can add
+ * another class to the {@code
} or {@code } element to specify the
+ * language, as in {@code
}. Any class that
+ * starts with "lang-" followed by a file extension, specifies the file type.
+ * See the "lang-*.js" files in this directory for code that implements
+ * per-language file handlers.
+ *
+ * Change log:
+ * cbeust, 2006/08/22
+ *
+ * Java annotations (start with "@") are now captured as literals ("lit")
+ *
+ * @requires console
+ */
+
+// JSLint declarations
+/*global console, document, navigator, setTimeout, window */
+
+/**
+ * Split {@code prettyPrint} into multiple timeouts so as not to interfere with
+ * UI events.
+ * If set to {@code false}, {@code prettyPrint()} is synchronous.
+ */
+window['PR_SHOULD_USE_CONTINUATION'] = true;
+
+/** the number of characters between tab columns */
+window['PR_TAB_WIDTH'] = 8;
+
+/** Walks the DOM returning a properly escaped version of innerHTML.
+ * @param {Node} node
+ * @param {Array.} out output buffer that receives chunks of HTML.
+ */
+window['PR_normalizedHtml']
+
+/** Contains functions for creating and registering new language handlers.
+ * @type {Object}
+ */
+ = window['PR']
+
+/** Pretty print a chunk of code.
+ *
+ * @param {string} sourceCodeHtml code as html
+ * @return {string} code as html, but prettier
+ */
+ = window['prettyPrintOne']
+/** Find all the {@code
} and {@code } tags in the DOM with
+ * {@code class=prettyprint} and prettify them.
+ * @param {Function?} opt_whenDone if specified, called when the last entry
+ * has been finished.
+ */
+ = window['prettyPrint'] = void 0;
+
+/** browser detection. @extern @returns false if not IE, otherwise the major version. */
+window['_pr_isIE6'] = function () {
+ var ieVersion = navigator && navigator.userAgent &&
+ navigator.userAgent.match(/\bMSIE ([678])\./);
+ ieVersion = ieVersion ? +ieVersion[1] : false;
+ window['_pr_isIE6'] = function () { return ieVersion; };
+ return ieVersion;
+};
+
+
+(function () {
+ // Keyword lists for various languages.
+ var FLOW_CONTROL_KEYWORDS =
+ "break continue do else for if return while ";
+ var C_KEYWORDS = FLOW_CONTROL_KEYWORDS + "auto case char const default " +
+ "double enum extern float goto int long register short signed sizeof " +
+ "static struct switch typedef union unsigned void volatile ";
+ var COMMON_KEYWORDS = C_KEYWORDS + "catch class delete false import " +
+ "new operator private protected public this throw true try typeof ";
+ var CPP_KEYWORDS = COMMON_KEYWORDS + "alignof align_union asm axiom bool " +
+ "concept concept_map const_cast constexpr decltype " +
+ "dynamic_cast explicit export friend inline late_check " +
+ "mutable namespace nullptr reinterpret_cast static_assert static_cast " +
+ "template typeid typename using virtual wchar_t where ";
+ var JAVA_KEYWORDS = COMMON_KEYWORDS +
+ "abstract boolean byte extends final finally implements import " +
+ "instanceof null native package strictfp super synchronized throws " +
+ "transient ";
+ var CSHARP_KEYWORDS = JAVA_KEYWORDS +
+ "as base by checked decimal delegate descending event " +
+ "fixed foreach from group implicit in interface internal into is lock " +
+ "object out override orderby params partial readonly ref sbyte sealed " +
+ "stackalloc string select uint ulong unchecked unsafe ushort var ";
+ var JSCRIPT_KEYWORDS = COMMON_KEYWORDS +
+ "debugger eval export function get null set undefined var with " +
+ "Infinity NaN ";
+ var PERL_KEYWORDS = "caller delete die do dump elsif eval exit foreach for " +
+ "goto if import last local my next no our print package redo require " +
+ "sub undef unless until use wantarray while BEGIN END ";
+ var PYTHON_KEYWORDS = FLOW_CONTROL_KEYWORDS + "and as assert class def del " +
+ "elif except exec finally from global import in is lambda " +
+ "nonlocal not or pass print raise try with yield " +
+ "False True None ";
+ var RUBY_KEYWORDS = FLOW_CONTROL_KEYWORDS + "alias and begin case class def" +
+ " defined elsif end ensure false in module next nil not or redo rescue " +
+ "retry self super then true undef unless until when yield BEGIN END ";
+ var SH_KEYWORDS = FLOW_CONTROL_KEYWORDS + "case done elif esac eval fi " +
+ "function in local set then until ";
+ var ALL_KEYWORDS = (
+ CPP_KEYWORDS + CSHARP_KEYWORDS + JSCRIPT_KEYWORDS + PERL_KEYWORDS +
+ PYTHON_KEYWORDS + RUBY_KEYWORDS + SH_KEYWORDS);
+
+ // token style names. correspond to css classes
+ /** token style for a string literal */
+ var PR_STRING = 'str';
+ /** token style for a keyword */
+ var PR_KEYWORD = 'kwd';
+ /** token style for a comment */
+ var PR_COMMENT = 'com';
+ /** token style for a type */
+ var PR_TYPE = 'typ';
+ /** token style for a literal value. e.g. 1, null, true. */
+ var PR_LITERAL = 'lit';
+ /** token style for a punctuation string. */
+ var PR_PUNCTUATION = 'pun';
+ /** token style for a punctuation string. */
+ var PR_PLAIN = 'pln';
+
+ /** token style for an sgml tag. */
+ var PR_TAG = 'tag';
+ /** token style for a markup declaration such as a DOCTYPE. */
+ var PR_DECLARATION = 'dec';
+ /** token style for embedded source. */
+ var PR_SOURCE = 'src';
+ /** token style for an sgml attribute name. */
+ var PR_ATTRIB_NAME = 'atn';
+ /** token style for an sgml attribute value. */
+ var PR_ATTRIB_VALUE = 'atv';
+
+ /**
+ * A class that indicates a section of markup that is not code, e.g. to allow
+ * embedding of line numbers within code listings.
+ */
+ var PR_NOCODE = 'nocode';
+
+ /** A set of tokens that can precede a regular expression literal in
+ * javascript.
+ * http://www.mozilla.org/js/language/js20/rationale/syntax.html has the full
+ * list, but I've removed ones that might be problematic when seen in
+ * languages that don't support regular expression literals.
+ *
+ *
Specifically, I've removed any keywords that can't precede a regexp
+ * literal in a syntactically legal javascript program, and I've removed the
+ * "in" keyword since it's not a keyword in many languages, and might be used
+ * as a count of inches.
+ *
+ *
The link a above does not accurately describe EcmaScript rules since
+ * it fails to distinguish between (a=++/b/i) and (a++/b/i) but it works
+ * very well in practice.
+ *
+ * @private
+ */
+ var REGEXP_PRECEDER_PATTERN = function () {
+ var preceders = [
+ "!", "!=", "!==", "#", "%", "%=", "&", "&&", "&&=",
+ "&=", "(", "*", "*=", /* "+", */ "+=", ",", /* "-", */ "-=",
+ "->", /*".", "..", "...", handled below */ "/", "/=", ":", "::", ";",
+ "<", "<<", "<<=", "<=", "=", "==", "===", ">",
+ ">=", ">>", ">>=", ">>>", ">>>=", "?", "@", "[",
+ "^", "^=", "^^", "^^=", "{", "|", "|=", "||",
+ "||=", "~" /* handles =~ and !~ */,
+ "break", "case", "continue", "delete",
+ "do", "else", "finally", "instanceof",
+ "return", "throw", "try", "typeof"
+ ];
+ var pattern = '(?:^^|[+-]';
+ for (var i = 0; i < preceders.length; ++i) {
+ pattern += '|' + preceders[i].replace(/([^=<>:&a-z])/g, '\\$1');
+ }
+ pattern += ')\\s*'; // matches at end, and matches empty string
+ return pattern;
+ // CAVEAT: this does not properly handle the case where a regular
+ // expression immediately follows another since a regular expression may
+ // have flags for case-sensitivity and the like. Having regexp tokens
+ // adjacent is not valid in any language I'm aware of, so I'm punting.
+ // TODO: maybe style special characters inside a regexp as punctuation.
+ }();
+
+ // Define regexps here so that the interpreter doesn't have to create an
+ // object each time the function containing them is called.
+ // The language spec requires a new object created even if you don't access
+ // the $1 members.
+ var pr_amp = /&/g;
+ var pr_lt = //g;
+ var pr_quot = /\"/g;
+ /** like textToHtml but escapes double quotes to be attribute safe. */
+ function attribToHtml(str) {
+ return str.replace(pr_amp, '&')
+ .replace(pr_lt, '<')
+ .replace(pr_gt, '>')
+ .replace(pr_quot, '"');
+ }
+
+ /** escapest html special characters to html. */
+ function textToHtml(str) {
+ return str.replace(pr_amp, '&')
+ .replace(pr_lt, '<')
+ .replace(pr_gt, '>');
+ }
+
+
+ var pr_ltEnt = /</g;
+ var pr_gtEnt = />/g;
+ var pr_aposEnt = /'/g;
+ var pr_quotEnt = /"/g;
+ var pr_ampEnt = /&/g;
+ var pr_nbspEnt = / /g;
+ /** unescapes html to plain text. */
+ function htmlToText(html) {
+ var pos = html.indexOf('&');
+ if (pos < 0) { return html; }
+ // Handle numeric entities specially. We can't use functional substitution
+ // since that doesn't work in older versions of Safari.
+ // These should be rare since most browsers convert them to normal chars.
+ for (--pos; (pos = html.indexOf('', pos + 1)) >= 0;) {
+ var end = html.indexOf(';', pos);
+ if (end >= 0) {
+ var num = html.substring(pos + 3, end);
+ var radix = 10;
+ if (num && num.charAt(0) === 'x') {
+ num = num.substring(1);
+ radix = 16;
+ }
+ var codePoint = parseInt(num, radix);
+ if (!isNaN(codePoint)) {
+ html = (html.substring(0, pos) + String.fromCharCode(codePoint) +
+ html.substring(end + 1));
+ }
+ }
+ }
+
+ return html.replace(pr_ltEnt, '<')
+ .replace(pr_gtEnt, '>')
+ .replace(pr_aposEnt, "'")
+ .replace(pr_quotEnt, '"')
+ .replace(pr_nbspEnt, ' ')
+ .replace(pr_ampEnt, '&');
+ }
+
+ /** is the given node's innerHTML normally unescaped? */
+ function isRawContent(node) {
+ return 'XMP' === node.tagName;
+ }
+
+ var newlineRe = /[\r\n]/g;
+ /**
+ * Are newlines and adjacent spaces significant in the given node's innerHTML?
+ */
+ function isPreformatted(node, content) {
+ // PRE means preformatted, and is a very common case, so don't create
+ // unnecessary computed style objects.
+ if ('PRE' === node.tagName) { return true; }
+ if (!newlineRe.test(content)) { return true; } // Don't care
+ var whitespace = '';
+ // For disconnected nodes, IE has no currentStyle.
+ if (node.currentStyle) {
+ whitespace = node.currentStyle.whiteSpace;
+ } else if (window.getComputedStyle) {
+ // Firefox makes a best guess if node is disconnected whereas Safari
+ // returns the empty string.
+ whitespace = window.getComputedStyle(node, null).whiteSpace;
+ }
+ return !whitespace || whitespace === 'pre';
+ }
+
+ function normalizedHtml(node, out, opt_sortAttrs) {
+ switch (node.nodeType) {
+ case 1: // an element
+ var name = node.tagName.toLowerCase();
+
+ out.push('<', name);
+ var attrs = node.attributes;
+ var n = attrs.length;
+ if (n) {
+ if (opt_sortAttrs) {
+ var sortedAttrs = [];
+ for (var i = n; --i >= 0;) { sortedAttrs[i] = attrs[i]; }
+ sortedAttrs.sort(function (a, b) {
+ return (a.name < b.name) ? -1 : a.name === b.name ? 0 : 1;
+ });
+ attrs = sortedAttrs;
+ }
+ for (var i = 0; i < n; ++i) {
+ var attr = attrs[i];
+ if (!attr.specified) { continue; }
+ out.push(' ', attr.name.toLowerCase(),
+ '="', attribToHtml(attr.value), '"');
+ }
+ }
+ out.push('>');
+ for (var child = node.firstChild; child; child = child.nextSibling) {
+ normalizedHtml(child, out, opt_sortAttrs);
+ }
+ if (node.firstChild || !/^(?:br|link|img)$/.test(name)) {
+ out.push('<\/', name, '>');
+ }
+ break;
+ case 3: case 4: // text
+ out.push(textToHtml(node.nodeValue));
+ break;
+ }
+ }
+
+ /**
+ * Given a group of {@link RegExp}s, returns a {@code RegExp} that globally
+ * matches the union o the sets o strings matched d by the input RegExp.
+ * Since it matches globally, if the input strings have a start-of-input
+ * anchor (/^.../), it is ignored for the purposes of unioning.
+ * @param {Array.} regexs non multiline, non-global regexs.
+ * @return {RegExp} a global regex.
+ */
+ function combinePrefixPatterns(regexs) {
+ var capturedGroupIndex = 0;
+
+ var needToFoldCase = false;
+ var ignoreCase = false;
+ for (var i = 0, n = regexs.length; i < n; ++i) {
+ var regex = regexs[i];
+ if (regex.ignoreCase) {
+ ignoreCase = true;
+ } else if (/[a-z]/i.test(regex.source.replace(
+ /\\u[0-9a-f]{4}|\\x[0-9a-f]{2}|\\[^ux]/gi, ''))) {
+ needToFoldCase = true;
+ ignoreCase = false;
+ break;
+ }
+ }
+
+ function decodeEscape(charsetPart) {
+ if (charsetPart.charAt(0) !== '\\') { return charsetPart.charCodeAt(0); }
+ switch (charsetPart.charAt(1)) {
+ case 'b': return 8;
+ case 't': return 9;
+ case 'n': return 0xa;
+ case 'v': return 0xb;
+ case 'f': return 0xc;
+ case 'r': return 0xd;
+ case 'u': case 'x':
+ return parseInt(charsetPart.substring(2), 16)
+ || charsetPart.charCodeAt(1);
+ case '0': case '1': case '2': case '3': case '4':
+ case '5': case '6': case '7':
+ return parseInt(charsetPart.substring(1), 8);
+ default: return charsetPart.charCodeAt(1);
+ }
+ }
+
+ function encodeEscape(charCode) {
+ if (charCode < 0x20) {
+ return (charCode < 0x10 ? '\\x0' : '\\x') + charCode.toString(16);
+ }
+ var ch = String.fromCharCode(charCode);
+ if (ch === '\\' || ch === '-' || ch === '[' || ch === ']') {
+ ch = '\\' + ch;
+ }
+ return ch;
+ }
+
+ function caseFoldCharset(charSet) {
+ var charsetParts = charSet.substring(1, charSet.length - 1).match(
+ new RegExp(
+ '\\\\u[0-9A-Fa-f]{4}'
+ + '|\\\\x[0-9A-Fa-f]{2}'
+ + '|\\\\[0-3][0-7]{0,2}'
+ + '|\\\\[0-7]{1,2}'
+ + '|\\\\[\\s\\S]'
+ + '|-'
+ + '|[^-\\\\]',
+ 'g'));
+ var groups = [];
+ var ranges = [];
+ var inverse = charsetParts[0] === '^';
+ for (var i = inverse ? 1 : 0, n = charsetParts.length; i < n; ++i) {
+ var p = charsetParts[i];
+ switch (p) {
+ case '\\B': case '\\b':
+ case '\\D': case '\\d':
+ case '\\S': case '\\s':
+ case '\\W': case '\\w':
+ groups.push(p);
+ continue;
+ }
+ var start = decodeEscape(p);
+ var end;
+ if (i + 2 < n && '-' === charsetParts[i + 1]) {
+ end = decodeEscape(charsetParts[i + 2]);
+ i += 2;
+ } else {
+ end = start;
+ }
+ ranges.push([start, end]);
+ // If the range might intersect letters, then expand it.
+ if (!(end < 65 || start > 122)) {
+ if (!(end < 65 || start > 90)) {
+ ranges.push([Math.max(65, start) | 32, Math.min(end, 90) | 32]);
+ }
+ if (!(end < 97 || start > 122)) {
+ ranges.push([Math.max(97, start) & ~32, Math.min(end, 122) & ~32]);
+ }
+ }
+ }
+
+ // [[1, 10], [3, 4], [8, 12], [14, 14], [16, 16], [17, 17]]
+ // -> [[1, 12], [14, 14], [16, 17]]
+ ranges.sort(function (a, b) { return (a[0] - b[0]) || (b[1] - a[1]); });
+ var consolidatedRanges = [];
+ var lastRange = [NaN, NaN];
+ for (var i = 0; i < ranges.length; ++i) {
+ var range = ranges[i];
+ if (range[0] <= lastRange[1] + 1) {
+ lastRange[1] = Math.max(lastRange[1], range[1]);
+ } else {
+ consolidatedRanges.push(lastRange = range);
+ }
+ }
+
+ var out = ['['];
+ if (inverse) { out.push('^'); }
+ out.push.apply(out, groups);
+ for (var i = 0; i < consolidatedRanges.length; ++i) {
+ var range = consolidatedRanges[i];
+ out.push(encodeEscape(range[0]));
+ if (range[1] > range[0]) {
+ if (range[1] + 1 > range[0]) { out.push('-'); }
+ out.push(encodeEscape(range[1]));
+ }
+ }
+ out.push(']');
+ return out.join('');
+ }
+
+ function allowAnywhereFoldCaseAndRenumberGroups(regex) {
+ // Split into character sets, escape sequences, punctuation strings
+ // like ('(', '(?:', ')', '^'), and runs of characters that do not
+ // include any of the above.
+ var parts = regex.source.match(
+ new RegExp(
+ '(?:'
+ + '\\[(?:[^\\x5C\\x5D]|\\\\[\\s\\S])*\\]' // a character set
+ + '|\\\\u[A-Fa-f0-9]{4}' // a unicode escape
+ + '|\\\\x[A-Fa-f0-9]{2}' // a hex escape
+ + '|\\\\[0-9]+' // a back-reference or octal escape
+ + '|\\\\[^ux0-9]' // other escape sequence
+ + '|\\(\\?[:!=]' // start of a non-capturing group
+ + '|[\\(\\)\\^]' // start/emd of a group, or line start
+ + '|[^\\x5B\\x5C\\(\\)\\^]+' // run of other characters
+ + ')',
+ 'g'));
+ var n = parts.length;
+
+ // Maps captured group numbers to the number they will occupy in
+ // the output or to -1 if that has not been determined, or to
+ // undefined if they need not be capturing in the output.
+ var capturedGroups = [];
+
+ // Walk over and identify back references to build the capturedGroups
+ // mapping.
+ for (var i = 0, groupIndex = 0; i < n; ++i) {
+ var p = parts[i];
+ if (p === '(') {
+ // groups are 1-indexed, so max group index is count of '('
+ ++groupIndex;
+ } else if ('\\' === p.charAt(0)) {
+ var decimalValue = +p.substring(1);
+ if (decimalValue && decimalValue <= groupIndex) {
+ capturedGroups[decimalValue] = -1;
+ }
+ }
+ }
+
+ // Renumber groups and reduce capturing groups to non-capturing groups
+ // where possible.
+ for (var i = 1; i < capturedGroups.length; ++i) {
+ if (-1 === capturedGroups[i]) {
+ capturedGroups[i] = ++capturedGroupIndex;
+ }
+ }
+ for (var i = 0, groupIndex = 0; i < n; ++i) {
+ var p = parts[i];
+ if (p === '(') {
+ ++groupIndex;
+ if (capturedGroups[groupIndex] === undefined) {
+ parts[i] = '(?:';
+ }
+ } else if ('\\' === p.charAt(0)) {
+ var decimalValue = +p.substring(1);
+ if (decimalValue && decimalValue <= groupIndex) {
+ parts[i] = '\\' + capturedGroups[groupIndex];
+ }
+ }
+ }
+
+ // Remove any prefix anchors so that the output will match anywhere.
+ // ^^ really does mean an anchored match though.
+ for (var i = 0, groupIndex = 0; i < n; ++i) {
+ if ('^' === parts[i] && '^' !== parts[i + 1]) { parts[i] = ''; }
+ }
+
+ // Expand letters to groupts to handle mixing of case-sensitive and
+ // case-insensitive patterns if necessary.
+ if (regex.ignoreCase && needToFoldCase) {
+ for (var i = 0; i < n; ++i) {
+ var p = parts[i];
+ var ch0 = p.charAt(0);
+ if (p.length >= 2 && ch0 === '[') {
+ parts[i] = caseFoldCharset(p);
+ } else if (ch0 !== '\\') {
+ // TODO: handle letters in numeric escapes.
+ parts[i] = p.replace(
+ /[a-zA-Z]/g,
+ function (ch) {
+ var cc = ch.charCodeAt(0);
+ return '[' + String.fromCharCode(cc & ~32, cc | 32) + ']';
+ });
+ }
+ }
+ }
+
+ return parts.join('');
+ }
+
+ var rewritten = [];
+ for (var i = 0, n = regexs.length; i < n; ++i) {
+ var regex = regexs[i];
+ if (regex.global || regex.multiline) { throw new Error('' + regex); }
+ rewritten.push(
+ '(?:' + allowAnywhereFoldCaseAndRenumberGroups(regex) + ')');
+ }
+
+ return new RegExp(rewritten.join('|'), ignoreCase ? 'gi' : 'g');
+ }
+
+ var PR_innerHtmlWorks = null;
+ function getInnerHtml(node) {
+ // inner html is hopelessly broken in Safari 2.0.4 when the content is
+ // an html description of well formed XML and the containing tag is a PRE
+ // tag, so we detect that case and emulate innerHTML.
+ if (null === PR_innerHtmlWorks) {
+ var testNode = document.createElement('PRE');
+ testNode.appendChild(
+ document.createTextNode('\n'));
+ PR_innerHtmlWorks = !/)[\r\n]+/g, '$1')
+ .replace(/(?:[\r\n]+[ \t]*)+/g, ' ');
+ }
+ return content;
+ }
+
+ var out = [];
+ for (var child = node.firstChild; child; child = child.nextSibling) {
+ normalizedHtml(child, out);
+ }
+ return out.join('');
+ }
+
+ /** returns a function that expand tabs to spaces. This function can be fed
+ * successive chunks of text, and will maintain its own internal state to
+ * keep track of how tabs are expanded.
+ * @return {function (string) : string} a function that takes
+ * plain text and return the text with tabs expanded.
+ * @private
+ */
+ function makeTabExpander(tabWidth) {
+ var SPACES = ' ';
+ var charInLine = 0;
+
+ return function (plainText) {
+ // walk over each character looking for tabs and newlines.
+ // On tabs, expand them. On newlines, reset charInLine.
+ // Otherwise increment charInLine
+ var out = null;
+ var pos = 0;
+ for (var i = 0, n = plainText.length; i < n; ++i) {
+ var ch = plainText.charAt(i);
+
+ switch (ch) {
+ case '\t':
+ if (!out) { out = []; }
+ out.push(plainText.substring(pos, i));
+ // calculate how much space we need in front of this part
+ // nSpaces is the amount of padding -- the number of spaces needed
+ // to move us to the next column, where columns occur at factors of
+ // tabWidth.
+ var nSpaces = tabWidth - (charInLine % tabWidth);
+ charInLine += nSpaces;
+ for (; nSpaces >= 0; nSpaces -= SPACES.length) {
+ out.push(SPACES.substring(0, nSpaces));
+ }
+ pos = i + 1;
+ break;
+ case '\n':
+ charInLine = 0;
+ break;
+ default:
+ ++charInLine;
+ }
+ }
+ if (!out) { return plainText; }
+ out.push(plainText.substring(pos));
+ return out.join('');
+ };
+ }
+
+ var pr_chunkPattern = new RegExp(
+ '[^<]+' // A run of characters other than '<'
+ + '|<\!--[\\s\\S]*?--\>' // an HTML comment
+ + '|' // a CDATA section
+ // a probable tag that should not be highlighted
+ + '|<\/?[a-zA-Z](?:[^>\"\']|\'[^\']*\'|\"[^\"]*\")*>'
+ + '|<', // A '<' that does not begin a larger chunk
+ 'g');
+ var pr_commentPrefix = /^<\!--/;
+ var pr_cdataPrefix = /^) into their textual equivalent.
+ *
+ * @param {string} s html where whitespace is considered significant.
+ * @return {Object} source code and extracted tags.
+ * @private
+ */
+ function extractTags(s) {
+ // since the pattern has the 'g' modifier and defines no capturing groups,
+ // this will return a list of all chunks which we then classify and wrap as
+ // PR_Tokens
+ var matches = s.match(pr_chunkPattern);
+ var sourceBuf = [];
+ var sourceBufLen = 0;
+ var extractedTags = [];
+ if (matches) {
+ for (var i = 0, n = matches.length; i < n; ++i) {
+ var match = matches[i];
+ if (match.length > 1 && match.charAt(0) === '<') {
+ if (pr_commentPrefix.test(match)) { continue; }
+ if (pr_cdataPrefix.test(match)) {
+ // strip CDATA prefix and suffix. Don't unescape since it's CDATA
+ sourceBuf.push(match.substring(9, match.length - 3));
+ sourceBufLen += match.length - 12;
+ } else if (pr_brPrefix.test(match)) {
+ // tags are lexically significant so convert them to text.
+ // This is undone later.
+ sourceBuf.push('\n');
+ ++sourceBufLen;
+ } else {
+ if (match.indexOf(PR_NOCODE) >= 0 && isNoCodeTag(match)) {
+ // A will start a section that should be
+ // ignored. Continue walking the list until we see a matching end
+ // tag.
+ var name = match.match(pr_tagNameRe)[2];
+ var depth = 1;
+ var j;
+ end_tag_loop:
+ for (j = i + 1; j < n; ++j) {
+ var name2 = matches[j].match(pr_tagNameRe);
+ if (name2 && name2[2] === name) {
+ if (name2[1] === '/') {
+ if (--depth === 0) { break end_tag_loop; }
+ } else {
+ ++depth;
+ }
+ }
+ }
+ if (j < n) {
+ extractedTags.push(
+ sourceBufLen, matches.slice(i, j + 1).join(''));
+ i = j;
+ } else { // Ignore unclosed sections.
+ extractedTags.push(sourceBufLen, match);
+ }
+ } else {
+ extractedTags.push(sourceBufLen, match);
+ }
+ }
+ } else {
+ var literalText = htmlToText(match);
+ sourceBuf.push(literalText);
+ sourceBufLen += literalText.length;
+ }
+ }
+ }
+ return { source: sourceBuf.join(''), tags: extractedTags };
+ }
+
+ /** True if the given tag contains a class attribute with the nocode class. */
+ function isNoCodeTag(tag) {
+ return !!tag
+ // First canonicalize the representation of attributes
+ .replace(/\s(\w+)\s*=\s*(?:\"([^\"]*)\"|'([^\']*)'|(\S+))/g,
+ ' $1="$2$3$4"')
+ // Then look for the attribute we want.
+ .match(/[cC][lL][aA][sS][sS]=\"[^\"]*\bnocode\b/);
+ }
+
+ /**
+ * Apply the given language handler to sourceCode and add the resulting
+ * decorations to out.
+ * @param {number} basePos the index of sourceCode within the chunk of source
+ * whose decorations are already present on out.
+ */
+ function appendDecorations(basePos, sourceCode, langHandler, out) {
+ if (!sourceCode) { return; }
+ var job = {
+ source: sourceCode,
+ basePos: basePos
+ };
+ langHandler(job);
+ out.push.apply(out, job.decorations);
+ }
+
+ /** Given triples of [style, pattern, context] returns a lexing function,
+ * The lexing function interprets the patterns to find token boundaries and
+ * returns a decoration list of the form
+ * [index_0, style_0, index_1, style_1, ..., index_n, style_n]
+ * where index_n is an index into the sourceCode, and style_n is a style
+ * constant like PR_PLAIN. index_n-1 <= index_n, and style_n-1 applies to
+ * all characters in sourceCode[index_n-1:index_n].
+ *
+ * The stylePatterns is a list whose elements have the form
+ * [style : string, pattern : RegExp, DEPRECATED, shortcut : string].
+ *
+ * Style is a style constant like PR_PLAIN, or can be a string of the
+ * form 'lang-FOO', where FOO is a language extension describing the
+ * language of the portion of the token in $1 after pattern executes.
+ * E.g., if style is 'lang-lisp', and group 1 contains the text
+ * '(hello (world))', then that portion of the token will be passed to the
+ * registered lisp handler for formatting.
+ * The text before and after group 1 will be restyled using this decorator
+ * so decorators should take care that this doesn't result in infinite
+ * recursion. For example, the HTML lexer rule for SCRIPT elements looks
+ * something like ['lang-js', /<[s]cript>(.+?)<\/script>/]. This may match
+ * '