Skip to content
Open

lab5 #70

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
10 changes: 10 additions & 0 deletions .idea/.gitignore

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 9 additions & 0 deletions .idea/lab-java-springboot-rest-api.iml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions .idea/misc.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 8 additions & 0 deletions .idea/modules.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions .idea/vcs.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

41 changes: 41 additions & 0 deletions src/main/java/com/example/hellolab5/Customer.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package com.example.hellolab5;

import jakarta.validation.constraints.*;

public class Customer {
@NotBlank //not blank = non vuoto
private String name;

@Email @NotBlank
private String email;//(valid email format)

@Min(18)
private int age;

@NotBlank
private String address;

// Costruttore senza argomenti
public Customer() {}

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

// Getter e Setter
public String getName() { return name; }
public void setName(String name) { this.name = name; }

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; }
}
35 changes: 35 additions & 0 deletions src/main/java/com/example/hellolab5/GlobalExceptionHandler.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package com.example.hellolab5;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingRequestHeaderException;
import org.springframework.web.bind.annotation.*;
import java.util.*;

@RestControllerAdvice
public class GlobalExceptionHandler {

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

@ExceptionHandler(MissingRequestHeaderException.class)
public ResponseEntity<String> handleMissingHeader(MissingRequestHeaderException ex) {
return new ResponseEntity<>("Missing API-Key header", HttpStatus.UNAUTHORIZED);
}

@ExceptionHandler(IllegalArgumentException.class)
public ResponseEntity<String> handleInvalidPrice(IllegalArgumentException ex) {
return new ResponseEntity<>(ex.getMessage(), HttpStatus.BAD_REQUEST);
}

@ExceptionHandler(RuntimeException.class)
public ResponseEntity<String> handleRuntime(RuntimeException ex) {
HttpStatus status = ex.getMessage().contains("not found") ? HttpStatus.NOT_FOUND : HttpStatus.UNAUTHORIZED;
return new ResponseEntity<>(ex.getMessage(), status);
}
}
13 changes: 13 additions & 0 deletions src/main/java/com/example/hellolab5/HelloLab5Application.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package com.example.hellolab5;

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

@SpringBootApplication
public class HelloLab5Application {

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

}
41 changes: 41 additions & 0 deletions src/main/java/com/example/hellolab5/Product.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package com.example.hellolab5;

import jakarta.validation.constraints.*;

public class Product {
@NotBlank @Size(min = 3)
private String name;

@Positive
private double price;

@NotBlank
private String category;

@Positive
private int quantity;

// Costruttore senza argomenti
public Product() {}

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

// Getter e Setter
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; }
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package com.example.hellolab5.controller;

import com.example.hellolab5.Customer;
import jakarta.validation.Valid;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/customers")
public class CustomerController {
private final List<Customer> customers = new ArrayList<>();

@PostMapping
public ResponseEntity<String> create(@Valid @RequestBody Customer c) {
customers.add(c);
return ResponseEntity.ok("Customer created");
}

@GetMapping
public List<Customer> getAll() { return customers; }

@GetMapping("/{email}")
public Customer getByEmail(@PathVariable String email) {
return customers.stream().filter(c -> c.getEmail().equals(email)).findFirst()
.orElseThrow(() -> new RuntimeException("Customer not found"));
}

@PutMapping("/{email}")
public void update(@PathVariable String email, @Valid @RequestBody Customer updated) {
getByEmail(email).setAddress(updated.getAddress());
// Altri campi...
}

@DeleteMapping("/{email}")
public void delete(@PathVariable String email) {
customers.removeIf(c -> c.getEmail().equals(email));
}

@GetMapping("/")
public String welcome() {
return "API is running! Use /products or /customers endpoints.";
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
package com.example.hellolab5.controller;

import com.example.hellolab5.Product;
import com.example.hellolab5.service.ProductService;
import jakarta.validation.Valid;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;

@RestController
@RequestMapping("/products")
public class ProductController {
private final ProductService service;

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

@PostMapping
public ResponseEntity<String> create(@RequestHeader("API-Key") String key, @Valid @RequestBody Product p) {
validateKey(key);
service.add(p);
return ResponseEntity.ok("Product created");
}

@GetMapping
public List<Product> getAll(@RequestHeader("API-Key") String key) {
validateKey(key);
return service.getAll();
}

@GetMapping("/{name}")
public Product getByName(@RequestHeader("API-Key") String key, @PathVariable String name) {
validateKey(key);
return service.getByName(name).orElseThrow(() -> new RuntimeException("Product not found"));
}

@PutMapping("/{name}")
public ResponseEntity<String> update(@RequestHeader("API-Key") String key, @PathVariable String name, @Valid @RequestBody Product p) {
validateKey(key);
service.update(name, p);
return ResponseEntity.ok("Product updated");
}

@DeleteMapping("/{name}")
public ResponseEntity<String> delete(@RequestHeader("API-Key") String key, @PathVariable String name) {
validateKey(key);
service.delete(name);
return ResponseEntity.ok("Product deleted");
}

@GetMapping("/category/{category}")
public List<Product> getByCategory(@RequestHeader("API-Key") String key, @PathVariable String category) {
validateKey(key);
return service.getByCategory(category);
}

@GetMapping("/price")
public List<Product> getByPrice(@RequestHeader("API-Key") String key, @RequestParam double min, @RequestParam double max) {
validateKey(key);
return service.getByPriceRange(min, max);
}

private void validateKey(String key) {
if (!"123456".equals(key)) throw new RuntimeException("Invalid API-Key");
}
}
40 changes: 40 additions & 0 deletions src/main/java/com/example/hellolab5/service/ProductService.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package com.example.hellolab5.service;

import com.example.hellolab5.Product;
import org.springframework.stereotype.Service;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ProductService {
private final List<Product> products = new ArrayList<>();

public void add(Product p) { products.add(p); }

public List<Product> getAll() { return products; }

public Optional<Product> getByName(String name) {
return products.stream().filter(p -> p.getName().equalsIgnoreCase(name)).findFirst();
}

public void update(String name, Product updated) {
getByName(name).ifPresent(p -> {
p.setPrice(updated.getPrice());
p.setCategory(updated.getCategory());
p.setQuantity(updated.getQuantity());
});
}

public void delete(String name) {
products.removeIf(p -> p.getName().equalsIgnoreCase(name));
}

public List<Product> getByCategory(String category) {
return products.stream().filter(p -> p.getCategory().equalsIgnoreCase(category)).collect(Collectors.toList());
}

public List<Product> getByPriceRange(double min, double max) {
if (min > max) throw new IllegalArgumentException("Min range cannot be greater than max");
return products.stream().filter(p -> p.getPrice() >= min && p.getPrice() <= max).collect(Collectors.toList());
}
}
1 change: 1 addition & 0 deletions src/main/resources/application.properties
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
spring.application.name=HelloLab5
13 changes: 13 additions & 0 deletions src/test/java/com/example/hellolab5/HelloLab5ApplicationTests.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package com.example.hellolab5;

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class HelloLab5ApplicationTests {

@Test
void contextLoads() {
}

}