This commit is contained in:
shadowik 2023-04-30 00:20:46 +04:00
parent 64360fee8c
commit 32895a211f
29 changed files with 829 additions and 1377 deletions

View File

@ -12,12 +12,22 @@ repositories {
mavenCentral()
}
jar {
enabled = false
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'com.h2database:h2:2.1.210'
implementation 'org.springframework.boot:spring-boot-starter-validation'
implementation group: 'org.springdoc', name: 'springdoc-openapi-ui', version: '1.6.5'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'com.h2database:h2:2.1.210'
implementation 'org.hibernate.validator:hibernate-validator'
implementation 'org.springdoc:springdoc-openapi-ui:1.6.5'
testImplementation 'org.springframework.boot:spring-boot-starter-test'

Binary file not shown.

File diff suppressed because it is too large Load Diff

View File

@ -1 +1,2 @@
rootProject.name = 'demo'
include 'front'

View File

@ -1,7 +1,14 @@
package com.example.demo;
import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfiguration implements WebMvcConfigurer {
@ -9,4 +16,21 @@ public class WebConfiguration implements WebMvcConfigurer {
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedMethods("*");
}
@Override
public void addViewControllers(ViewControllerRegistry registry) {
ViewControllerRegistration registration = registry.addViewController("/notFound");
registration.setViewName("forward:/index.html");
registration.setStatusCode(HttpStatus.OK);
// Alternative way (404 error hits the console):
// > registry.addViewController("/notFound").setViewName("forward:/index.html");
}
@Bean
public WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> containerCustomizer() {
return container -> {
container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/notFound"));
};
}
}

View File

@ -1,6 +1,6 @@
package com.example.demo.master;
import com.example.demo.order.MastersOrders;
import com.example.demo.order.Order;
import jakarta.persistence.*;
import java.util.List;
@ -11,71 +11,77 @@ import java.util.Objects;
public class Master {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long _id;
@Column(name="_id")
private Long id;
@Column()
private String firstName;
private String lastName;
@OneToMany(fetch = FetchType.EAGER, mappedBy = "master", cascade = CascadeType.REMOVE)
private List<MastersOrders> mastersOrders;
private String email;
private String password;
public Master() {
}
public Master(String firstName, String lastName) {
public Master(String firstName, String lastName, String email, String password) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.password = password;
}
public Long get_id() {
return _id;
public Long getId() {
return id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public String getEmail() {return email; }
public String getPassword() { return password; }
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public void setEmail(String email) {
this.email = email;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Master master = (Master) o;
return Objects.equals(_id, master._id);
return Objects.equals(id, master.id);
}
@Override
public int hashCode() {
return Objects.hash(_id);
return Objects.hash(id);
}
@Override
public String toString() {
return "Master{" +
"id=" + _id +
"id=" + id +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", email='" + email + '\'' +
", password='" + password + '\'' +
'}';
}
public List<MastersOrders> getOrders() {
return mastersOrders;
}
public void setOrder(MastersOrders mastersOrders) {
if (mastersOrders.getMaster().equals(this)) {
this.mastersOrders.add(mastersOrders);
}
}
}

View File

@ -1,6 +1,6 @@
package com.example.demo.master;
import org.springframework.beans.factory.annotation.Autowired;
import com.example.demo.order.OrderService;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
@ -16,37 +16,55 @@ import java.util.List;
@RequestMapping("/master")
public class MasterController {
private final MasterService masterService;
private final OrderService orderService;
private Long currentMasterId = 0L;
@Autowired
public MasterController(MasterService masterService) {
public MasterController(MasterService masterService, OrderService orderService) {
this.masterService = masterService;
}
@GetMapping("/{id}")
public Master getMaster(@PathVariable Long id) {
return masterService.findMaster(id);
this.orderService = orderService;
}
@GetMapping("/")
public List<Master> getMaster() {
return masterService.findAllMasters();
}
public MasterDto getCurrentMaster() {
return new MasterDto(masterService.findMaster(currentMasterId));
}
@GetMapping("/{email}/{password}")
public MasterDto getCurrentMaster(@PathVariable("email") String email,
@PathVariable("password") String password) {
var master = new MasterDto(masterService.findMaster(email, password));
currentMasterId = master.getId();
return master;
}
@PostMapping("/")
public Master createMaster(@RequestParam("firstName") String firstName,
@RequestParam("lastName") String lastName) {
return masterService.addMaster(firstName, lastName);
public MasterDto createMaster(@RequestParam("firstName") String firstName,
@RequestParam("lastName") String lastName,
@RequestParam("email") String email,
@RequestParam("password") String password) {
MasterDto master = new MasterDto(masterService.addMaster(firstName, lastName, email, password));
currentMasterId = master.getId();
orderService.addOrder(currentMasterId);
return master;
}
@PatchMapping("/{id}")
public Master updateMaster(@PathVariable Long id,
@RequestParam("firstName") String firstName,
@RequestParam("lastName") String lastName) {
return masterService.updateMaster(id, firstName, lastName);
public MasterDto updateMaster(@PathVariable Long id,
@RequestParam("firstName") String firstName,
@RequestParam("lastName") String lastName,
@RequestParam("email") String email,
@RequestParam("password") String password) {
return new MasterDto(masterService.updateMaster(id, firstName, lastName, email, password));
}
@DeleteMapping("/{id}")
public Master deleteMaster(@PathVariable Long id) {
return masterService.deleteMaster(id);
public MasterDto deleteMaster(@PathVariable Long id) {
return new MasterDto(masterService.deleteMaster(id));
}
@PostMapping("/log_out")
public void logOut() {
currentMasterId = 0L;
}
}

View File

@ -0,0 +1,44 @@
package com.example.demo.master;
import com.example.demo.order.Order;
import jakarta.validation.constraints.NotBlank;
import java.util.List;
public class MasterDto {
private final Long id;
@NotBlank
private final String firstName;
@NotBlank
private final String lastName;
@NotBlank
private final String email;
@NotBlank
private final String password;
public MasterDto(Master master) {
id = master.getId();
firstName = master.getFirstName();
lastName = master.getLastName();
email = master.getEmail();
password = master.getPassword();
}
public long getId() {
return id;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getEmail() {return email; }
public String getPassword() { return password; }
}

View File

@ -0,0 +1,10 @@
package com.example.demo.master;
public class MasterNotFoundException extends RuntimeException {
public MasterNotFoundException(Long id) {
super(String.format("Master with id [%s] is not found", id));
}
public MasterNotFoundException(String email) {
super(String.format("Master with email [%s] is not found", email));
}
}

View File

@ -0,0 +1,10 @@
package com.example.demo.master;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
import java.util.Optional;
public interface MasterRepository extends JpaRepository<Master, Long> {
Optional<Master> findByEmail(String email);
}

View File

@ -1,65 +1,75 @@
package com.example.demo.master;
import com.example.demo.order.MastersOrders;
import com.example.demo.product.Product;
import jakarta.persistence.*;
import com.example.demo.order.OrderController;
import com.example.demo.order.OrderService;
import com.example.demo.util.validation.ValidatorUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
@Service
public class MasterService {
@PersistenceContext
private EntityManager em;
private final MasterRepository masterRepository;
private final ValidatorUtil validatorUtil;
public MasterService(MasterRepository masterRepository, ValidatorUtil validatorUtil) {
this.masterRepository = masterRepository;
this.validatorUtil = validatorUtil;
}
@Transactional
public Master addMaster(String firstName, String lastName) {
if (!StringUtils.hasText(firstName) || !StringUtils.hasText(lastName)) {
throw new IllegalArgumentException("Master name is null or empty");
}
final Master master = new Master(firstName, lastName);
em.persist(master);
return master;
public Master addMaster(String firstName, String lastName, String email, String password) {
final Master master = new Master(firstName, lastName, email, password);
validatorUtil.validate(master);
return masterRepository.save(master);
}
@Transactional(readOnly = true)
public Master findMaster(Long id) {
final Master master = em.find(Master.class, id);
if (master == null) {
throw new EntityNotFoundException(String.format("Master with id [%s] is not found", id));
final Optional<Master> mater = masterRepository.findById(id);
return mater.orElseThrow(() -> new MasterNotFoundException(id));
}
@Transactional(readOnly = true)
public Master findMaster(String email, String password) {
final Optional<Master> master = masterRepository.findByEmail(email);
Master realMaster = master.orElseThrow(() -> new MasterNotFoundException(email));
if (!Objects.equals(realMaster.getPassword(), password)) {
throw new MasterNotFoundException(email);
}
return master;
return realMaster;
}
@Transactional(readOnly = true)
public List<Master> findAllMasters() {
return em.createQuery("select s from Master s", Master.class)
.getResultList();
return masterRepository.findAll();
}
@Transactional
public Master updateMaster(Long id, String firstName, String lastName) {
if (!StringUtils.hasText(firstName) || !StringUtils.hasText(lastName)) {
throw new IllegalArgumentException("Master name is null or empty");
}
final Master currentMaster = findMaster(id);
currentMaster.setFirstName(firstName);
currentMaster.setLastName(lastName);
return em.merge(currentMaster);
public Master updateMaster(Long id, String firstName, String lastName, String email, String password) {
final Master master = findMaster(id);
master.setFirstName(firstName);
master.setLastName(lastName);
master.setEmail(email);
master.setPassword(password);
validatorUtil.validate(master);
return masterRepository.save(master);
}
@Transactional
public Master deleteMaster(Long id) {
final Master currentMaster = findMaster(id);
em.remove(currentMaster);
return currentMaster;
final Master master = findMaster(id);
masterRepository.delete(master);
return master;
}
@Transactional
public void deleteAllMasters() {
em.createQuery("delete from Master").executeUpdate();
masterRepository.deleteAll();
}

View File

@ -4,49 +4,51 @@ import com.example.demo.master.Master;
import com.example.demo.product.Product;
import jakarta.persistence.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
@Entity
public class MastersOrders {
@Table(name = "Master_order")
public class Order {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long _id;
@Column
private Date dateOfPurchase;
@Column(name="_id")
private Long id;
@ManyToOne(fetch = FetchType.EAGER)
private Master master;
@ManyToMany(fetch = FetchType.EAGER)
@ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.PERSIST)
@JoinTable(name = "order_products", joinColumns = {@JoinColumn(name = "order_id")}, inverseJoinColumns = {@JoinColumn(name = "product_id")})
private List<Product> products;
public MastersOrders() {
public Order() {
}
public MastersOrders(Date dateOfPurchase) {
this.dateOfPurchase = dateOfPurchase;
public Long getId() {
return id;
}
public Long get_id() {
return _id;
}
public Date getDateOfPurchase() {
return dateOfPurchase;
}
public void setDateOfPurchase(Date dateOfPurchase) {
this.dateOfPurchase = dateOfPurchase;
public void buyProducts() {
for (var item: products) {
removeProduct(item);
}
}
public void addProduct(Product product) {
if (products == null)
products = new ArrayList<>();
products.add(product);
if (product.getOrders() == null) {
product.setOrder(this);
}
}
public void removeProduct(Product product) {
if (products == null)
products = new ArrayList<>();
products.remove(product);
}
public Master getMaster() {
@ -55,9 +57,6 @@ public class MastersOrders {
public void setMaster(Master master) {
this.master = master;
if (!master.getOrders().contains(this)) {
master.setOrder(this);
}
}
public List<Product> getProducts() {
@ -72,20 +71,20 @@ public class MastersOrders {
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MastersOrders mastersOrders = (MastersOrders) o;
return Objects.equals(_id, mastersOrders._id);
Order order = (Order) o;
return Objects.equals(id, order.id);
}
@Override
public int hashCode() {
return Objects.hash(_id);
return Objects.hash(id);
}
@Override
public String toString() {
return "Order {" +
"id=" + _id +
", date='" + dateOfPurchase.toString() + '\'' +
", customer='" + master.toString() + '\'';
"id=" + id +
", master='" + master.toString() + '\'' +
", products='" + products.toString() + '\'';
}
}

View File

@ -1,4 +1,56 @@
package com.example.demo.order;
import com.example.demo.product.Product;
import com.example.demo.product.ProductDto;
import com.example.demo.product.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
@RestController
@RequestMapping("/order")
public class OrderController {
private final OrderService orderService;
public OrderController(OrderService orderService) {
this.orderService = orderService;
}
@GetMapping("/{id}")
public OrderDto getOrder(@PathVariable Long id) {
return new OrderDto(orderService.findOrder(id));
}
@DeleteMapping("/{id}")
public void buyProducts(@PathVariable Long id) {
orderService.buyProducts(id);
}
@GetMapping("/")
public List<OrderDto> getOrder() {
return orderService.findAllOrders().stream().map(OrderDto::new).toList();
}
@PostMapping("/")
public OrderDto createOrder(@RequestParam("master") Long masterId) {
return new OrderDto(orderService.addOrder(masterId));
}
@PostMapping("{id}/{product}")
public void addProduct(@PathVariable("id") Long id,
@PathVariable("product") Long productId) {
orderService.addProduct(id, productId);
}
@DeleteMapping("{id}/{product}")
public void deleteProduct(@PathVariable("id") Long id,
@PathVariable("product") Long productId) {
orderService.deleteProduct(id, productId);
}
@DeleteMapping("/")
public void deleteOrders() {
orderService.deleteAllOrders();
}
}

View File

@ -0,0 +1,34 @@
package com.example.demo.order;
import com.example.demo.master.Master;
import com.example.demo.product.Product;
import jakarta.validation.constraints.NotBlank;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class OrderDto {
private final Long id;
@NotBlank
private final Master master;
private final List<Product> products;
public OrderDto(Order order) {
id = order.getId();
master = order.getMaster();
products = order.getProducts();
}
public long getId() {
return id;
}
public Master getMaster() {
return master;
}
public List<Product> getProducts() {
return products;
}
}

View File

@ -0,0 +1,7 @@
package com.example.demo.order;
public class OrderNotFoundException extends RuntimeException {
public OrderNotFoundException(Long id) {
super(String.format("Order with id [%s] is not found", id));
}
}

View File

@ -0,0 +1,10 @@
package com.example.demo.order;
import com.example.demo.master.Master;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;
public interface OrderRepository extends JpaRepository<Order, Long> {
Optional<Order> findByMaster(Master master);
}

View File

@ -1,86 +1,111 @@
package com.example.demo.order;
import com.example.demo.master.Master;
import com.example.demo.master.MasterNotFoundException;
import com.example.demo.master.MasterRepository;
import com.example.demo.product.Product;
import com.example.demo.product.ProductNotFoundException;
import com.example.demo.product.ProductRepository;
import com.example.demo.product.Status;
import com.example.demo.util.validation.ValidatorUtil;
import jakarta.persistence.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;
@Service
public class OrderService {
@PersistenceContext
private EntityManager em;
private final OrderRepository orderRepository;
private final ProductRepository productRepository;
private final MasterRepository masterRepository;
private final ValidatorUtil validatorUtil;
@Transactional
public MastersOrders addOrder(Master master) {
if (master == null || em.find(Master.class, master.get_id()) == null) {
throw new IllegalArgumentException("addOrder empty fields");
}
final MastersOrders order = new MastersOrders(new Date(System.currentTimeMillis()));
order.setMaster(master);
em.persist(order);
em.merge(master);
return order;
public OrderService(OrderRepository orderRepository, ProductRepository productRepository,
MasterRepository masterRepository, ValidatorUtil validatorUtil) {
this.orderRepository = orderRepository;
this.productRepository = productRepository;
this.masterRepository = masterRepository;
this.validatorUtil = validatorUtil;
}
@Transactional
public MastersOrders addProduct(Long id, Product product) {
if (product == null) {
throw new IllegalArgumentException("addOrder empty fields");
public Order addOrder(Long masterId) {
final Order order = new Order();
order.setMaster(masterRepository.findById(masterId).orElseThrow(() -> new MasterNotFoundException(masterId)));
validatorUtil.validate(order);
return orderRepository.save(order);
}
@Transactional
public void addProduct(Long masterId, Long productId) {
final Order order = orderRepository.findByMaster(masterRepository.findById(masterId).orElseThrow(() -> new MasterNotFoundException(masterId))).orElseThrow(() -> new OrderNotFoundException(masterId));
final Product product = productRepository.findById(productId).orElseThrow(() ->
new ProductNotFoundException(productId));
order.addProduct(product);
product.setOrder(order);
product.setAvailable(Status.Ordered);
orderRepository.save(order);
productRepository.save(product);
}
@Transactional
public void buyProducts(Long masterId) {
final Order order = orderRepository.findByMaster(masterRepository.findById(masterId).orElseThrow(() -> new MasterNotFoundException(masterId))).orElseThrow(() -> new OrderNotFoundException(masterId));
var products = new ArrayList<Product>(order.getProducts());
for (var item: products) {
item.setAvailable(Status.Bought);
productRepository.save(item);
order.removeProduct(item);
}
final MastersOrders currentOrder = findOrder(id);
currentOrder.addProduct(product);
product.setOrder(currentOrder);
em.merge(product);
return em.merge(currentOrder);
orderRepository.save(order);
}
@Transactional
public void deleteProduct(Long masterId, Long productId) {
final Order order = orderRepository.findByMaster(masterRepository.findById(masterId).orElseThrow(() -> new MasterNotFoundException(masterId))).orElseThrow(() -> new OrderNotFoundException(masterId));
final Product product = productRepository.findById(productId).orElseThrow(() ->
new ProductNotFoundException(productId));
order.removeProduct(product);
product.removeOrder(order);
product.setAvailable(Status.Availible);
orderRepository.save(order);
productRepository.save(product);
}
@Transactional()
public MastersOrders findOrder(Long id) {
final MastersOrders order = em.find(MastersOrders.class, id);
if (order == null) {
throw new EntityNotFoundException(String.format("Order with id [%s] is not found", id));
}
public Order findOrder(Long masterId) {
final Order order = orderRepository.findByMaster(masterRepository.findById(masterId).orElseThrow(() -> new MasterNotFoundException(masterId))).orElseThrow(() -> new OrderNotFoundException(masterId));
return order;
}
@Transactional(readOnly = true)
public List<MastersOrders> findAllOrders() {
return em.createQuery("select o from MastersOrders o", MastersOrders.class)
.getResultList();
public List<Order> findAllOrders() {
return orderRepository.findAll();
}
@Transactional
public MastersOrders deleteOrder(Long id) {
final MastersOrders currentOrder = findOrder(id);
em.remove(currentOrder);
return currentOrder;
}
@Transactional
public MastersOrders deleteProductsInOrder(Long id, Product product) {
final MastersOrders currentOrder = findOrder(id);
final Product currentProduct = em.find(Product.class, product.get_id());
currentOrder.getProducts().remove(currentProduct);
currentProduct.getOrders().remove(currentOrder);
em.merge(currentProduct);
return em.merge(currentOrder);
public Order deleteOrder(Long id) {
final Order order = findOrder(id);
orderRepository.delete(order);
return order;
}
@Transactional
public void deleteAllOrders() {
em.createQuery("delete from MastersOrders").executeUpdate();
orderRepository.deleteAll();
}
@Transactional
public List<MastersOrders> findOrdersWithProduct(Long masterId, Product product) {
return em.createQuery("SELECT o FROM MastersOrders o WHERE (o.master._id = :masterId) and (:product member OF o.products)",
MastersOrders.class)
.setParameter("product", product)
.setParameter("masterId", masterId)
.getResultList();
}
// EXTRA TASK FROM LAB 3
// @Transactional
// public List<Order> findOrdersWithProduct(Long masterId, Product product) {
// return em.createQuery("SELECT o FROM Order o WHERE (o.master._id = :masterId) and (:product member OF o.products)",
// Order.class)
// .setParameter("product", product)
// .setParameter("masterId", masterId)
// .getResultList();
// }
}

View File

@ -1,6 +1,8 @@
package com.example.demo.product;
import com.example.demo.order.MastersOrders;
import com.example.demo.master.Master;
import com.example.demo.order.Order;
import com.fasterxml.jackson.annotation.JsonIgnore;
import jakarta.persistence.*;
import java.util.List;
@ -10,32 +12,40 @@ import java.util.Objects;
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long _id;
@Column(name="_id")
private Long id;
@Column()
private String _name;
private String name;
private Integer cost;
@ManyToMany(fetch = FetchType.EAGER, mappedBy = "products")
private List<MastersOrders> mastersOrders;
@ManyToMany(fetch = FetchType.LAZY)
@JsonIgnore
private List<Order> mastersOrders;
@ManyToOne(fetch = FetchType.EAGER)
private Master master;
private Status status;
public Product() {
}
public Product(String _name, Integer cost) {
this._name = _name;
public Product(String name, Integer cost) {
this.name = name;
this.cost = cost;
this.status = Status.Availible;
}
public Long get_id() {
return _id;
public Long getId() {
return id;
}
public String getName() {
return _name;
return name;
}
public void setName(String _name) {
this._name = _name;
this.name = _name;
}
public Integer getCost() {
@ -51,31 +61,51 @@ public class Product {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Product product = (Product) o;
return Objects.equals(_id, product._id);
return Objects.equals(id, product.id);
}
@Override
public int hashCode() {
return Objects.hash(_id);
return Objects.hash(id);
}
@Override
public String toString() {
return "Product {" +
"id=" + _id +
", firstName='" + _name + '\'' +
"id=" + id +
", firstName='" + name + '\'' +
", cost='" + cost.toString() + '\'' +
", master='" + master.toString() + '\'' +
'}';
}
public List<MastersOrders> getOrders() {
return mastersOrders;
public Master getMaster() {
return master;
}
public void setOrder(MastersOrders mastersOrders) {
if (!mastersOrders.getProducts().contains(this)) {
mastersOrders.getProducts().add(this);
public void setMaster(Master master) {
this.master = master;
}
public List<Order> getOrders() {
return mastersOrders;
}
public void setOrder(Order order) {
if (!order.getProducts().contains(this)) {
order.getProducts().add(this);
}
}
public void removeOrder(Order order) {
order.getProducts().remove(this);
}
public Status getAvailable() {
return this.status;
}
public void setAvailable(Status status) {
this.status = status;
}
}

View File

@ -14,38 +14,44 @@ import java.util.List;
@RestController
@RequestMapping("/product")
public class ProductController {
private final ProductService masterService;
private final ProductService productService;
@Autowired
public ProductController(ProductService masterService) {
this.masterService = masterService;
public ProductController(ProductService productService) {
this.productService = productService;
}
@GetMapping("/{id}")
public Product getProduct(@PathVariable Long id) {
return masterService.findProduct(id);
public ProductDto getProduct(@PathVariable Long id) {
return new ProductDto(productService.findProduct(id));
}
@GetMapping("/")
public List<Product> getProduct() {
return masterService.findAllProducts();
public List<ProductDto> getProduct() {
return productService.findAllProducts().stream().map(ProductDto::new).toList();
}
@PostMapping("/")
public Product createProduct(@RequestParam("name") String name,
@RequestParam("cost") Integer cost) {
return masterService.addProduct(name, cost);
@GetMapping("/master/{id}")
public List<ProductDto> getMasterProduct(@PathVariable("id") Long id) {
return productService.findProducts(id).stream().map(ProductDto::new).toList();
}
@PostMapping("/{name}/{cost}/{masterId}")
public ProductDto createProduct(@PathVariable("name") String name,
@PathVariable("cost") Integer cost,
@PathVariable("masterId") Long masterId) {
return new ProductDto(productService.addProduct(name, cost, masterId));
}
@PatchMapping("/{id}")
public Product updateProduct(@PathVariable Long id,
public ProductDto updateProduct(@PathVariable Long id,
@RequestParam("name") String name,
@RequestParam("cost") Integer cost) {
return masterService.updateProduct(id, name, cost);
return new ProductDto(productService.updateProduct(id, name, cost));
}
@DeleteMapping("/{id}")
public Product deleteProduct(@PathVariable Long id) {
return masterService.deleteProduct(id);
public ProductDto deleteProduct(@PathVariable Long id) {
return new ProductDto(productService.deleteProduct(id));
}
}

View File

@ -0,0 +1,54 @@
package com.example.demo.product;
import com.example.demo.master.Master;
import com.example.demo.order.Order;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import java.util.List;
public class ProductDto {
private final long id;
@NotBlank
private final String name;
@Min(1)
private final int cost;
private final List<Order> orders;
@NotBlank
private final Master master;
@NotBlank
private final Status status;
public ProductDto(Product product) {
id = product.getId();
name = product.getName();
cost = product.getCost();
orders = product.getOrders();
master = product.getMaster();
status = product.getAvailable();
}
public long getId() {
return id;
}
public String getName() {
return name;
}
public Integer getCost() {
return cost;
}
public List<Order> getOrders() {
return orders;
}
public Master getMaster() {
return master;
}
public Status getStatus() {
return status;
}
}

View File

@ -0,0 +1,7 @@
package com.example.demo.product;
public class ProductNotFoundException extends RuntimeException {
public ProductNotFoundException(Long id) {
super(String.format("Product with id [%s] is not found", id));
}
}

View File

@ -0,0 +1,13 @@
package com.example.demo.product;
import com.example.demo.master.Master;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
import java.util.Optional;
public interface ProductRepository extends JpaRepository<Product, Long> {
List<Product> findByMaster(Master master);
List<Product> findByStatus(Status status);
}

View File

@ -1,68 +1,73 @@
package com.example.demo.product;
import com.example.demo.master.Master;
import com.example.demo.master.MasterRepository;
import com.example.demo.master.MasterDto;
import com.example.demo.master.MasterNotFoundException;
import com.example.demo.util.validation.ValidatorUtil;
import jakarta.persistence.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.util.List;
import java.util.Optional;
@Service
public class ProductService {
@PersistenceContext
private EntityManager em;
private final ProductRepository productRepository;
private final ValidatorUtil validatorUtil;
private final MasterRepository masterRepository;
public ProductService(ProductRepository productRepository, MasterRepository masterRepository, ValidatorUtil validatorUtil) {
this.productRepository = productRepository;
this.validatorUtil = validatorUtil;
this.masterRepository = masterRepository;
}
@Transactional
public Product addProduct(String name, Integer cost) {
if (!StringUtils.hasText(name)) {
throw new IllegalArgumentException("Product name is null or empty");
}
if (cost < 0) {
throw new IllegalArgumentException("Product cost is below 0");
}
public Product addProduct(String name, Integer cost, Long masterId) {
final Product product = new Product(name, cost);
em.persist(product);
return product;
validatorUtil.validate(product);
product.setMaster(masterRepository.findById(masterId).orElseThrow(() -> new MasterNotFoundException(masterId)));
return productRepository.save(product);
}
@Transactional(readOnly = true)
public Product findProduct(Long id) {
final Product product = em.find(Product.class, id);
if (product == null) {
throw new EntityNotFoundException(String.format("Product with id [%s] is not found", id));
}
return product;
final Optional<Product> product = productRepository.findById(id);
return product.orElseThrow(() -> new ProductNotFoundException(id));
}
@Transactional(readOnly = true)
public List<Product> findProducts(Long masterId) {
List<Product> products = productRepository.findByMaster(masterRepository.findById(masterId).orElseThrow(() -> new MasterNotFoundException(masterId)));
return products.stream().filter((item) -> item.getAvailable() != Status.Bought).toList();
}
@Transactional(readOnly = true)
public List<Product> findAllProducts() {
return em.createQuery("select s from Product s", Product.class)
.getResultList();
return productRepository.findByStatus(Status.Availible);
}
@Transactional
public Product updateProduct(Long id, String name, Integer cost) {
if (!StringUtils.hasText(name)) {
throw new IllegalArgumentException("Product name is null or empty");
}
if (cost < 0) {
throw new IllegalArgumentException("Product cost is below 0");
}
final Product currentProduct = findProduct(id);
currentProduct.setName(name);
currentProduct.setCost(cost);
return em.merge(currentProduct);
final Product product = findProduct(id);
product.setName(name);
product.setCost(cost);
validatorUtil.validate(product);
return productRepository.save(product);
}
@Transactional
public Product deleteProduct(Long id) {
final Product currentProduct = findProduct(id);
em.remove(currentProduct);
return currentProduct;
final Product product = findProduct(id);
productRepository.delete(product);
return product;
}
@Transactional
public void deleteAllProducts() {
em.createQuery("delete from Product ").executeUpdate();
productRepository.deleteAll();
}
}

View File

@ -0,0 +1,7 @@
package com.example.demo.product;
public enum Status {
Availible,
Ordered,
Bought
}

View File

@ -0,0 +1,44 @@
package com.example.demo.util.error;
import com.example.demo.master.MasterNotFoundException;
import com.example.demo.order.Order;
import com.example.demo.order.OrderNotFoundException;
import com.example.demo.product.ProductNotFoundException;
import com.example.demo.util.validation.ValidationException;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import java.util.stream.Collectors;
@ControllerAdvice
public class AdviceController {
@ExceptionHandler({
MasterNotFoundException.class,
ProductNotFoundException.class,
OrderNotFoundException.class,
ValidationException.class,
})
public ResponseEntity<Object> handleException(Throwable e) {
return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<Object> handleBindException(MethodArgumentNotValidException e) {
final ValidationException validationException = new ValidationException(
e.getBindingResult().getAllErrors().stream()
.map(DefaultMessageSourceResolvable::getDefaultMessage)
.collect(Collectors.toSet()));
return handleException(validationException);
}
@ExceptionHandler(Exception.class)
public ResponseEntity<Object> handleUnknownException(Throwable e) {
e.printStackTrace();
return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}

View File

@ -0,0 +1,9 @@
package com.example.demo.util.validation;
import java.util.Set;
public class ValidationException extends RuntimeException {
public ValidationException(Set<String> errors) {
super(String.join("\n", errors));
}
}

View File

@ -0,0 +1,32 @@
package com.example.demo.util.validation;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import jakarta.validation.ValidatorFactory;
import org.springframework.stereotype.Component;
import java.util.Set;
import java.util.stream.Collectors;
@Component
public class ValidatorUtil {
private final Validator validator;
public ValidatorUtil() {
try (ValidatorFactory factory = Validation.buildDefaultValidatorFactory()) {
this.validator = factory.getValidator();
}
}
public <T> void validate(T object) {
final Set<ConstraintViolation<T>> errors = validator.validate(object);
if (!errors.isEmpty()) {
throw new ValidationException(errors.stream()
.map(ConstraintViolation::getMessage)
.collect(Collectors.toSet()));
}
}
}

View File

@ -1,5 +1,5 @@
#server.port=8080
server.port=8080
spring.datasource.url=jdbc:h2:file:./data
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa

View File

@ -1,134 +1,133 @@
package com.example.demo;
import jakarta.persistence.EntityNotFoundException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import com.example.demo.order.*;
import com.example.demo.master.*;
import com.example.demo.product.*;
import java.util.List;
import java.util.logging.Logger;
@SpringBootTest
class DemoApplicationTests {
@Autowired
private MasterService masterService;
@Autowired
private ProductService productService;
@Autowired
private OrderService orderService;
@Test
void testOrder() {
productService.deleteAllProducts();
orderService.deleteAllOrders();
masterService.deleteAllMasters();
final Product product1 = productService.addProduct("Машинка", 300);
final Product product2 = productService.addProduct("Ключ", 200);
final Master master1 = masterService.addMaster("Кирилл", "Петрович");
final MastersOrders order0 = orderService.addOrder(masterService.findMaster(master1.get_id()));
final MastersOrders order1 = orderService.findOrder(order0.get_id());
Assertions.assertEquals(order0, order1);
Assertions.assertEquals(masterService
.findMaster(master1.get_id()).getOrders().size(), 1);
orderService.deleteAllOrders();
Assertions.assertThrows(EntityNotFoundException.class, () -> orderService.findOrder(-1L));
final Master customer2 = masterService.addMaster("Александр", "Игоревич");
final MastersOrders order2 = orderService
.addOrder(masterService.findMaster(customer2.get_id()));
orderService.addProduct(order2.get_id(), product1);
orderService.addProduct(order2.get_id(), product1);
orderService.deleteProductsInOrder(order2.get_id(), product1);
Assertions.assertEquals(orderService
.findOrder(order2.get_id()).getProducts().size(), 1);
masterService.deleteMaster(customer2.get_id());
Assertions.assertThrows(EntityNotFoundException.class, () -> masterService.findMaster(customer2.get_id()));
Assertions.assertThrows(EntityNotFoundException.class, () -> orderService.findOrder(order2.get_id()));
Assertions.assertEquals(orderService.findAllOrders().size(), 0);
}
@Test()
void testMaster() {
masterService.deleteAllMasters();
final Master customer = masterService.addMaster("Иван", "Иванов");
Assertions.assertNotNull(customer.get_id());
masterService.deleteAllMasters();
final Master customer1 = masterService.addMaster("Иван", "Иванов");
final Master findMaster = masterService.findMaster(customer1.get_id());
Assertions.assertEquals(customer1, findMaster);
masterService.deleteAllMasters();
Assertions.assertThrows(EntityNotFoundException.class, () -> masterService.findMaster(-1L));
masterService.deleteAllMasters();
masterService.addMaster("Иван", "Иванов");
masterService.addMaster("Петр", "Петров");
final List<Master> customers1 = masterService.findAllMasters();
Assertions.assertEquals(customers1.size(), 2);
masterService.deleteAllMasters();
final List<Master> customers2 = masterService.findAllMasters();
Assertions.assertEquals(customers2.size(), 0);
}
@Test
void testProduct() {
productService.deleteAllProducts();
final Product ticket1 = productService.addProduct("Руно", 100);
Assertions.assertNotNull(ticket1.get_id());
productService.deleteAllProducts();
final Product ticket2 = productService.addProduct("Шоколад", 100);
final Product findProduct = productService.findProduct(ticket2.get_id());
Assertions.assertEquals(ticket2, findProduct);
productService.deleteAllProducts();
Assertions.assertThrows(EntityNotFoundException.class, () -> productService.findProduct(-1L));
productService.deleteAllProducts();
productService.addProduct("Автомобиль", 100);
productService.addProduct("Мячик", 100);
final List<Product> tickets1 = productService.findAllProducts();
Assertions.assertEquals(tickets1.size(), 2);
productService.deleteAllProducts();
final List<Product> tickets2 = productService.findAllProducts();
Assertions.assertEquals(tickets2.size(), 0);
}
@Test
void testCommand() {
productService.deleteAllProducts();
orderService.deleteAllOrders();
masterService.deleteAllMasters();
final Product product1 = productService.addProduct("Машинка", 300);
final Product product2 = productService.addProduct("Ключ", 200);
final Master master1 = masterService.addMaster("Кирилл", "Петрович");
final Master master2 = masterService.addMaster("Александр", "Камугович");
final MastersOrders order0 = orderService.addOrder(masterService.findMaster(master1.get_id()));
final MastersOrders order1 = orderService.addOrder(masterService.findMaster(master2.get_id()));
final MastersOrders order2 = orderService.addOrder(masterService.findMaster(master2.get_id()));
orderService.addProduct(order0.get_id(), product1);
orderService.addProduct(order1.get_id(), product1);
orderService.addProduct(order2.get_id(), product1);
Assertions.assertTrue(orderService.findOrdersWithProduct(master1.get_id(), product1).contains(order0));
Assertions.assertTrue(orderService.findOrdersWithProduct(master1.get_id(), product2).isEmpty());
Assertions.assertTrue(orderService.findOrdersWithProduct(master2.get_id(), product1).contains(order1)
&& orderService.findOrdersWithProduct(master2.get_id(), product1).contains(order2));
}
}
//package com.example.demo;
//
//import jakarta.persistence.EntityNotFoundException;
//import org.junit.jupiter.api.Assertions;
//import org.junit.jupiter.api.Test;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.boot.test.context.SpringBootTest;
//import com.example.demo.order.*;
//import com.example.demo.master.*;
//import com.example.demo.product.*;
//
//import java.util.List;
//
//@SpringBootTest
//class DemoApplicationTests {
//
// @Autowired
// private MasterService masterService;
// @Autowired
// private ProductService productService;
// @Autowired
// private OrderService orderService;
//
// @Test
// void testOrder() {
// productService.deleteAllProducts();
// orderService.deleteAllOrders();
// masterService.deleteAllMasters();
//
// final Product product1 = productService.addProduct("Машинка", 300);
// final Product product2 = productService.addProduct("Ключ", 200);
//
// final Master master1 = masterService.addMaster("Кирилл", "Петрович");
//
// final Order order0 = orderService.addOrder(masterService.findMaster(master1.getId()));
// final Order order1 = orderService.findOrder(order0.getId());
// Assertions.assertEquals(order0, order1);
//
// Assertions.assertEquals(masterService
// .findMaster(master1.getId()).getOrders().size(), 1);
// orderService.deleteAllOrders();
// Assertions.assertThrows(EntityNotFoundException.class, () -> orderService.findOrder(-1L));
// final Master customer2 = masterService.addMaster("Александр", "Игоревич");
// final Order order2 = orderService
// .addOrder(masterService.findMaster(customer2.getId()));
// orderService.addProduct(order2.getId(), product1);
// orderService.addProduct(order2.getId(), product1);
// orderService.deleteProductsInOrder(order2.getId(), product1);
//
// Assertions.assertEquals(orderService
// .findOrder(order2.getId()).getProducts().size(), 1);
// masterService.deleteMaster(customer2.getId());
// Assertions.assertThrows(EntityNotFoundException.class, () -> masterService.findMaster(customer2.getId()));
// Assertions.assertThrows(EntityNotFoundException.class, () -> orderService.findOrder(order2.getId()));
// Assertions.assertEquals(orderService.findAllOrders().size(), 0);
// }
//
// @Test()
// void testMaster() {
// masterService.deleteAllMasters();
// final Master customer = masterService.addMaster("Иван", "Иванов");
// Assertions.assertNotNull(customer.getId());
//
// masterService.deleteAllMasters();
// final Master customer1 = masterService.addMaster("Иван", "Иванов");
// final Master findMaster = masterService.findMaster(customer1.getId());
// Assertions.assertEquals(customer1, findMaster);
//
// masterService.deleteAllMasters();
// Assertions.assertThrows(EntityNotFoundException.class, () -> masterService.findMaster(-1L));
//
// masterService.deleteAllMasters();
// masterService.addMaster("Иван", "Иванов");
// masterService.addMaster("Петр", "Петров");
// final List<Master> customers1 = masterService.findAllMasters();
// Assertions.assertEquals(customers1.size(), 2);
//
// masterService.deleteAllMasters();
// final List<Master> customers2 = masterService.findAllMasters();
//
// Assertions.assertEquals(customers2.size(), 0);
// }
//
// @Test
// void testProduct() {
// productService.deleteAllProducts();
// final Product ticket1 = productService.addProduct("Руно", 100);
// Assertions.assertNotNull(ticket1.getId());
//
// productService.deleteAllProducts();
// final Product ticket2 = productService.addProduct("Шоколад", 100);
// final Product findProduct = productService.findProduct(ticket2.getId());
// Assertions.assertEquals(ticket2, findProduct);
//
// productService.deleteAllProducts();
// Assertions.assertThrows(EntityNotFoundException.class, () -> productService.findProduct(-1L));
//
// productService.deleteAllProducts();
// productService.addProduct("Автомобиль", 100);
// productService.addProduct("Мячик", 100);
// final List<Product> tickets1 = productService.findAllProducts();
// Assertions.assertEquals(tickets1.size(), 2);
//
// productService.deleteAllProducts();
// final List<Product> tickets2 = productService.findAllProducts();
// Assertions.assertEquals(tickets2.size(), 0);
// }
//
// @Test
// void testCommand() {
// productService.deleteAllProducts();
// orderService.deleteAllOrders();
// masterService.deleteAllMasters();
//
// final Product product1 = productService.addProduct("Машинка", 300);
// final Product product2 = productService.addProduct("Ключ", 200);
//
// final Master master1 = masterService.addMaster("Кирилл", "Петрович");
// final Master master2 = masterService.addMaster("Александр", "Камугович");
//
// final Order order0 = orderService.addOrder(masterService.findMaster(master1.getId()));
// final Order order1 = orderService.addOrder(masterService.findMaster(master2.getId()));
// final Order order2 = orderService.addOrder(masterService.findMaster(master2.getId()));
// orderService.addProduct(order0.getId(), product1);
// orderService.addProduct(order1.getId(), product1);
// orderService.addProduct(order2.getId(), product1);
//
// Assertions.assertTrue(orderService.findOrdersWithProduct(master1.getId(), product1).contains(order0));
// Assertions.assertTrue(orderService.findOrdersWithProduct(master1.getId(), product2).isEmpty());
// Assertions.assertTrue(orderService.findOrdersWithProduct(master2.getId(), product1).contains(order1)
// && orderService.findOrdersWithProduct(master2.getId(), product1).contains(order2));
// }
//}