Compare commits

...

2 Commits

Author SHA1 Message Date
39680b73cf Готовая 3 лаба 2023-04-15 21:07:36 +04:00
108665ee17 Готовая 2 лаба 2023-03-07 09:42:01 +03:00
20 changed files with 1211 additions and 59 deletions

View File

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

View File

@ -2,40 +2,49 @@ function setResult(result) {
let lbl = `<label class="bg-success">Ответ:${result}</label>`; let lbl = `<label class="bg-success">Ответ:${result}</label>`;
document.getElementById("result").innerHTML = lbl; document.getElementById("result").innerHTML = lbl;
} }
let addButton = document.getElementById("getResultAdd");
let a = document.getElementById("addNum1");
let b = document.getElementById("addNum2");
let Output = document.getElementById("addAnswer");
let address = "hello"
function add(){ function add(){
address = "add" executeRequest("add");
executeRequest();
} }
function sub(){ function sub(){
address = "sub" executeRequest("sub");
executeRequest();
} }
function mul(){ function mul(){
address = "mul" executeRequest("mul");
executeRequest();
} }
function del(){ function del(){
executeRequest("del");
address = "del"
if(b.value != 0) executeRequest();
} }
function executeRequest() { function enterArray(){
executeRequestArray("array");
}
let num1 = a.value; function executeRequest(address) {
let num2 = b.value; let num1 = document.getElementById("addNum1").value;
let num2 = document.getElementById("addNum2").value;
let type = document.getElementById("type").value;
console.log("a" + num1 + "b" + num2) console.log("a" + num1 + "b" + num2)
fetch(`http://localhost:8080/${address}?a=${num1}&b=${num2}`) fetch(`http://localhost:8080/${address}?a=${num1}&b=${num2}&type=${type}`)
.then(response => { .then(response => {
return response.json(); return response.text();
}) })
.then(result => { .then(result => {
setResult(result); setResult(result);
}) })
} }
function executeRequestArray(address) {
let array = document.getElementById("enterArray").value;
fetch(`http://localhost:8080/${address}?InputNumbers=${array}&type=${type}`)
.then(response => {
return response.json();
})
.then(result => {
setResult(result);
})
}

View File

@ -9,20 +9,27 @@
<body> <body>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js" integrity="sha384-w76AqPfDkMBDXo30jS1Sgez6pr3x5MlQ1ZAGC+nuZB+EYdgRZgiwxhTBTkF7CXvN" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js" integrity="sha384-w76AqPfDkMBDXo30jS1Sgez6pr3x5MlQ1ZAGC+nuZB+EYdgRZgiwxhTBTkF7CXvN" crossorigin="anonymous"></script>
<main> <main>
<div class = "container" style="margin: 1%">
<h4 class="mb-3">Команды</h4> <h4 class="mb-3">Команды</h4>
<p>Сложение</p> <p>Сложение</p>
<input type="number" class="form-control" id="addNum1" placeholder="" value="0" required="" style="width: 10%;"> <input type="text" class="form-control" id="addNum1" placeholder="" value="0" required="" style="width: 10%;">
<input type="number" class="form-control" id="addNum2" placeholder="" value="0" required="" style="width: 10%;"> <input type="text" class="form-control" id="addNum2" placeholder="" value="0" required="" style="width: 10%;">
<select class="form-select form-select-lg mb-3" id= "type" aria-label=".form-select-lg example" style="width: 10%">
<option selected>Тип</option>
<option value="string">string</option>
<option value="int">int</option>
<option value="boolean">boolean</option>
</select>
<button class="btn btn-success" onclick="add()">Сложить</button> <button class="btn btn-success" onclick="add()">Сложить</button>
<button class="btn btn-success" onclick="sub()">Вычесть</button> <button class="btn btn-success" onclick="sub()">Вычесть</button>
<button class="btn btn-success" onclick="mul()">Умножить</button> <button class="btn btn-success" onclick="mul()">Умножить</button>
<button class="btn btn-success" onclick="del()">Поделить</button> <button class="btn btn-success" onclick="del()">Поделить</button>
<div id="result">Ответ:</div>
<div id="result">Ответ:</div>
</div>
</main> </main>
<script src="MyScript.js"></script> <script src="MyScript.js"></script>

View File

@ -15,39 +15,7 @@ public class MyappApplication {
SpringApplication.run(MyappApplication.class, args); SpringApplication.run(MyappApplication.class, args);
} }
@GetMapping("/hello")
public String hello(@RequestParam(value = "name", defaultValue = "World") String name) {
return String.format("Hello %s!", name);
}
@CrossOrigin
@GetMapping(value = "/add")
public Integer doSum(@RequestParam(value = "a", defaultValue = "0") int a,
@RequestParam(value = "b", defaultValue = "0") int b){
return a + b;
}
@GetMapping("/sub")
public Integer doSub(@RequestParam(value = "a", defaultValue = "0") int a,
@RequestParam(value = "b", defaultValue = "0") int b){
return a - b;
}
@GetMapping("/mul")
public Integer doMul(@RequestParam(value = "a", defaultValue = "0") int a,
@RequestParam(value = "b", defaultValue = "0") int b){
return a * b;
}
@GetMapping("/del")
public Integer doDel(@RequestParam(value = "a", defaultValue = "0") int a,
@RequestParam(value = "b", defaultValue = "1") int b){
return a / b;
}
@GetMapping("/mu")
public String len(@RequestParam(value = "word", defaultValue = "") String name){
return String.format("Длина слова " + name + " " + len(name));
}
@GetMapping("/de")
public String root(){
return new Date().toString();
}

View File

@ -0,0 +1,53 @@
package ru.ulstu.is.myapp.controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import ru.ulstu.is.myapp.service.MethodService;
import java.util.Date;
@RestController
public class Controller {
private final MethodService methodService;
public Controller(MethodService methodService){
this.methodService = methodService;
}
@GetMapping("/hello")
public String hello(@RequestParam(value = "name", defaultValue = "World") String name) {
return String.format("Hello %s!", name);
}
@CrossOrigin
@GetMapping(value = "/add")
public String doSum(@RequestParam(value = "a", defaultValue = "0") Object a,
@RequestParam(value = "b", defaultValue = "0") Object b,
@RequestParam(value = "type", defaultValue = "int") String type){
return methodService.doSum(a,b, type);
}
@GetMapping("/sub")
public String doSub(@RequestParam(value = "a", defaultValue = "0") Object a,
@RequestParam(value = "b", defaultValue = "0") Object b,
@RequestParam(value = "type", defaultValue = "int") String type){
return methodService.doSub(a, b, type);
}
@GetMapping("/mul")
public String doMul(@RequestParam(value = "a", defaultValue = "0") Object a,
@RequestParam(value = "b", defaultValue = "0") Object b,
@RequestParam(value = "type", defaultValue = "int") String type){
return methodService.doMul(a, b, type);
}
@GetMapping("/del")
public String doDel(@RequestParam(value = "a", defaultValue = "0") Object a,
@RequestParam(value = "b", defaultValue = "1") Object b,
@RequestParam(value = "type", defaultValue = "int") String type){
return methodService.doDel(a, b, type);
}
@GetMapping("/mu")
public String len(@RequestParam(value = "word", defaultValue = "") String name){
return String.format("Длина слова " + name + " " + len(name));
}
@GetMapping("/de")
public String root(){
return new Date().toString();
}
}

View File

@ -0,0 +1,28 @@
package ru.ulstu.is.myapp.domain;
import org.springframework.stereotype.Component;
@Component(value="boolean")
public class BoolMethod implements IMethods<Boolean>{
@Override
public Boolean doSum(Boolean a, Boolean b) {
return a || b;
}
@Override
public Boolean doSub(Boolean a, Integer b) {
return (!a && b%2==0) || (a && !(b%2==0));
}
@Override
public Boolean doMul(Boolean a, Integer b) {
return a && b%2 != 0;
}
@Override
public Boolean doDel(Boolean a, Integer b) {
if (b%2==0) return false;
else if(!a) return false;
else return true;
}
}

View File

@ -0,0 +1,9 @@
package ru.ulstu.is.myapp.domain;
public interface IMethods<T> {
T doSum(T a, T b);
T doSub(T a, Integer b);
T doMul(T a, Integer b);
T doDel(T a, Integer b);
}

View File

@ -0,0 +1,30 @@
package ru.ulstu.is.myapp.domain;
import org.springframework.stereotype.Component;
@Component(value="int")
public class IntMethod implements IMethods<Integer> {
@Override
public Integer doSum(Integer a, Integer b) {
return a + b;
}
@Override
public Integer doSub(Integer a, Integer b) {
return a - b;
}
@Override
public Integer doMul(Integer a, Integer b) {
return a*b;
}
@Override
public Integer doDel(Integer a, Integer b) {
if(b!=0){
return a/b;
}
return null;
}
}

View File

@ -0,0 +1,49 @@
package ru.ulstu.is.myapp.domain;
import org.springframework.stereotype.Component;
@Component(value="string")
public class StrMethod implements IMethods<String> {
@Override
public String doSum(String a, String b) {
return a.concat(b);
}
@Override
public String doSub(String a, Integer b) {
String temp = a;
if(temp.length() >= b){
return temp.substring(0, a.length() - b);
}else{
return a;
}
}
@Override
public String doMul(String a, Integer b) {
String str = " ";
if(b == 0){
return str;
}
for(int i = 0; i < b; i++){
str = str + a;
}
return str;
}
@Override
public String doDel(String a, Integer b) {
if(b == 0){
return "На ноль делить нельзя!";
}
char[] chara = a.toCharArray();
String result = "";
for(int i = 0; i < chara.length/b; i++){
result += chara[i];
}
return result;
}
}

View File

@ -0,0 +1,113 @@
package ru.ulstu.is.myapp.models;
import jakarta.persistence.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
@Entity
@Table(name = "table_customer")
public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column()
private String firstName;
private String lastName;
private String address;
private String email;
@OneToMany(mappedBy = "customer", cascade = CascadeType.ALL,fetch = FetchType.EAGER)
private List<Purchase> purchases = new ArrayList<>();
public Customer() {
}
public Customer(String firstName, String lastName, String address, String email) {
this.firstName = firstName;
this.lastName = lastName;
this.address = address;
this.email = email;
}
public Long getId() {
return id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getAddress() {
return address;
}
public String setAddress(String address) {
return address;
}
public String getEmail() {
return email;
}
public String setEmail(String email) {
return email;
}
public List<Purchase> getPurchases() {
return purchases;
}
public void setPurchases(List<Purchase> purchases) {
this.purchases = purchases;
}
public void addNewPurchase(Purchase purchase) {
purchases.add(purchase);
purchase.setCustomer(this);
}
public void deletePurchase(Purchase purchase) {
purchases.remove(purchase);
purchase.deleteCompany();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Customer customer = (Customer) o;
return Objects.equals(id, customer.id);
}
public int hashCode() {
return Objects.hash(id);
}
@Override
public String toString() {
return "Customer{" +
"id=" + id +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", address='" + address + '\'' +
", email='" + email + '\'' +
", purchases=" + purchases +
'}';
}
}

View File

@ -0,0 +1,99 @@
package ru.ulstu.is.myapp.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;
@Column()
private String name;
private Double price;
private String category;
@ManyToMany(mappedBy = "products", cascade = {CascadeType.REMOVE}, fetch = FetchType.EAGER)
private List<Purchase> purchases = new ArrayList<>();
public Product(){
}
public Product(String name, Double price, String category){
this.name = name;
this.price = price;
this.category = category;
}
public Long getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
//
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Product product = (Product) o;
return Objects.equals(id, product.id);
}
public List<Purchase> getPurchases() {
return purchases;
}
public void setPurchases(List<Purchase> employees) {
this.purchases = employees;
}
public void addNewPurchase(Purchase purchase) {
purchases.add(purchase);
}
public void deletePurchase(Purchase purchase) {
purchases.remove(purchase);
if (purchase.getProducts().contains(this)) {
purchase.removeProducts(this);
}
}
public int hashCode() {
return Objects.hash(id);
}
@Override
public String toString() {
return "Product{" +
"id=" + id +
", name='" + name + '\'' +
", price='" + price + '\'' +
", category='" + category + '\'' +
'}';
}
}

View File

@ -0,0 +1,101 @@
package ru.ulstu.is.myapp.models;
import jakarta.persistence.*;
import java.util.*;
@Entity
public class Purchase {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column
@Temporal(TemporalType.DATE)
private Date purchase_date;
private double price;
@ManyToOne(fetch = FetchType.EAGER,cascade = CascadeType.MERGE)
private Customer customer;
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private Set<Product> products = new HashSet<>();
public Purchase(){
}
public Purchase(Date purchase_date, Double price){
this.purchase_date = purchase_date;
this.price = price;
}
public Long getId() {
return id;
}
public Date getDate() {
return purchase_date;
}
public void setDate(Date purchase_date) {
this.purchase_date = purchase_date;
}
//
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public Customer getCustomer() {
return customer;
}
public List<Product> getProducts() {
return products.stream().toList();
}
public void addNewProduct(Product p) {
products.add(p);
if (!p.getPurchases().contains(this)) {
p.addNewPurchase(this);
}
}
public void removeProducts(Product product) {
products.remove(product);
if (product.getPurchases().contains(this)) {
product.deletePurchase(this);
}
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
public void deleteCompany() {
if (customer.getPurchases().contains(this)) {
customer.deletePurchase(this);
}
this.customer = null;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Purchase p = (Purchase) o;
return Objects.equals(id, p.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
@Override
public String toString() {
return "Purchase{" +
"Id=" + id +
", purchase_date='" + purchase_date + '\'' +
", price=" + price +
'}';
}
}

View File

@ -0,0 +1,83 @@
package ru.ulstu.is.myapp.service;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityNotFoundException;
import jakarta.persistence.PersistenceContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import ru.ulstu.is.myapp.models.Customer;
import ru.ulstu.is.myapp.models.Purchase;
import java.util.List;
@Service
public class CustomerService {
@PersistenceContext
private EntityManager em;
@Transactional
public Customer addCustomer(String firstName, String lastName, String address, String email) {
if (!StringUtils.hasText(firstName) || !StringUtils.hasText(lastName) || !StringUtils.hasText(address) || !StringUtils.hasText(email) ) {
throw new IllegalArgumentException("Пустое поле!");
}
final Customer customer = new Customer(firstName, lastName, address, email);
em.persist(customer);
return customer;
}
@Transactional(readOnly = true)
public Customer findCustomer(Long id) {
final Customer customer = em.find(Customer.class, id);
if (customer == null) {
throw new EntityNotFoundException(String.format("Company with id [%s] is not found", id));
}
return customer;
}
@Transactional(readOnly = true)
public List<Customer> findAllCustomers() {
return em.createQuery("select c from Customer c", Customer.class)
.getResultList();
}
@Transactional
public Customer updateCustomer(Long id, String firstName, String lastName, String address, String email) {
if (!StringUtils.hasText(firstName) || !StringUtils.hasText(lastName) || !StringUtils.hasText(address) || !StringUtils.hasText(email)) {
throw new IllegalArgumentException("Пустое поле");
}
final Customer currentCustomer = findCustomer(id);
currentCustomer.setFirstName(firstName);
currentCustomer.setLastName(lastName);
currentCustomer.setEmail(email);
currentCustomer.setAddress(address);
return em.merge(currentCustomer);
}
@Transactional
public Customer deleteCustomer(Long id) {
final Customer currentCustomer = findCustomer(id);
em.remove(currentCustomer);
return currentCustomer;
}
@Transactional
public void deleteAllCustomer() {
em.createQuery("delete from Customer").executeUpdate();
}
@Transactional
public void addNewPurchase(Long id, Purchase purchase) {
Customer currentCustomer = findCustomer(id);
currentCustomer.addNewPurchase(purchase);
em.merge(currentCustomer);
}
@Transactional
public void deletePurchase(Long id, Purchase purchase) {
Customer currentCustomer = findCustomer(id);
currentCustomer.deletePurchase(purchase);
em.merge(purchase);
}
}

View File

@ -0,0 +1,76 @@
package ru.ulstu.is.myapp.service;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import ru.ulstu.is.myapp.domain.BoolMethod;
import ru.ulstu.is.myapp.domain.IMethods;
import ru.ulstu.is.myapp.domain.IntMethod;
import ru.ulstu.is.myapp.domain.StrMethod;
@Service
public class MethodService {
private final ApplicationContext applicationContext;
public MethodService(ApplicationContext applicationContext){
this.applicationContext = applicationContext;
}
public String doSum(Object a, Object b, String type){
final IMethods method = (IMethods) applicationContext.getBean(type);
if(method instanceof StrMethod){
System.out.print("str");
return String.format("%s" , method.doSum(a, b));
}
if(method instanceof IntMethod){
System.out.print("int");
return String.format("%s" , method.doSum(Integer.parseInt(a.toString()), Integer.parseInt(b.toString())));
}
if(method instanceof BoolMethod){
System.out.print("bool");
return String.format("%s" , method.doSum(Boolean.parseBoolean(a.toString()), Boolean.parseBoolean(b.toString())));
}
return null;
}
public String doSub(Object a, Object b, String type){
final IMethods method = (IMethods) applicationContext.getBean(type);
if(method instanceof StrMethod){
return String.format("%s" , method.doSub(a.toString(), Integer.parseInt(b.toString())));
}
if(method instanceof IntMethod){
return String.format("%s" , method.doSub(Integer.parseInt(a.toString()), Integer.parseInt(b.toString())));
}
if(method instanceof BoolMethod){
return String.format("%s" , method.doSub(Boolean.parseBoolean(a.toString()), Integer.parseInt(b.toString())));
}
return null;
}
public String doMul(Object a, Object b, String type){
final IMethods method = (IMethods) applicationContext.getBean(type);
if(method instanceof StrMethod){
return String.format("%s" , method.doMul(a.toString(), Integer.parseInt(b.toString())));
}
if(method instanceof IntMethod){
return String.format("%s" , method.doMul(Integer.parseInt(a.toString()), Integer.parseInt(b.toString())));
}
if(method instanceof BoolMethod){
return String.format("%s" , method.doMul(Boolean.parseBoolean(a.toString()), Integer.parseInt(b.toString())));
}
return null;
}
public String doDel(Object a, Object b, String type){
final IMethods method = (IMethods) applicationContext.getBean(type);
if(method instanceof StrMethod){
return String.format("%s" , method.doDel(a.toString(), Integer.parseInt(b.toString())));
}
if(method instanceof IntMethod){
return String.format("%s" , method.doDel(Integer.parseInt(a.toString()), Integer.parseInt(b.toString())));
}
if(method instanceof BoolMethod){
return String.format("%s" , method.doDel(Boolean.parseBoolean(a.toString()), Integer.parseInt(b.toString())));
}
return null;
}
}

View File

@ -0,0 +1,67 @@
package ru.ulstu.is.myapp.service;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityNotFoundException;
import jakarta.persistence.PersistenceContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import ru.ulstu.is.myapp.models.Product;
import java.util.List;
@Service
public class ProductService {
@PersistenceContext
private EntityManager em;
@Transactional
public Product addProduct(String name, Double price, String category) {
if (!StringUtils.hasText(name)||!StringUtils.hasText(price.toString())||!StringUtils.hasText(category)) {
throw new IllegalArgumentException("Employee's data is null or empty");
}
final Product product = new Product(name, price, category);
em.persist(product);
return product;
}
@Transactional
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;
}
@Transactional(readOnly = true)
public List<Product> findAllProducts() {
return em.createQuery("select p from Product p", Product.class)
.getResultList();
}
@Transactional
public Product updateProduct(Long id, String name, Double price, String category) {
if (!StringUtils.hasText(name)||!StringUtils.hasText(price.toString())||!StringUtils.hasText(category)) {
throw new IllegalArgumentException("Пустое поле");
}
final Product currentProduct = findProduct(id);
currentProduct.setName(name);
currentProduct.setPrice(price);
currentProduct.setCategory(category);
return em.merge(currentProduct);
}
@Transactional
public Product deleteProduct(Long id) {
final Product p = findProduct(id);
em.remove(p);
return p;
}
@Transactional
public void deleteAllProducts() {
em.createQuery("delete from Product").executeUpdate();
}
}

View File

@ -0,0 +1,111 @@
package ru.ulstu.is.myapp.service;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityNotFoundException;
import jakarta.persistence.PersistenceContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import ru.ulstu.is.myapp.models.Customer;
import ru.ulstu.is.myapp.models.Product;
import ru.ulstu.is.myapp.models.Purchase;
import java.util.Date;
import java.util.List;
@Service
public class PurchaseService {
@PersistenceContext
private EntityManager em;
@Transactional
public Purchase addPurchase(Date purchase_date, Double price) {
if (!StringUtils.hasText(purchase_date.toString()) ||!StringUtils.hasText(price.toString())) {
throw new IllegalArgumentException("Пустое поле");
}
final Purchase purchase = new Purchase(purchase_date, price);
em.persist(purchase);
return purchase;
}
@Transactional
public Purchase findPurchase (Long id) {
final Purchase purchase = em.find(Purchase.class, id);
if (purchase == null) {
throw new EntityNotFoundException(String.format("Purchase with id [%s] is not found", id));
}
return purchase ;
}
@Transactional(readOnly = true)
public List<Purchase> findAllPurchases() {
return em.createQuery("select p from Purchase p", Purchase.class)
.getResultList();
}
@Transactional
public Purchase updatePurchase(Long id, Date purchase_date, Double price) {
if (!StringUtils.hasText(purchase_date.toString()) ||!StringUtils.hasText(price.toString())) {
throw new IllegalArgumentException("Пустое поле");
}
final Purchase currentPurchase = findPurchase(id);
currentPurchase.setDate(purchase_date);
currentPurchase.setPrice(price);
return em.merge(currentPurchase);
}
@Transactional
public Purchase deletePurchase(Long id) {
final Purchase purchase = findPurchase(id);
em.remove(purchase);
return purchase;
}
@Transactional
public void deleteAllPurchases() {
em.createQuery("delete from Purchase").executeUpdate();
}
@Transactional
public void addCustomer(Long id, Customer c) {
final Purchase purchase = findPurchase(id);
purchase.setCustomer(c);
em.merge(purchase);
}
@Transactional
public void deleteCustomer(Long id) {
final Purchase purchase = findPurchase(id);
purchase.deleteCompany();
em.merge(purchase);
}
@Transactional
public void addProduct(Long id, Product p) {
Purchase pur = findPurchase(id);
pur.addNewProduct(p);
em.merge(pur);
}
@Transactional
public void deleteProduct(Long id, Product p) {
Purchase pur = findPurchase(id);
pur.removeProducts(p);
em.merge(pur);
em.flush();
}
@Transactional
public List<Purchase> getPurchasesByProducts(Product p) {
List<Purchase> purchases = em.createQuery("select p from Purchase pur INNER JOIN pur.products p WHERE p.id=:product",
Purchase.class)
.setParameter("product", p.getId())
.getResultList();
for (Purchase pur : purchases) {
System.out.println(pur);
}
return purchases;
}
}

View File

@ -0,0 +1,118 @@
package ru.ulstu.is.myapp;
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 ru.ulstu.is.myapp.models.Customer;
import ru.ulstu.is.myapp.models.Purchase;
import ru.ulstu.is.myapp.service.CustomerService;
import ru.ulstu.is.myapp.service.PurchaseService;
import java.util.Date;
@SpringBootTest
public class CustomerServiceTests {
@Autowired
private CustomerService customerService;
@Autowired
private PurchaseService purchaseService;
@Test
public void testDeleteAllCustomers() {
customerService.deleteAllCustomer();
int n = 3;
for (int i = 0; i < n; i++) {
String name = "Customer" + i;
customerService.addCustomer(name, name, "address", "email"+i);
}
customerService.deleteAllCustomer();
Assertions.assertEquals(customerService.findAllCustomers().size(), 0);
}
@Test
public void testDeleteCustomer() {
customerService.deleteAllCustomer();
String name = "Customer1";
Customer c = customerService.addCustomer(name, name, "address", "email");
customerService.deleteCustomer(c.getId());
Assertions.assertThrows(EntityNotFoundException.class, () -> {customerService.findCustomer(c.getId());});
}
@Test
public void testAddCustomer() {
customerService.deleteAllCustomer();
String name = "Company1";
Customer c = customerService.addCustomer(name, name, "address", "email");
Assertions.assertNotNull(customerService.findCustomer(c.getId()));
customerService.deleteAllCustomer();
}
@Test
public void testUpdateCustomer() {
customerService.deleteAllCustomer();
String name = "Customer1";
Customer c = customerService.addCustomer(name, name, "address", "email");
String name2 = "Customer2";
customerService.updateCustomer(c.getId(), name2, name2, "fdgd", "effsd");
Assertions.assertNotNull(customerService.findCustomer(c.getId()));
customerService.deleteAllCustomer();
}
@Test
public void testFindAllCustomers() {
customerService.deleteAllCustomer();
int n = 3;
for (int i = 0; i < n; i++) {
String name = "customer" + i;
customerService.addCustomer(name, name, "address", "email2");
}
Assertions.assertEquals(customerService.findAllCustomers().size(), n);
customerService.deleteAllCustomer();
}
@Test
public void testAddPurchase() {
purchaseService.deleteAllPurchases();
customerService.deleteAllCustomer();
final String name = "Customer";
Customer c = customerService.addCustomer(name, name, "address", "email");
Purchase newPurchase = purchaseService.addPurchase(new Date(1212121212121L), 3456.00);
customerService.addNewPurchase(c.getId(), newPurchase);
Assertions.assertTrue(customerService.findCustomer(c.getId()).getPurchases().contains(newPurchase));
purchaseService.deleteAllPurchases();
customerService.deleteAllCustomer();
}
@Test
public void testDeletePurchase() {
purchaseService.deleteAllPurchases();
customerService.deleteAllCustomer();
final String name = "Company";
Customer c = customerService.addCustomer(name, name, "address", "email");
Purchase newPurchase = purchaseService.addPurchase(new Date(1212121212121L), 3567.00);
customerService.addNewPurchase(c.getId(), newPurchase);
Assertions.assertTrue(customerService.findCustomer(c.getId()).getPurchases().contains(newPurchase));
customerService.deletePurchase(c.getId(), newPurchase);
Assertions.assertFalse(customerService.findCustomer(c.getId()).getPurchases().contains(newPurchase));
purchaseService.deleteAllPurchases();
purchaseService.deleteAllPurchases();
}
}

View File

@ -1,13 +1,91 @@
package ru.ulstu.is.myapp; package ru.ulstu.is.myapp;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test; 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; import org.springframework.boot.test.context.SpringBootTest;
import ru.ulstu.is.myapp.service.MethodService;
@SpringBootTest @SpringBootTest
class MyappApplicationTests { class MyappApplicationTests {
@Autowired
private MethodService methodService;
@Test @Test
void contextLoads() { void contextLoads() {
} }
//sum
@Test
void testSumStr(){
String res = methodService.doSum("Hi, ", "Dima", "string");
Assertions.assertEquals("Hi, Dima", res);
}
@Test
void testSumInt(){
Integer res = Integer.valueOf(methodService.doSum(5, 5, "int"));
Assertions.assertEquals(10, res);
}
@Test
void testSumBool(){
Boolean res = Boolean.valueOf(methodService.doSum(true, true, "boolean"));
Assertions.assertEquals(true, res);
}
//Sub
@Test
void testSubStr(){
String res = methodService.doSub("hello", 1, "string");
Assertions.assertEquals("hell", res);
}
@Test
void testSubStr2(){
Assertions.assertThrows(NumberFormatException.class, () -> methodService.doSub("hello", 2, "int"));
}
@Test
void testSubInt(){
Integer res = Integer.valueOf(methodService.doSub(5, 2, "int"));
Assertions.assertEquals(3, res);
}
@Test
void testSubBool(){
Boolean res = Boolean.valueOf(methodService.doSub(true, 0, "boolean"));
Assertions.assertEquals(false, res);
}
//Mul
@Test
void testMulStr(){
String res = methodService.doMul("hello", 2, "string");
Assertions.assertEquals(" hellohello", res);
}
@Test
void testMulInt(){
Integer res = Integer.valueOf(methodService.doMul(5, 2, "int"));
Assertions.assertEquals(10, res);
}
@Test
void testMulBool(){
Boolean res = Boolean.valueOf(methodService.doMul(true, 0, "boolean"));
Assertions.assertEquals(false, res);
}
//Del
@Test
void testDelStr(){
String res = methodService.doDel("hello0", 2, "string");
Assertions.assertEquals("hel", res);
}
@Test
void testDelInt(){
Integer res = Integer.valueOf(methodService.doDel(6, 2, "int"));
Assertions.assertEquals(3, res);
}
@Test
void testDelBool(){
Boolean res = Boolean.valueOf(methodService.doDel(true, 2, "boolean"));
Assertions.assertEquals(false, res);
}
} }

View File

@ -0,0 +1,72 @@
package ru.ulstu.is.myapp;
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 ru.ulstu.is.myapp.models.Product;
import ru.ulstu.is.myapp.models.Purchase;
import ru.ulstu.is.myapp.service.ProductService;
import ru.ulstu.is.myapp.service.PurchaseService;
import java.util.Date;
import java.util.List;
@SpringBootTest
public class ProductTests {
@Autowired
private ProductService productService;
@Test
public void testAddCustomer() {
productService.deleteAllProducts();
Product p = productService.addProduct("dgdf", 4567.00, "gfgf");
Assertions.assertNotNull(productService.findProduct(p.getId()));
productService.deleteAllProducts();
}
@Test
public void testUpdatePurchase() {
productService.deleteAllProducts();
Product p = productService.addProduct("dgdf", 4567.00, "gfgf");
productService.updateProduct(p.getId(),"dgdf", 4567.00, "gfgf");
Assertions.assertNotNull(productService.findProduct(p.getId()));
productService.deleteAllProducts();
}
@Test
public void testDeleteCustomer() {
productService.deleteAllProducts();
Product p = productService.addProduct("dgdf", 4567.00, "gfgf");
productService.deleteProduct(p.getId());
Assertions.assertThrows(EntityNotFoundException.class, () -> {productService.findProduct(p.getId());});
}
@Test
void testPurchaseRead() {
productService.deleteAllProducts();
final Product product = productService.addProduct("dgdf", 4567.00, "gfgf");
final Product findProduct= productService.findProduct(product.getId());
Assertions.assertEquals(product, findProduct);
}
@Test
void testPurchaseReadNotFound() {
productService.deleteAllProducts();
Assertions.assertThrows(EntityNotFoundException.class, () -> productService.findProduct(1L));
}
@Test
void testPurchaseReadAll() {
productService.deleteAllProducts();
productService.addProduct("dgdf", 4567.00, "gfgf");
productService.addProduct("dgdf", 4567.00, "gfgf");
final List<Product> purchases = productService.findAllProducts();
Assertions.assertEquals(purchases.size(), 2);
}
@Test
void testPurchaseReadAllEmpty() {
productService.deleteAllProducts();
final List<Product> products = productService.findAllProducts();
Assertions.assertEquals(products.size(), 0);
}
}

View File

@ -0,0 +1,78 @@
package ru.ulstu.is.myapp;
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 ru.ulstu.is.myapp.models.Customer;
import ru.ulstu.is.myapp.models.Purchase;
import ru.ulstu.is.myapp.service.CustomerService;
import ru.ulstu.is.myapp.service.PurchaseService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Date;
import java.util.List;
@SpringBootTest
public class PurchaseTests {
private static final Logger log = LoggerFactory.getLogger(PurchaseTests.class);
@Autowired
private PurchaseService purchaseService;
@Test
public void testAddCustomer() {
purchaseService.deleteAllPurchases();
Purchase p = purchaseService.addPurchase(new Date(1212121212121L), 4356.00);
Assertions.assertNotNull(purchaseService.findPurchase(p.getId()));
purchaseService.deleteAllPurchases();
}
@Test
public void testUpdatePurchase() {
purchaseService.deleteAllPurchases();
Purchase p = purchaseService.addPurchase(new Date(1212121212121L), 4356.00);
purchaseService.updatePurchase(p.getId(), new Date(1212121212121L), 4356.00);
Assertions.assertNotNull(purchaseService.findPurchase(p.getId()));
purchaseService.deleteAllPurchases();
}
@Test
public void testDeleteCustomer() {
purchaseService.deleteAllPurchases();
Purchase p = purchaseService.addPurchase(new Date(1212121212121L), 4356.00);
purchaseService.deletePurchase(p.getId());
Assertions.assertThrows(EntityNotFoundException.class, () -> {purchaseService.findPurchase(p.getId());});
}
@Test
void testPurchaseRead() {
purchaseService.deleteAllPurchases();
final Purchase purchase = purchaseService.addPurchase(new Date(1212121212121L), 4356.00);
final Purchase findPurchase = purchaseService.findPurchase(purchase.getId());
Assertions.assertEquals(purchase, findPurchase);
}
@Test
void testPurchaseReadNotFound() {
purchaseService.deleteAllPurchases();
Assertions.assertThrows(EntityNotFoundException.class, () -> purchaseService.findPurchase(1L));
}
@Test
void testPurchaseReadAll() {
purchaseService.deleteAllPurchases();
purchaseService.addPurchase(new Date(1212121212121L), 4356.00);
purchaseService.addPurchase(new Date(1212124212221L), 4356.00);
final List<Purchase> purchases = purchaseService.findAllPurchases();
log.info(purchases.toString());
Assertions.assertEquals(purchases.size(), 2);
}
@Test
void testPurchaseReadAllEmpty() {
purchaseService.deleteAllPurchases();
final List<Purchase> students = purchaseService.findAllPurchases();
Assertions.assertEquals(students.size(), 0);
}
}