Compare commits

...

6 Commits

28 changed files with 1449 additions and 81 deletions

View File

@ -14,6 +14,13 @@ repositories {
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
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.hibernate.validator:hibernate-validator'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

BIN
backend/lab/data.mv.db Normal file

Binary file not shown.

58
backend/lab/data.trace.db Normal file
View File

@ -0,0 +1,58 @@
2023-04-25 12:33:02 database: wrong user or password; user: "USER"
org.h2.message.DbException: Неверное имя пользователя или пароль
Wrong user name or password [28000-210]
at org.h2.message.DbException.get(DbException.java:227)
at org.h2.message.DbException.get(DbException.java:203)
at org.h2.message.DbException.get(DbException.java:192)
at org.h2.engine.Engine.openSession(Engine.java:154)
at org.h2.engine.Engine.openSession(Engine.java:222)
at org.h2.engine.Engine.createSession(Engine.java:201)
at org.h2.engine.SessionRemote.connectEmbeddedOrServer(SessionRemote.java:338)
at org.h2.jdbc.JdbcConnection.<init>(JdbcConnection.java:122)
at org.h2.util.JdbcUtils.getConnection(JdbcUtils.java:288)
at org.h2.server.web.WebServer.getConnection(WebServer.java:807)
at org.h2.server.web.WebApp.login(WebApp.java:1033)
at org.h2.server.web.WebApp.process(WebApp.java:226)
at org.h2.server.web.WebApp.processRequest(WebApp.java:176)
at org.h2.server.web.JakartaWebServlet.doGet(JakartaWebServlet.java:129)
at org.h2.server.web.JakartaWebServlet.doPost(JakartaWebServlet.java:166)
at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:731)
at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:814)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:223)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158)
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:177)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:119)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:400)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:859)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1734)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:52)
at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:833)
Caused by: org.h2.jdbc.JdbcSQLInvalidAuthorizationSpecException: Неверное имя пользователя или пароль
Wrong user name or password [28000-210]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:529)
at org.h2.message.DbException.getJdbcSQLException(DbException.java:496)
... 50 more

View File

@ -0,0 +1,30 @@
package com.example.lab.AllTypeCalc.configuration;
import com.example.lab.AllTypeCalc.domain.CalculationInt;
import com.example.lab.AllTypeCalc.domain.CalculationStr;
import com.example.lab.AllTypeCalc.domain.CalculationArr;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
public class CalcConfig {
private final Logger log = LoggerFactory.getLogger(com.example.lab.AllTypeCalc.configuration.CalcConfig.class);
@Bean(value = "int")
public CalculationInt createCalculationInt(){
log.info("Call createCalculationInt()");
return new CalculationInt();
}
@Bean(value = "str")
public CalculationStr createCalculationStr() {
log.info("Call createCalculationStr()");
return new CalculationStr();
}
@Bean (value = "arr")
public CalculationArr createCalculationArr() {
log.info("Call createCalculationArr()");
return new CalculationArr();
}
}

View File

@ -0,0 +1,43 @@
package com.example.lab.AllTypeCalc.controller;
import com.example.lab.AllTypeCalc.service.CalcService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class CalcController {
private final CalcService calcService;
public CalcController(CalcService calcService) {
this.calcService = calcService;
}
@GetMapping("/GetSum")
public Object getSum(@RequestParam(value = "obj1", defaultValue = "null") Object obj1,
@RequestParam(value = "obj2", defaultValue = "null") Object obj2,
@RequestParam(value = "typeInp", defaultValue = "str") String typeInp) {
return calcService.GetSum(obj1, obj2, typeInp);
}
@GetMapping("/GetMinus")
public Object getMinus(@RequestParam(value = "obj1", defaultValue = "null") Object obj1,
@RequestParam(value = "obj2", defaultValue = "null") Object obj2,
@RequestParam(value = "typeInp", defaultValue = "str") String typeInp) {
return calcService.GetMinus(obj1, obj2, typeInp);
}
@GetMapping("/GetMult")
public Object getMult(@RequestParam(value = "obj1", defaultValue = "null") Object obj1,
@RequestParam(value = "obj2", defaultValue = "null") Object obj2,
@RequestParam(value = "typeInp", defaultValue = "str") String typeInp) {
return calcService.GetMult(obj1, obj2, typeInp);
}
@GetMapping("/GetDiv")
public Object getDiv(@RequestParam(value = "obj1", defaultValue = "null") Object obj1,
@RequestParam(value = "obj2", defaultValue = "null") Object obj2,
@RequestParam(value = "typeInp", defaultValue = "str") String typeInp) {
return calcService.GetDiv(obj1, obj2, typeInp);
}
}

View File

@ -0,0 +1,97 @@
package com.example.lab.AllTypeCalc.domain;
import com.example.lab.AllTypeCalc.domain.ICalculation;
import org.springframework.stereotype.Component;
import java.util.Arrays;
@Component(value = "arr")
public class CalculationArr implements ICalculation<String[]> {
@Override
public String[] GetSum(String[] firstInp, String[] secondInp) {
String[] resArr;
String[] longArr;
String[] shortArr;
if (secondInp.length > firstInp.length) {
longArr = secondInp.clone();
shortArr = firstInp.clone();
} else {
longArr = firstInp.clone();
shortArr = secondInp.clone();
}
resArr = new String[longArr.length];
for (int i = 0; i < shortArr.length; i++) {
resArr[i] = Integer.toString(Integer.parseInt(longArr[i]) + Integer.parseInt(shortArr[i]));
}
for (int i = shortArr.length; i < longArr.length; i++) {
resArr[i] = longArr[i];
}
return resArr;
}
@Override
public String[] GetMinus(String[] firstInp, String[] secondInp) {
String[] resArr;
String[] longArr;
String[] shortArr;
if (secondInp.length > firstInp.length) {
longArr = secondInp.clone();
shortArr = firstInp.clone();
} else {
longArr = firstInp.clone();
shortArr = secondInp.clone();
}
resArr = new String[longArr.length];
for (int i = 0; i < shortArr.length; i++) {
resArr[i] = Integer.toString(Integer.parseInt(longArr[i]) - Integer.parseInt(shortArr[i]));
}
for (int i = shortArr.length; i < longArr.length; i++) {
resArr[i] = longArr[i];
}
return resArr;
}
@Override
public String[] GetMult(String firstInp[], String secondInp[]) {
String[] resArr;
String[] longArr;
String[] shortArr;
if (secondInp.length > firstInp.length) {
longArr = secondInp.clone();
shortArr = firstInp.clone();
} else {
longArr = firstInp.clone();
shortArr = secondInp.clone();
}
resArr = new String[longArr.length];
for (int i = 0; i < shortArr.length; i++) {
resArr[i] = Integer.toString(Integer.parseInt(longArr[i]) * Integer.parseInt(shortArr[i]));
}
for (int i = shortArr.length; i < longArr.length; i++) {
resArr[i] = longArr[i];
}
return resArr;
}
@Override
public String[] GetDiv(String[] firstInp, String[] secondInp) {
String[] resArr;
String[] longArr;
String[] shortArr;
if (secondInp.length > firstInp.length) {
longArr = secondInp.clone();
shortArr = firstInp.clone();
} else {
longArr = firstInp.clone();
shortArr = secondInp.clone();
}
resArr = new String[longArr.length];
for (int i = 0; i < shortArr.length; i++) {
resArr[i] =Integer.toString(Integer.parseInt(longArr[i]) / Integer.parseInt(shortArr[i]));
}
for (int i = shortArr.length; i < longArr.length; i++) {
resArr[i] = longArr[i];
}
return resArr;
}
}

View File

@ -0,0 +1,33 @@
package com.example.lab.AllTypeCalc.domain;
import com.example.lab.AllTypeCalc.domain.ICalculation;
import org.springframework.stereotype.Component;
@Component(value = "int")
public class CalculationInt implements ICalculation<Integer> {
@Override
public Integer GetSum(Integer firstInp, Integer secondInp) {
return firstInp+secondInp;
}
@Override
public Integer GetMinus(Integer firstInp, Integer secondInp) {
return firstInp - secondInp;
}
@Override
public Integer GetMult(Integer firstInp, Integer secondInp) {
return firstInp*secondInp;
}
@Override
public Integer GetDiv(Integer firstInp, Integer secondInp) {
if (secondInp == 0){
return 0;
}
else{
return (firstInp/secondInp);
}
}
}

View File

@ -0,0 +1,54 @@
package com.example.lab.AllTypeCalc.domain;
import com.example.lab.AllTypeCalc.domain.ICalculation;
import org.springframework.stereotype.Component;
@Component(value = "str")
public class CalculationStr implements ICalculation<String> {
@Override
public String GetSum(String firstInp, String secondInp) {
return (firstInp+secondInp);
}
@Override
public String GetMinus(String firstInp, String secondInp) {
StringBuilder bufStr = new StringBuilder();
if (firstInp.equals(secondInp)){
return "0";
}
else {
for (int i = 0; i < firstInp.length(); i++) {
boolean check = true;
for (int k = 0; k < secondInp.length(); k++) {
if (firstInp.charAt(i) == secondInp.charAt(k)) {
check = false;
break;
}
}
if (check){
bufStr.append(firstInp.charAt(i));}
}
}
return bufStr.toString();
}
@Override
public String GetMult(String firstInp, String secondInp) {
int multInt = secondInp.length();
StringBuilder multResult = new StringBuilder();
for (int i = 0; i < multInt; i++){
multResult.append(firstInp);
}
return multResult.toString();
}
@Override
public String GetDiv(String firstInp, String secondInp) {
if (secondInp.length() !=0) {
double divRes = 1.0 * firstInp.length() / secondInp.length();
return Double.toString(divRes);
}
else return "error";
}
}

View File

@ -0,0 +1,8 @@
package com.example.lab.AllTypeCalc.domain;
public interface ICalculation <V> {
V GetSum(V firstInp, V secondInp);
V GetMinus (V firstInp, V secondInp);
V GetMult (V firstInp, V secondInp);
V GetDiv(V firstInp, V secondInp);
}

View File

@ -0,0 +1,83 @@
package com.example.lab.AllTypeCalc.service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import com.example.lab.AllTypeCalc.domain.CalculationInt;
import com.example.lab.AllTypeCalc.domain.ICalculation;
import java.util.Arrays;
@Service
public class CalcService {
private final ApplicationContext applicationContext;
private final Logger log = LoggerFactory.getLogger(CalculationInt.class);
public CalcService(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
public Object GetSum(Object firstInp, Object secondInp, String type) {
final ICalculation calculator = (ICalculation) applicationContext.getBean(type);
if(type.equals("str")){
return calculator.GetSum(firstInp.toString(),secondInp.toString());
}
if(type.equals("int")) {
return calculator.GetSum(Integer.parseInt(firstInp.toString()), Integer.parseInt(secondInp.toString()) );
}
if(type.equals("arr")){
return calculator.GetSum(cleanToArr(firstInp) , cleanToArr(secondInp));
}
return "error";
}
public Object GetMinus(Object firstInp, Object secondInp, String type) {
final ICalculation calculator = (ICalculation) applicationContext.getBean(type);
if(type.equals("str")){
return calculator.GetMinus(firstInp.toString(),secondInp.toString());
}
if (type.equals("int")){
return calculator.GetMinus(Integer.parseInt(firstInp.toString()), Integer.parseInt(secondInp.toString()));
}
if(type.equals("arr")){
return calculator.GetMinus(cleanToArr(firstInp) , cleanToArr(secondInp));
}
return "error";
}
public Object GetMult(Object firstInp, Object secondInp, String type) {
final ICalculation calculator = (ICalculation) applicationContext.getBean(type);
if(type.equals("str")){
return calculator.GetMult(firstInp.toString(), secondInp.toString());
}
if (type.equals("int")){
return calculator.GetMult(Integer.parseInt(firstInp.toString()),
Integer.parseInt(secondInp.toString()));
}
if (type.equals("arr")){
return calculator.GetMult(cleanToArr(firstInp) , cleanToArr(secondInp));
}
return "error";
}
public Object GetDiv(Object firstInp, Object secondInp, String type) {
final ICalculation calculator = (ICalculation) applicationContext.getBean(type);
if (type.equals("str")){
return calculator.GetDiv(firstInp.toString(), secondInp.toString());
}
if (type.equals("int")){
return calculator.GetDiv(
Integer.parseInt(firstInp.toString()),
Integer.parseInt(secondInp.toString()));
}
if(type.equals("arr")){
return calculator.GetDiv(cleanToArr(firstInp) , cleanToArr(secondInp));
}
return "error";
}
public String[] cleanToArr(Object arr){
return Arrays.stream(arr.toString()
.split("[\\(\\)\\,\\.\\[\\] \\!\\?\\:\\;]"))
.filter(e -> e.trim().length()>0)
.toArray(String[]::new);
}
}

View File

@ -0,0 +1,75 @@
package com.example.lab.DataBase.Models;
import jakarta.persistence.*;
import java.util.*;
@Entity
public class Cart {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@OneToMany
private List<CountProduct> countProducts;
@OneToOne
private Customer customer;
public Cart(){}
public Cart(Customer customer) {
this.countProducts = new ArrayList<>();
this.customer = customer;
}
@PreRemove
public void deleteThis(){
//deleteAllProducts();
this.getCustomer().setCart(null);
}
public void addCountProduct(CountProduct countProduct){
countProducts.add(countProduct);
if (countProduct.getCart() != this) {
countProduct.setCart(this);
}
}
public void deleteCountProduct(CountProduct countProduct){
countProducts.remove(countProduct);
if (countProduct.getCart() == this) {
countProduct.setCart(null);
}
}
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
if(customer.getCart()!=this){
customer.setCart(this);
}
}
public Long getId() {
return id;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Cart cart = (Cart) obj;
return Objects.equals(id, cart.id);
}
@Override
public int hashCode(){
return Objects.hashCode(id);
}
}

View File

@ -0,0 +1,87 @@
package com.example.lab.DataBase.Models;
import jakarta.persistence.*;
import java.util.*;
@Entity
public class CountProduct {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column
private Integer amount;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name="cart_fk")
private Cart cart;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name="product_fk")
private Product product;
public CountProduct(){}
public CountProduct(Cart cart, Product product) {
this.cart = cart;
this.product = product;
this.amount = 0;
this.cart.addCountProduct(this);
this.product.addCountProduct(this);
}
public void setProduct(Product product) {
this.product = product;
if (product != null && !product.getCountProducts().contains(this)){
product.addCountProduct(this);
}
}
public Cart getCart() {
return cart;
}
public void setCart(Cart cart) {
this.cart = cart;
}
public Product getProduct() {
return product;
}
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
public void incrementAmount(){
this.amount++;
}
public void decrementAmount(){
this.amount--;
}
@PreRemove
public void deleteThis(){
if(this.product !=null) this.product.deleteCountProduct(this);
if(this.cart !=null) this.cart.deleteCountProduct(this);
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
CountProduct countProducts = (CountProduct) obj;
return Objects.equals(id, countProducts.id);
}
@Override
public int hashCode(){
return Objects.hashCode(id);
}
}

View File

@ -0,0 +1,75 @@
package com.example.lab.DataBase.Models;
import jakarta.persistence.*;
import java.util.Objects;
@Entity
public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column
private String firstName;
@Column
private String lastName;
@Column
private String customerAddress;
@OneToOne(fetch = FetchType.EAGER, mappedBy = "customer", cascade = CascadeType.ALL)
private Cart cart;
public Customer(){}
public Customer(String lastName, String firstName, String customerAddress) {
this.lastName = lastName;
this.firstName = firstName;
this.customerAddress = customerAddress;
}
public Cart getCart() {
return cart;
}
public void setCart(Cart cart) {
this.cart = cart;
if(cart != null && cart.getCustomer()!=this){
cart.setCustomer(this);
}
}
public Long getId() {
return id;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getCustomerAddress() {
return customerAddress;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public void setCustomerAddress(String customerAddress) {
this.customerAddress = customerAddress;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Customer customer = (Customer) obj;
return Objects.equals(id, customer.id);
}
@Override
public int hashCode(){
return Objects.hashCode(id);
}
}

View File

@ -0,0 +1,105 @@
package com.example.lab.DataBase.Models;
import jakarta.persistence.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
@Entity
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
private float price;
@OneToMany
private List<CountProduct> countProducts;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "productCategory_fk")
private ProductCategory productCategory;
public Product(){}
public Product(String name, float price, ProductCategory productCategory){
this.name = name;
this.price = price;
this.productCategory = productCategory;
this.countProducts = new ArrayList<>();
}
public ProductCategory getProductCategory() {
return productCategory;
}
public void setProductCategory(ProductCategory productCategory) {
this.productCategory = productCategory;
if(productCategory == null){
return;
}
if (!productCategory.getProducts().contains(this)){
productCategory.AddProduct(this);
}
}
public Long getId() {
return id;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setPrice(float price) {
this.price = price;
}
public float getPrice() {
return price;
}
@PreRemove
public void deleteThis(){
//deleteAllCarts();
this.productCategory.getProducts().remove(this);
}
public List<CountProduct> getCountProducts(){
return countProducts;
}
public void addCountProduct(CountProduct countProduct){
countProducts.add(countProduct);
if (countProduct.getProduct() != this) {
countProduct.setProduct(this);
}
}
public void deleteCountProduct(CountProduct countProduct){
countProducts.remove(countProduct);
if (countProduct.getProduct() == this) {
countProduct.setProduct(null);
}
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Product product = (Product) obj;
return Objects.equals(id, product.id);
}
@Override
public int hashCode(){
return Objects.hashCode(id);
}
}

View File

@ -0,0 +1,64 @@
package com.example.lab.DataBase.Models;
import jakarta.persistence.*;
import java.util.*;
@Entity
public class ProductCategory {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
@OneToMany(fetch = FetchType.EAGER, mappedBy = "productCategory", cascade = CascadeType.ALL)
private List<Product> products;
public void AddProduct(Product product){
this.products.add(product);
if (product.getProductCategory() != this){
product.setProductCategory(this);
}
}
public void deleteProduct(Product product) {
products.remove(product);
if (product.getProductCategory() == this) {
product.setProductCategory(null);
}
}
public ProductCategory(){}
public ProductCategory(String name){
this.name = name;
this.products = new ArrayList<Product>();
}
public Long getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Product> getProducts() {
return products;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
ProductCategory customer = (ProductCategory) obj;
return Objects.equals(id, customer.id);
}
@Override
public int hashCode(){
return Objects.hashCode(id);
}
}

View File

@ -0,0 +1,94 @@
package com.example.lab.DataBase.Services;
import com.example.lab.DataBase.Models.Customer;
import com.example.lab.DataBase.Models.Product;
import com.example.lab.DataBase.Models.CountProduct;
import jakarta.persistence.*;
import jakarta.transaction.Transactional;
import org.springframework.stereotype.Service;
import com.example.lab.DataBase.Models.Cart;
import java.util.List;
@Service
public class CartService {
@PersistenceContext
private EntityManager em;
private final ProductService productService;
private final CountProductService countProductService;
public CartService(ProductService productService, CountProductService countProductService){
this.productService = productService;
this.countProductService = countProductService;
}
@Transactional
public Cart addCart(Customer customer){
Cart cart = new Cart(customer);
cart.getCustomer().setCart(cart);
em.persist(cart);
return cart;
}
@Transactional()
public Cart getCart(Long id){
Cart cart = em.find(Cart.class, id);
if (cart == null){
throw new EntityNotFoundException(String.format("Error: Cart id %s not found", id));
}
return cart;
}
@Transactional
public List<Cart> getAllCarts(){
return em.createQuery("from Cart", Cart.class).getResultList();
}
@Transactional
public Cart deleteCart(Long id){
final Cart cart = getCart(id);
em.remove(cart);
return cart;
}
@Transactional
public void deleteAllCarts(){
for (var cart:
getAllCarts()) {
cart.deleteThis();
em.remove(cart);
}
}
@Transactional
public CountProduct addProduct(Long cartId, Long productId){
Product product = productService.getProduct(productId);
Cart cart = getCart(cartId);
var countProduct = countProductService.getCountProduct(productId, cartId);
if(countProduct == null) countProductService.addCountProduct(product, cart);
var resProd = countProductService.incrementProduct(productId, cartId);
em.persist(cart);
return resProd;
}
@Transactional
public Product deleteProduct(Long cartId, Long productId){
Product product = productService.getProduct(productId);
Cart cart = getCart(cartId);
var countProduct = countProductService.getCountProduct(productId, cartId);
if(countProduct == null) return null;
countProductService.deleteCountProduct(productId,cartId);
em.persist(cart);
return product;
}
@Transactional
public Product reduceProduct(Long cartId, Long productId){
Product product = productService.getProduct(productId);
Cart cart = getCart(cartId);
var countProduct = countProductService.getCountProduct(productId, cartId);
if(countProduct == null) return null;
countProduct.decrementAmount();
em.persist(countProduct);
return product;
}
}

View File

@ -0,0 +1,78 @@
package com.example.lab.DataBase.Services;
import com.example.lab.DataBase.Models.*;
import jakarta.persistence.*;
import jakarta.transaction.Transactional;
import org.springframework.stereotype.Service;
import com.example.lab.DataBase.Models.Product;
import java.util.List;
@Service
public class CountProductService {
@PersistenceContext
private EntityManager em;
@Transactional
public CountProduct addCountProduct(Product product,
Cart cart){
CountProduct countProduct = new CountProduct(cart, product);
em.persist(countProduct);
return countProduct;
}
@Transactional
public CountProduct getCountProduct(long productId, long cartId){
var count = getAllCountProducts();
var countProduct = count.stream().filter(x -> x.getProduct().getId() == productId
&& x.getCart().getId() == cartId ).findFirst();
if(countProduct.isEmpty()) return null;
else return countProduct.get();
}
@Transactional
public CountProduct incrementProduct (long productId, long cartId){
CountProduct countProduct = getCountProduct(productId, cartId);
countProduct.incrementAmount();
return em.merge(countProduct);
}
@Transactional
public CountProduct decrementProduct (long productId, long cartId){
CountProduct countProduct = getCountProduct(productId, cartId);
countProduct.decrementAmount();
return em.merge(countProduct);
}
@Transactional
public CountProduct deleteCountProduct(long productId, long cartId){
final CountProduct countProduct = getCountProduct(productId, cartId);
em.remove(countProduct);
return countProduct;
}
@Transactional
public void deleteAll(){
var list = getAllCountProducts();
for (var cp:
list) {
cp.deleteThis();
em.remove(cp);
}
}
@Transactional
public List<CountProduct> getAllCountProducts(){
return em.createQuery("from CountProduct", CountProduct.class).getResultList();
}
@Transactional
public List<CountProduct> getFilteredCountProduct(Long customerId, int amount, int minSum){
return em.createQuery("SELECT c FROM CountProduct c" +
" WHERE c.cart.customer.id = ?1 AND c.amount = ?2 AND c.product.price > ?3",CountProduct.class)
.setParameter(1, customerId)
.setParameter(2, amount)
.setParameter(3, minSum)
.getResultList();
}
}

View File

@ -0,0 +1,68 @@
package com.example.lab.DataBase.Services;
import com.example.lab.DataBase.Models.Cart;
import com.example.lab.DataBase.Models.CountProduct;
import jakarta.persistence.*;
import jakarta.transaction.Transactional;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import com.example.lab.DataBase.Models.Customer;
import java.util.List;
@Service
public class CustomerService {
@PersistenceContext
private EntityManager em;
@Transactional
public Customer addCustomer(String customerFirstName, String customerLastName, String customerAddress){
if (!StringUtils.hasText(customerFirstName) || !StringUtils.hasText(customerLastName)){
throw new IllegalArgumentException("Customer first and last names can't be null");
}
else if(!StringUtils.hasText(customerAddress)){
throw new IllegalArgumentException("Customer address can't be null");
}
Customer customer = new Customer(customerLastName, customerFirstName, customerAddress);
em.persist(customer);
return customer;
}
@Transactional()
public Customer getCustomer(Long id){
Customer customer = em.find(Customer.class, id);
if (customer == null){
throw new EntityNotFoundException(String.format("Error: Customer id %s not found", id));
}
return customer;
}
@Transactional
public List<Customer> getAllCustomers(){
return em.createQuery("get c from Customer c", Customer.class).getResultList();
}
@Transactional
public Customer updateCustomer(Long id, String customerLastName, String customerFirstName, String customerAddress){
if (!StringUtils.hasText(customerLastName) || !StringUtils.hasText(customerFirstName)){
throw new IllegalArgumentException("Customer last or/and first name is null");
}
if (!StringUtils.hasText(customerAddress)){
throw new IllegalArgumentException("Customer address can't be null");
}
final Customer customer = getCustomer(id);
customer.setLastName(customerLastName);
customer.setFirstName(customerFirstName);
customer.setCustomerAddress(customerAddress);
return em.merge(customer);
}
@Transactional
public Customer deleteCustomer(Long id){
final Customer customer = getCustomer(id);
em.remove(customer);
return customer;
}
@Transactional
public void deleteAllCustomers(){
em.createQuery("Delete from Customer").executeUpdate();
}
}

View File

@ -0,0 +1,59 @@
package com.example.lab.DataBase.Services;
import jakarta.persistence.*;
import jakarta.transaction.Transactional;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import com.example.lab.DataBase.Models.ProductCategory;
import java.util.List;
@Service
public class ProductCategoryService {
@PersistenceContext
private EntityManager em;
@Transactional
public ProductCategory addProductCategory(String name){
if (!StringUtils.hasText(name)){
throw new IllegalArgumentException("ProductCategory name can't be null");
}
ProductCategory productCategory = new ProductCategory(name);
em.persist(productCategory);
return productCategory;
}
@Transactional()
public ProductCategory getProductCategory(Long id){
ProductCategory productCategory = em.find(ProductCategory.class, id);
if (productCategory == null){
throw new EntityNotFoundException(String.format("Error: ProductCategory id %s not found", id));
}
return productCategory;
}
@Transactional
public List<ProductCategory> getAllProductCategorys(){
return em.createQuery("get c from ProductCategory c", ProductCategory.class).getResultList();
}
@Transactional
public ProductCategory updateProductCategory(Long id, String productCategoryName){
if (!StringUtils.hasText(productCategoryName)){
throw new IllegalArgumentException("ProductCategory name is null");
}
final ProductCategory productCategory = getProductCategory(id);
productCategory.setName(productCategoryName);
return em.merge(productCategory);
}
@Transactional
public ProductCategory deleteProductCategory(Long id){
final ProductCategory productCategory = getProductCategory(id);
em.remove(productCategory);
return productCategory;
}
@Transactional
public void deleteAllProductCategories(){
em.createQuery("Delete from ProductCategory").executeUpdate();
}
}

View File

@ -0,0 +1,72 @@
package com.example.lab.DataBase.Services;
import com.example.lab.DataBase.Models.ProductCategory;
import jakarta.persistence.*;
import jakarta.transaction.Transactional;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import com.example.lab.DataBase.Models.Product;
import java.util.List;
@Service
public class ProductService {
@PersistenceContext
private EntityManager em;
@Transactional
public Product addProduct(String name, float price, ProductCategory productCategory){
if (!StringUtils.hasText(name)){
throw new IllegalArgumentException("Product first and last names can't be null");
}
else if(price <= 0){
throw new IllegalArgumentException("Product price cant be under 0");
}
Product product = new Product(name, price, productCategory);
product.getProductCategory().AddProduct(product);
em.persist(product);
return product;
}
@Transactional()
public Product getProduct(Long id){
Product product = em.find(Product.class, id);
if (product == null){
throw new EntityNotFoundException(String.format("Error: Product id %s not found", id));
}
return product;
}
@Transactional
public List<Product> getAllProducts(){
return em.createQuery("from Product", Product.class).getResultList();
}
@Transactional
public Product updateProduct(Long id, String name, float price){
if (!StringUtils.hasText(name)){
throw new IllegalArgumentException("Product name cant be null");
}
else if(price <= 0){
throw new IllegalArgumentException("Product price cant be under 0");
}
final Product product = getProduct(id);
product.setName(name);
product.setPrice(price);
return em.merge(product);
}
@Transactional
public Product deleteProduct(Long id){
final Product product = getProduct(id);
em.remove(product);
return product;
}
@Transactional
public void deleteAllProducts(){
for (var product:
getAllProducts()) {
product.deleteThis();
em.remove(product);
}
}
}

View File

@ -1,77 +1,16 @@
package com.example.lab;
import com.example.lab.AllTypeCalc.controller.CalcController;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class LabApplication {
public static void main(String[] args) {
SpringApplication.run(LabApplication.class, args);
}
@GetMapping("/calculateSquare")
public String calculateSquare(@RequestParam int num,
@RequestParam int step) {
double res;
res = Math.pow(num,step);
return ("Результат: " + Double.toString(res));
}
@GetMapping("/calculateFactorial")
public String calculateFactorial(@RequestParam int num) {
long res = 1;
for (int i = 1; i <= num; i++) {
res = res * i;
}
return ("Результат: " + Long.toString(res));
}
public int getFibonacciValue(int n) {
if (n <= 1) {
return 0;
} else if (n == 2) {
return 1;
} else {
return getFibonacciValue(n - 1) + getFibonacciValue(n - 2);
}
}
@GetMapping("/calculateFibbN")
public String calculateFibbN(@RequestParam int num) {
int result = 0;
result = getFibonacciValue(num);
return ("Результат: " + Integer.toString(result));
}
public static boolean checkSimple(int i){
if (i<=1)
return false;
else if (i <=3)
return true;
else if (i%2==0 || i %3 ==0)
return false;
int n = 5;
while (n*n <=i){
if (i % n ==0 || i % (n+2) == 0)
return false;
n=n+6;
}
return true;
}
@GetMapping("/calculateLastSimple")
public String calculateSimple(@RequestParam int num){
int result = 0;
for (int i=2;i<=num;i++){
if(checkSimple(i))
result = i;
}
return ("Результат: " + Integer.toString(result));
}
}

View File

@ -0,0 +1,13 @@
package com.example.lab;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfiguration implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedMethods("*");
}
}

View File

@ -1 +1,11 @@
spring.main.banner-mode=off
#server.port=8080
spring.datasource.url=jdbc:h2:file:./data
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=user
spring.datasource.password=password
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto=update
spring.h2.console.enabled=true
spring.h2.console.settings.trace=false
spring.h2.console.settings.web-allow-others=false

View File

@ -0,0 +1,143 @@
package com.example.lab;
import com.example.lab.DataBase.Models.*;
import com.example.lab.DataBase.Services.CartService;
import com.example.lab.DataBase.Services.CustomerService;
import com.example.lab.DataBase.Services.ProductCategoryService;
import com.example.lab.DataBase.Services.ProductService;
import com.example.lab.DataBase.Services.CountProductService;
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 java.util.*;
@SpringBootTest
public class DBTests {
@Autowired
CartService cartService;
@Autowired
CustomerService customerService;
@Autowired
ProductCategoryService productCategoryService;
@Autowired
ProductService productService;
@Autowired
CountProductService countProductService;
@Test
void testProductCategory(){
cleanAll();
ProductCategory productCategory = productCategoryService.addProductCategory("exampleCategory");
Assertions.assertEquals("exampleCategory", productCategory.getName());
productCategoryService.updateProductCategory(productCategory.getId(), "updExample");
Assertions.assertEquals("updExample", productCategoryService
.getProductCategory(productCategory.getId()).getName());
Assertions.assertEquals("updExample", productCategoryService
.deleteProductCategory(productCategory.getId()).getName());
cleanAll();
}
@Test
void testProduct() {
cleanAll();
ProductCategory productCategory = productCategoryService.addProductCategory("exampleCategory");
Product product = productService.addProduct("example", (float) 50, productCategory);
Assertions.assertEquals("example", product.getName());
Assertions.assertEquals("exampleCategory", product.getProductCategory().getName());
Assertions.assertEquals("example", productService.getProduct(product.getId()).getName());
Assertions.assertEquals((float) 50, productService.getProduct(product.getId()).getPrice());
productService.updateProduct(product.getId(), "newExample", (float) 60);
Assertions.assertEquals("newExample", productService.getProduct(product.getId()).getName());
Assertions.assertEquals((float) 60, productService.getProduct(product.getId()).getPrice());
Assertions.assertEquals("newExample", productService.deleteProduct(product.getId()).getName());
cleanAll();
}
@Test
void testCustomer(){
cleanAll();
Customer customer = customerService.addCustomer("Ivan",
"Ivanov", "cityExample");
Assertions.assertEquals("Ivan", customerService
.getCustomer(customer.getId()).getFirstName());
Assertions.assertEquals("Ivanov", customerService
.getCustomer(customer.getId()).getLastName());
Assertions.assertEquals("cityExample", customerService
.getCustomer(customer.getId()).getCustomerAddress());
customerService.updateCustomer(customer.getId(),"Vaskin",
"Vasilii", "newAddress");
Assertions.assertEquals("Vasilii", customerService
.getCustomer(customer.getId()).getFirstName());
Assertions.assertEquals("Vaskin", customerService
.getCustomer(customer.getId()).getLastName());
Assertions.assertEquals("newAddress", customerService
.getCustomer(customer.getId()).getCustomerAddress());
Assertions.assertEquals("Vasilii", customerService
.deleteCustomer(customer.getId()).getFirstName());
cleanAll();
}
@Test
void testCart(){
cleanAll();
ProductCategory productCategory = productCategoryService
.addProductCategory("exampleCategory");
Product product = productService
.addProduct("exampleProduct", (float)50, productCategory );
Customer customer = customerService.addCustomer("Ivan",
"Ivanov", "cityExample");
Cart cart = cartService.addCart(customer);
Assertions.assertEquals(product,cartService.addProduct(cart.getId(), product.getId()));
Assertions.assertEquals(cart,cartService.getCart(cart.getId()));
Assertions.assertEquals(product, cartService.reduceProduct(cart.getId(),product.getId()));
Assertions.assertEquals(product, cartService.deleteProduct(cart.getId(),product.getId()));
Assertions.assertEquals(cart,cartService.deleteCart(cart.getId()));
cleanAll();
}
@Test
void testCountProductService(){
cleanAll();
ProductCategory productCategory = productCategoryService
.addProductCategory("exampleCategory");
Product product1 = productService
.addProduct("exampleProduct1", (float)50, productCategory);
Product product2 = productService
.addProduct("exampleProduct2", (float)500, productCategory);
Product product3 = productService
.addProduct("exampleProduct2", (float)200, productCategory);
Customer customer = customerService.addCustomer("Ivan",
"Ivanov", "cityExample");
Cart cart = cartService.addCart(customer);
CountProduct countProduct = cartService.addProduct(cart.getId(), product1.getId());
CountProduct countProduct2 = cartService.addProduct(cart.getId(), product2.getId());
CountProduct countProduct3 = cartService.addProduct(cart.getId(), product3.getId());
List<CountProduct> expected = new ArrayList<>();
countProduct2 = countProductService.incrementProduct(countProduct2.getProduct().getId(), countProduct2.getCart().getId());
countProduct2 = countProductService.incrementProduct(countProduct2.getProduct().getId(), countProduct2.getCart().getId());
expected.add(countProduct2);
Assertions.assertEquals(expected, countProductService.getFilteredCountProduct(customer.getId(), 3,100));
cleanAll();
}
public void cleanAll(){
countProductService.deleteAll();
productService.deleteAllProducts();
cartService.deleteAllCarts();
customerService.deleteAllCustomers();
productCategoryService.deleteAllProductCategories();
}
}

View File

@ -1,13 +1,67 @@
package com.example.lab;
import com.example.lab.AllTypeCalc.service.CalcService;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class LabApplicationTests {
@Autowired
CalcService calcService;
@Test
void contextLoads() {
void testIntSum() {
final Object result = calcService.GetSum(1, 2, "int");
Assertions.assertEquals("3", result.toString());
}
@Test
void testStringSum() {
final Object result = calcService.GetSum("ab", "bc", "str");
Assertions.assertEquals("abbc", result.toString());
}
@Test
void testIntMinus() {
final Object result = calcService.GetMinus(5, 4, "int");
Assertions.assertEquals("1", result.toString());
}
@Test
void testStringMinus() {
final Object result = calcService.GetMinus("abc", "bc", "str");
Assertions.assertEquals("a", result.toString());
}
@Test
void testIntMult() {
final Object result = calcService.GetMult(4, 4, "int");
Assertions.assertEquals("16", result.toString());
}
@Test
void testStringMult() {
final Object result = calcService.GetMult("ab", "bc", "str");
Assertions.assertEquals("abab", result.toString());
}
@Test
void testIntDiv() {
final Object result = calcService.GetDiv(12, 6, "int");
Assertions.assertEquals("2", result.toString());
}
@Test
void testStringDiv() {
final Object result = calcService.GetDiv("ab", "bc", "str");
Assertions.assertEquals("1.0", result.toString());
}
@Test
void testCalculatorErrorWired() {
Assertions.assertThrows(NoSuchBeanDefinitionException.class, () -> calcService.GetSum("1", "1", "integer"));
}
}

View File

@ -0,0 +1,6 @@
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=user
spring.datasource.password=password
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto=create-drop

View File

@ -11,16 +11,21 @@
<body class="ms-3">
<h3 class="mt-2">Вычисления</h3>
<div class="d-flex form-group">
<label class="m-2" for="textFieldNum">Число 1:</label>
<input type="number" class="form-control w-25" id="textFieldNum" placeholder="Введите число...">
<label class="m-2" for="textFieldNum2">Число 2:</label>
<input type="number" class="form-control w-25" id="textFieldNum2" placeholder="Введите число...">
<label class="m-2" for="obj1Input">Поле 1:</label>
<input class="w-25" id="obj1Input" placeholder="Введите...">
<label class="m-2" for="obj2Input">Поле 2:</label>
<input class="w-25" id="obj2Input" placeholder="Введите...">
<select class="custom-select w-auto ms-3" id="typeSelect">
<option value="int">Числа</option>
<option value="str">Строки</option>
<option value="arr">Массив</option>
</select>
</div>
<div>
<button id = "1" class="btn btn-primary w-auto mt-2 ms-3" onclick="Okclick(this.id)">Степень</button>
<button id = "2" class="btn btn-primary w-auto mt-2 ms-3" onclick="Okclick(this.id)">Факториал</button>
<button id = "3" class="btn btn-primary w-auto mt-2 ms-3" onclick="Okclick(this.id)">Фибоначчи</button>
<button id = "4" class="btn btn-primary w-auto mt-2 ms-3" onclick="Okclick(this.id)">Простое число</button>
<button id = "1" class="btn btn-primary w-auto mt-2 ms-3" onclick="Okclick(this.id)">+</button>
<button id = "2" class="btn btn-primary w-auto mt-2 ms-3" onclick="Okclick(this.id)">-</button>
<button id = "3" class="btn btn-primary w-auto mt-2 ms-3" onclick="Okclick(this.id)">*</button>
<button id = "4" class="btn btn-primary w-auto mt-2 ms-3" onclick="Okclick(this.id)">%</button>
</div>
<a id="res"></a>
</body>

View File

@ -1,26 +1,34 @@
function Okclick(clicked) {
var num = document.getElementById("textFieldNum").value
var num2 = document.getElementById("textFieldNum2").value
var obj1 = document.getElementById("obj1Input").value
var obj2 = document.getElementById("obj2Input").value
var typeInp = document.getElementById("typeSelect").value
var id = clicked;
var argument = "";
console.log(typeInp);
if (document.getElementById("typeSelect").value == "arr"){
console.log("aaa");
obj1= encodeURIComponent(obj1);
obj2 = encodeURIComponent(obj2);
console.log(obj1);
console.log(obj2);
}
if(id == "1"){
argument = ("calculateSquare?num=" + num +"&step=" + num2);
argument = ("GetSum?obj1=" + obj1 +"&obj2=" + obj2 + "&typeInp=" + typeInp);
}
else if (id == "2"){
argument = ("calculateFactorial?num=" + num);
argument = ("GetMinus?obj1=" + obj1 + "&obj2=" + obj2 + "&typeInp=" + typeInp);
}
else if( id == "3"){
argument = ("calculateFibbN?num=" + num);
argument = ("GetMult?obj1=" + obj1 + "&obj2=" + obj2 + "&typeInp=" + typeInp);
}
else if (id == "4"){
argument = ("calculateLastSimple?num=" + num);
argument = ("GetDiv?obj1=" + obj1 + "&obj2=" + obj2 + "&typeInp=" + typeInp);
}
fetch ("http://127.0.0.1:8080/" + argument)
.then(response => response.text())
.then((response) => {
console.log(response)
document.getElementById("res").innerHTML = response
document.getElementById("res").innerHTML = "Результат = " + response
})
}