Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions src/main/java/com/example/labweek5/LabWeek5Application.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package com.example.labweek5;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class LabWeek5Application {

public static void main(String[] args) {
SpringApplication.run(LabWeek5Application.class, args);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package com.example.labweek5.controller;


import com.example.labweek5.models.Customer;
import com.example.labweek5.service.CustomerService;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/customers")
public class CustomerController {
private final CustomerService customerService;

public CustomerController(CustomerService customerService) {
this.customerService = customerService;
}

@PostMapping
public Customer createNewCustomer(@Valid @RequestBody Customer customer){
return customerService.addNewCustomer(customer);
}

@GetMapping
public List<Customer> getAllCustomers(){
return customerService.getAllCustomers();
}

@GetMapping("/{email}")
public Customer getCustomerByEmail (@Valid @PathVariable String email){
return customerService.getCustomerByEmail(email);
}

@PutMapping("/{email}")
public Customer updateCustomer (@Valid @PathVariable String email, @Valid @RequestBody Customer updatedCustomer){
return customerService.updateCustomer(email, updatedCustomer);
}

@DeleteMapping("/{email}")
public void deleteCustomer (@Valid @PathVariable String email){
customerService.deleteCustomer(email);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
package com.example.labweek5.controller;

//import com.example.labweek5.exception.InvalidApiKeyEx;
import com.example.labweek5.models.Product;
import com.example.labweek5.service.ProductService;
import jakarta.validation.Valid;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import static org.apache.logging.log4j.util.StringBuilders.equalsIgnoreCase;

@RestController
@RequestMapping("/products")
public class ProductController {
private final ProductService productService;
private final String API_KEY = "123456";

public ProductController(ProductService productService) {
this.productService = productService;
}


private void apiKeyCheck(String apiKey) {
if (!apiKey.equals(API_KEY)) {
throw new RuntimeException("Invalid or missing API-Key!!");
}
}

@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public Product createNewProduct(@RequestHeader("API-KEY") String apiKey, @Valid @RequestBody Product product) {
apiKeyCheck(apiKey);
return productService.addNewProduct(product);
}

@GetMapping
public List<Product> getAllProducts(@RequestHeader("API-KEY") String apiKey) {
apiKeyCheck(apiKey);
return productService.getAllProducts();
}

@GetMapping("/{name}")
public Product getProductByName(@RequestHeader("API-KEY") String apiKey, @Valid @PathVariable String name) {
apiKeyCheck(apiKey);
return productService.getProductByName(name);
}

@PutMapping("/{name}")
public Product updateProduct(@RequestHeader("API-KEY") String apiKey, @Valid @PathVariable String name, @RequestBody Product updatedProduct) {
apiKeyCheck(apiKey);
return productService.updateProduct(name, updatedProduct);
}

@DeleteMapping("/{name}")
public ResponseEntity<Void> deleteProduct(@RequestHeader("API-KEY") String apiKey, @PathVariable String name) {
apiKeyCheck(apiKey);
productService.deleteProduct(name);
return ResponseEntity.noContent().build();
}

@GetMapping("/category/{category}")
public List<Product> getByCategory(@RequestHeader("API-KEY") String apiKey, @Valid @PathVariable String category) {
apiKeyCheck(apiKey);
return productService.getProductByCategory(category);
}

@GetMapping("/price")
public List<Product> getByPriceRange(@RequestHeader("API-KEY") String apiKey, @Valid @RequestParam long min, @Valid @RequestParam long max) {
apiKeyCheck(apiKey);
return productService.getProductsByPriceRange(min, max);
}

}

Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package com.example.labweek5.controller;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestControllerAdvice
public class ValidationExceptionHandler {

@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<Map<String, List<String>>> handleValidationErrors(
MethodArgumentNotValidException ex) {

Map<String, List<String>> errors = new HashMap<>();

ex.getBindingResult().getFieldErrors()
.forEach(error -> {
String field = error.getField();
String message = error.getDefaultMessage();
errors.computeIfAbsent(field, k -> new ArrayList<>())
.add(message);
});

return ResponseEntity
.badRequest()
.body(errors);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package com.ironhack.labrestapi.exception;


import com.example.labweek5.exception.InvalidApiKeyEx;
import com.example.labweek5.exception.InvalidPriceRangeEx;
import com.example.labweek5.exception.ProductNotFoundEx;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

@RestControllerAdvice
public class GlobalExceptionHandlerEx {

@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public Map<String, String> handleValidation(MethodArgumentNotValidException ex) {
Map<String, String> errors = new HashMap<>();
ex.getBindingResult().getFieldErrors().forEach(e -> errors.put(e.getField(), e.getDefaultMessage()));
return errors;
}

@ExceptionHandler(InvalidApiKeyEx.class)
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public Map<String, String> handleMissingApiKey(InvalidApiKeyEx ex) {
Map<String, String> error = new HashMap<>();
error.put("error", ex.getMessage());
return error;
}

@ExceptionHandler(ProductNotFoundEx.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public Map<String, String> handleProductNotFound(ProductNotFoundEx ex) {
Map<String, String> error = new HashMap<>();
error.put("error", ex.getMessage());
return error;
}

@ExceptionHandler(InvalidPriceRangeEx.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public Map<String, String> handleInvalidPriceRange(InvalidPriceRangeEx ex) {
Map<String, String> error = new HashMap<>();
error.put("error", ex.getMessage());
return error;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package com.example.labweek5.exception;

public class InvalidApiKeyEx extends RuntimeException{
public InvalidApiKeyEx(String message){
super(message);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package com.example.labweek5.exception;

public class InvalidPriceRangeEx extends RuntimeException {
public InvalidPriceRangeEx(String message) {
super(message);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package com.example.labweek5.exception;

public class ProductNotFoundEx extends RuntimeException {
public ProductNotFoundEx(String message) {
super(message);
}
}
47 changes: 47 additions & 0 deletions src/main/java/com/example/labweek5/models/Customer.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package com.example.labweek5.models;

import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;

public class Customer {

@Email
private String email;

@Min(18)
private int age;

@NotBlank
private String address;

public Customer(String email, int age, String address) {
this.email = email;
this.age = age;
this.address = address;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

public String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address;
}
}
61 changes: 61 additions & 0 deletions src/main/java/com/example/labweek5/models/Product.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package com.example.labweek5.models;

import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.Positive;
import org.hibernate.validator.constraints.Length;

public class Product {

@NotBlank (message = "Name cannot be blank" )
@Length(min = 3, message = "Min length 3")
private String name;

@Positive (message = "Price must be positive")
private double price;

@NotBlank (message = " Category cannot be blank")
private String category;

@Positive (message = "Quantity must be positive")
private int quantity;

public Product(String name, double price, String category, int quantity) {
this.name = name;
this.price = price;
this.category = category;
this.quantity = quantity;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public double getPrice() {
return price;
}

public void setPrice(double price) {
this.price = price;
}

public String getCategory() {
return category;
}

public void setCategory(String category) {
this.category = category;
}

public int getQuantity() {
return quantity;
}

public void setQuantity(int quantity) {
this.quantity = quantity;
}
}
Loading