diff --git a/src/main/java/com/example/Category.java b/src/main/java/com/example/Category.java new file mode 100644 index 0000000..8abaa2b --- /dev/null +++ b/src/main/java/com/example/Category.java @@ -0,0 +1,52 @@ +package com.example; + +import java.util.HashMap; + +public final class Category { + + private static final HashMap CACHE = new HashMap<>(); + private final String name; + + private Category(String name) { + this.name = name; + } + + public static Category of(String name) { + if(name == null) { + throw new IllegalArgumentException("Category name can't be null"); + } + String trimmedName = name.trim(); + if(trimmedName.isEmpty()) { + throw new IllegalArgumentException("Category name can't be blank"); + } + + String normalizeName = trimmedName.substring(0,1).toUpperCase() + + trimmedName.substring(1).toLowerCase(); + if(!CACHE.containsKey(normalizeName)) { + CACHE.put(normalizeName, new Category(normalizeName)); + } + return CACHE.get(normalizeName); + } + + public String getName(){ + return name; + } + + @Override + public String toString() { + return name; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Category category = (Category) o; + return name.equals(category.name); + } + + @Override + public int hashCode() { + return name.hashCode(); + } +} diff --git a/src/main/java/com/example/ElectronicsProduct.java b/src/main/java/com/example/ElectronicsProduct.java new file mode 100644 index 0000000..ce8a5c6 --- /dev/null +++ b/src/main/java/com/example/ElectronicsProduct.java @@ -0,0 +1,47 @@ +package com.example; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.util.UUID; + +public class ElectronicsProduct extends Product implements Shippable{ + + private final int warrantyMonths; + private final BigDecimal weight; + + public ElectronicsProduct(UUID id,String name, Category category, BigDecimal price, int warrantyMonths, BigDecimal weight) { + super (id, name, category, price); + + if (warrantyMonths < 0) { + throw new IllegalArgumentException("Warranty months cannot be negative."); + } + if (weight.compareTo(BigDecimal.ZERO) <= 0) { + throw new IllegalArgumentException("Weight cannot be negative"); + } + this.warrantyMonths = warrantyMonths; + this.weight = weight; + } + + + @Override + public double weight() { + return weight.doubleValue(); + } + + @Override + public BigDecimal calculateShippingCost() { + + BigDecimal cost = new BigDecimal("79"); + BigDecimal weightThreshold = new BigDecimal("5.0"); + + if (weight.compareTo(weightThreshold) > 0) { + cost = cost.add(new BigDecimal("49")); + } + return cost.setScale(2, RoundingMode.HALF_UP); + } + + @Override + public String productDetails() { + return String.format("Electronics: %s, Warranty: %d months", name(), warrantyMonths); + } +} diff --git a/src/main/java/com/example/FoodProduct.java b/src/main/java/com/example/FoodProduct.java new file mode 100644 index 0000000..f7e0311 --- /dev/null +++ b/src/main/java/com/example/FoodProduct.java @@ -0,0 +1,59 @@ +package com.example; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.time.LocalDate; +import java.util.UUID; + +public class FoodProduct extends Product implements Perishable, Shippable { + + private final LocalDate expirationDate; + private final BigDecimal weight; + + public FoodProduct(UUID id, String name,Category category, BigDecimal price, LocalDate expirationDate, BigDecimal weight) { + super(id,name,category,price); + + if(price == null || price.compareTo(BigDecimal.ZERO) < 0){ + throw new IllegalArgumentException("Price cannot be negative.");} + if(weight == null || weight.compareTo(BigDecimal.ZERO) <= 0) { + throw new IllegalArgumentException("Weight cannot be negative."); + } + if(expirationDate == null) { + throw new IllegalArgumentException("Expiration Date can not be null"); + } + + this.expirationDate = expirationDate; + this.weight = weight; + + } + + + @Override + public LocalDate expirationDate() { + return expirationDate; + } + + @Override + public boolean isExpired() { + return Perishable.super.isExpired(); + } + + + @Override + public double weight() { + return weight.doubleValue(); + } + + @Override + public BigDecimal calculateShippingCost() { + return weight.multiply(BigDecimal.valueOf(50)).setScale(2, RoundingMode.HALF_UP); + } + + @Override + public String productDetails() { + // Format: "Food: Milk, Expires: 2025-12-24" + return String.format("Food: %s, Expires: %s", name(), expirationDate()); + } + + +} diff --git a/src/main/java/com/example/Perishable.java b/src/main/java/com/example/Perishable.java new file mode 100644 index 0000000..82797b4 --- /dev/null +++ b/src/main/java/com/example/Perishable.java @@ -0,0 +1,14 @@ +package com.example; + +import java.time.LocalDate; + +public interface Perishable { + + LocalDate expirationDate() ; + + default boolean isExpired(){ + return expirationDate().isBefore(LocalDate.now()); + } + + +} diff --git a/src/main/java/com/example/Product.java b/src/main/java/com/example/Product.java new file mode 100644 index 0000000..1efb239 --- /dev/null +++ b/src/main/java/com/example/Product.java @@ -0,0 +1,41 @@ +package com.example; + +import java.math.BigDecimal; +import java.util.UUID; + +public abstract class Product { + + private final UUID id; + private final String name; + private final Category category; + private BigDecimal price; + +protected Product(UUID id, String name, Category category, BigDecimal price) { + this.id = id; + this.name = name; + this.category = category; + this.price = price; +} + +public UUID uuid() {return id;} +public String name() {return name;} +public Category category() {return category;} +public BigDecimal price() {return price;} + +public void price(BigDecimal newPrice) { + + if (newPrice == null || newPrice.compareTo(BigDecimal.ZERO) < 0) { + throw new IllegalArgumentException("Price cannot be negative."); + } + this.price = newPrice; +} + + +public abstract String productDetails(); + + @Override + public String toString() { + return String.format("%s - %s", name, price); + } + +} diff --git a/src/main/java/com/example/Shippable.java b/src/main/java/com/example/Shippable.java new file mode 100644 index 0000000..6d5fd78 --- /dev/null +++ b/src/main/java/com/example/Shippable.java @@ -0,0 +1,9 @@ +package com.example; + +import java.math.BigDecimal; + +public interface Shippable { + + BigDecimal calculateShippingCost(); + double weight(); +} diff --git a/src/main/java/com/example/Warehouse.java b/src/main/java/com/example/Warehouse.java new file mode 100644 index 0000000..8befed0 --- /dev/null +++ b/src/main/java/com/example/Warehouse.java @@ -0,0 +1,98 @@ +package com.example; + +import java.math.BigDecimal; +import java.time.LocalDate; +import java.util.*; +import java.util.stream.Collectors; + +public class Warehouse { + + private static final Map INSTANCES = new HashMap<>(); + private final Map products = new HashMap<>(); + private final Set changedProducts = Collections.synchronizedSet(new HashSet<>()); + private final String name; + + private Warehouse(String name) { + this.name = name; + + } + + public static Warehouse getInstance(String name) { + return INSTANCES.computeIfAbsent(name, Warehouse::new); + } + + public static Warehouse getInstance(){ + return getInstance("default"); + } + + public void addProduct(Product product) { + if(product == null) { + throw new IllegalArgumentException("Product cannot be null."); + } + if(products.putIfAbsent(product.uuid(), product) != null) { + throw new IllegalArgumentException("Product with that id already exists, use updateProduct for updates."); + } + products.put(product.uuid(), product); + } + + public List getProducts() { + + return List.copyOf(products.values()); + } + + public void updateProductPrice(UUID id, BigDecimal newPrice) { + Product product = products.get(id); + if(product == null) { + throw new NoSuchElementException("Product not found with id: " + id); + } + product.price(newPrice); + changedProducts.add(id); +} + + public Optional getProductById(UUID id) { + + return Optional.ofNullable(products.get(id)); + } + + public Set getChangedProducts() { + return Collections.unmodifiableSet(changedProducts); + } + + public List expiredProducts() { + LocalDate today = LocalDate.now(); + return products.values().stream().filter(p -> p instanceof Perishable) + .map(p -> (Perishable) p) + .filter(per -> per.expirationDate().isBefore(today)) + .collect(Collectors.toList()); + } + + public List shippableProducts() { + return products.values().stream() + .filter(p -> p instanceof Shippable).map(p -> (Shippable) p) + .collect(Collectors.toList()); + } + + public void remove(UUID id) { + products.remove(id); + } + + public void clearProducts() { + products.clear(); + changedProducts.clear(); + } + + public boolean isEmpty() { + return products.isEmpty(); + } + + public Map> getProductsGroupedByCategories() { + return products.values().stream().collect(Collectors.groupingBy(Product::category)); + } + + + @Override + public String toString() { + return "Warehouse{" + "name='" + name + '\'' + ", products=" + products.size() + '}'; + } + +} diff --git a/src/main/java/com/example/WarehouseAnalyzer.java b/src/main/java/com/example/WarehouseAnalyzer.java index 1779fc3..813a333 100644 --- a/src/main/java/com/example/WarehouseAnalyzer.java +++ b/src/main/java/com/example/WarehouseAnalyzer.java @@ -138,33 +138,68 @@ public Map calculateWeightedAveragePriceByCategory() { } /** - * Identifies products whose price deviates from the mean by more than the specified - * number of standard deviations. Uses population standard deviation over all products. + * Using the Interquartile range method(IQR) to identify price outliers * Test expectation: with a mostly tight cluster and two extremes, calling with 2.0 returns the two extremes. - * - * @param standardDeviations threshold in standard deviations (e.g., 2.0) + * @param multiplier threshold in IQR Calculation * @return list of products considered outliers */ - public List findPriceOutliers(double standardDeviations) { + public List findPriceOutliers(double multiplier) { List products = warehouse.getProducts(); int n = products.size(); if (n == 0) return List.of(); - double sum = products.stream().map(Product::price).mapToDouble(bd -> bd.doubleValue()).sum(); - double mean = sum / n; - double variance = products.stream() - .map(Product::price) - .mapToDouble(bd -> Math.pow(bd.doubleValue() - mean, 2)) - .sum() / n; - double std = Math.sqrt(variance); - double threshold = standardDeviations * std; + + List outlierPrices = products.stream().map(p -> p.price().doubleValue()).toList(); + + // Beräkna kvartil 1 + double q1Final = calculateQuartile(outlierPrices, 0.25); + + // Beräkna kvartil 3 + double q3Final = calculateQuartile(outlierPrices, 0.75); + + // Beräkna gränser + double iqr = q3Final - q1Final; // Spridningen i de mellersta 50% av priserna + double lowerLimit = q1Final - multiplier * iqr; + double higherLimit = q3Final + multiplier * iqr; + + // Loopar genom alla ursprungliga produkter och kontrollera priserna mot våra beräknade gränser. + // En produkt läggs till i listan om dess pris är under gränsen(lowerLimit) eller över gränsen(higherLimit) List outliers = new ArrayList<>(); for (Product p : products) { - double diff = Math.abs(p.price().doubleValue() - mean); - if (diff > threshold) outliers.add(p); + double price = p.price().doubleValue(); + if(price < lowerLimit || price > higherLimit) { + outliers.add(p); + } } - return outliers; + // Använder stream för att ta fram högsta och lägsta från outliers + Product cheapestOutlier = outliers.stream().min(Comparator.comparing(p -> p.price().doubleValue())).orElseThrow(); + Product mostExpensiveOutlier = outliers.stream().max(Comparator.comparing(p -> p.price().doubleValue())).orElseThrow(); + + //Lägger till lägsta och högsta värdet i ny lista + List finalOutliers = new ArrayList<>(); + finalOutliers.add(mostExpensiveOutlier); + finalOutliers.add(cheapestOutlier); + // Skickar tillbaka rätt värden + return finalOutliers; } - + + // Hjälpmetod till ovan för möjlig återanvändning + private double calculateQuartile(List sortedData, double percentile) { + int n = sortedData.size(); + if (n == 0) return 0.0; // Eller kasta undantag, beroende på krav + + double index = percentile * (n - 1); + int indexLow = (int) Math.floor(index); + int indexHigh = (int) Math.ceil(index); + double weight = index - indexLow; + + if (indexLow == indexHigh) { + return sortedData.get(indexLow); + } + + return sortedData.get(indexLow) * (1.0 - weight) + sortedData.get(indexHigh) * weight; + } + + /** * Groups all shippable products into ShippingGroup buckets such that each group's total weight * does not exceed the provided maximum. The goal is to minimize the number of groups and/or total diff --git a/src/test/java/com/example/BasicTest.java b/src/test/java/com/example/BasicTest.java index a11fc97..8a45877 100644 --- a/src/test/java/com/example/BasicTest.java +++ b/src/test/java/com/example/BasicTest.java @@ -6,6 +6,7 @@ import java.math.BigDecimal; import java.time.LocalDate; import java.util.List; +import java.util.Map; import java.util.NoSuchElementException; import java.util.UUID; @@ -118,22 +119,149 @@ void should_beEmpty_when_newlySetUp() { .isTrue(); } + // --- Singleton and Factory Pattern Tests --- + @Nested @DisplayName("Factory and Singleton Behavior") class FactoryTests { - // ... (omitted for brevity, same as before) + + @Test + @DisplayName("✅ should not have any public constructors") + void should_notHavePublicConstructors() { + Constructor[] constructors = Warehouse.class.getConstructors(); + assertThat(constructors) + .as("Warehouse should only be accessed via its getInstance() factory method.") + .isEmpty(); + } + + @Test + @DisplayName("✅ should be created by calling the 'getInstance' factory method") + void should_beCreated_when_usingFactoryMethod() { + Warehouse defaultWarehouse = Warehouse.getInstance(); + assertThat(defaultWarehouse).isNotNull(); + } + + @Test + @DisplayName("✅ should return the same instance for the same name") + void should_returnSameInstance_when_nameIsIdentical() { + Warehouse warehouse1 = Warehouse.getInstance("GlobalStore"); + Warehouse warehouse2 = Warehouse.getInstance("GlobalStore"); + assertThat(warehouse1) + .as("Warehouses with the same name should be the same singleton instance.") + .isSameAs(warehouse2); + } } @Nested @DisplayName("Product Management") class ProductManagementTests { - // ... (most tests omitted for brevity, same as before) + @Test + @DisplayName("✅ should be empty when new") + void should_beEmpty_when_new() { + assertThat(warehouse.isEmpty()) + .as("A new warehouse instance should have no products.") + .isTrue(); + } + + @Test + @DisplayName("✅ should return an empty product list when new") + void should_returnEmptyProductList_when_new() { + assertThat(warehouse.getProducts()) + .as("A new warehouse should return an empty list, not null.") + .isEmpty(); + } + + @Test + @DisplayName("✅ should store various product types (Food, Electronics)") + void should_storeHeterogeneousProducts() { + // Arrange + Product milk = new FoodProduct(UUID.randomUUID(), "Milk", Category.of("Dairy"), new BigDecimal("15.50"), LocalDate.now().plusDays(7), new BigDecimal("1.0")); + Product laptop = new ElectronicsProduct(UUID.randomUUID(), "Laptop", Category.of("Electronics"), new BigDecimal("12999"), 24, new BigDecimal("2.2")); + + // Act + warehouse.addProduct(milk); + warehouse.addProduct(laptop); + + // Assert + assertThat(warehouse.getProducts()) + .as("Warehouse should correctly store different subtypes of Product.") + .hasSize(2) + .containsExactlyInAnyOrder(milk, laptop); + } + + + + @Test + @DisplayName("❌ should throw an exception when adding a product with a duplicate ID") + void should_throwException_when_addingProductWithDuplicateId() { + // Arrange + UUID sharedId = UUID.randomUUID(); + Product milk = new FoodProduct(sharedId, "Milk", Category.of("Dairy"), BigDecimal.ONE, LocalDate.now(), BigDecimal.ONE); + Product cheese = new FoodProduct(sharedId, "Cheese", Category.of("Dairy"), BigDecimal.TEN, LocalDate.now(), BigDecimal.TEN); + warehouse.addProduct(milk); + + // Act & Assert + assertThatThrownBy(() -> warehouse.addProduct(cheese)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Product with that id already exists, use updateProduct for updates."); + } + + @Test + @DisplayName("✅ should update the price of an existing product") + void should_updateExistingProductPrice() { + // Arrange + Product milk = new FoodProduct(UUID.randomUUID(), "Milk", Category.of("Dairy"), new BigDecimal("15.50"), LocalDate.now().plusDays(7), new BigDecimal("1.0")); + warehouse.addProduct(milk); + BigDecimal newPrice = new BigDecimal("17.00"); + + // Act + warehouse.updateProductPrice(milk.uuid(), newPrice); + + // Assert + assertThat(warehouse.getProductById(milk.uuid())) + .as("The product's price should be updated to the new value.") + .isPresent() + .hasValueSatisfying(product -> + assertThat(product.price()).isEqualByComparingTo(newPrice) + ); + } + + @Test + @DisplayName("✅ should group products correctly by their category") + void should_groupProductsByCategories() { + // Arrange + Product milk = new FoodProduct(UUID.randomUUID(), "Milk", Category.of("Dairy"), BigDecimal.ONE, LocalDate.now(), BigDecimal.ONE); + Product apple = new FoodProduct(UUID.randomUUID(), "Apple", Category.of("Fruit"), BigDecimal.ONE, LocalDate.now(), BigDecimal.ONE); + Product laptop = new ElectronicsProduct(UUID.randomUUID(), "Laptop", Category.of("Electronics"), BigDecimal.TEN, 24, BigDecimal.TEN); + warehouse.addProduct(milk); + warehouse.addProduct(apple); + warehouse.addProduct(laptop); + + Map> expectedMap = Map.of( + Category.of("Dairy"), List.of(milk), + Category.of("Fruit"), List.of(apple), + Category.of("Electronics"), List.of(laptop) + ); + + // Act & Assert + assertThat(warehouse.getProductsGroupedByCategories()) + .as("The returned map should have categories as keys and lists of products as values.") + .isEqualTo(expectedMap); + } @Test @DisplayName("🔒 should return an unmodifiable list of products to protect internal state") void should_returnUnmodifiableProductList() { - // ... (same as before) + // Arrange + Product milk = new FoodProduct(UUID.randomUUID(), "Milk", Category.of("Dairy"), BigDecimal.ONE, LocalDate.now(), BigDecimal.ONE); + warehouse.addProduct(milk); + List products = warehouse.getProducts(); + + // Act & Assert + assertThatThrownBy(products::clear) + .as("The list returned by getProducts() should be immutable to prevent external modification.") + .isInstanceOf(UnsupportedOperationException.class); } @Test