LabWork04: Работа готова

This commit is contained in:
Safgerd 2023-04-18 01:45:35 +04:00
parent a243920d42
commit 5ec74ef311
27 changed files with 488 additions and 481 deletions

View File

@ -18,6 +18,8 @@ dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'com.h2database:h2:2.1.210'
implementation group: 'org.springdoc', name: 'springdoc-openapi-ui', version: '1.6.5'
implementation 'org.hibernate.validator:hibernate-validator'
implementation 'org.springdoc:springdoc-openapi-ui:1.6.5'
}
tasks.named('test') {

View File

@ -1,64 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<title>Calc</title>
<link rel="stylesheet" href="https://unpkg.com/chota@latest">
</head>
<body>
<div class="container" style="max-width:600px">
<div class="card row is-full-screen is-center">
<div class="col">
<div class="row">
<div class="col">
<input type="text" id="val1">
</div>
<div class="col">
<select id="operation">
<option value="sum" selected>+</option>
<option value="sub">-</option>
<option value="mul">*</option>
<option value="div">/</option>
</select>
</div>
<div class="col">
<input type="text" id="val2">
</div>
</div>
<div class="row">
<div class="col">
<button type="button" id="get-int-result" onclick="calculate('inttype')">Result for int</button>
</div>
<div class="col is-right">
<button type="button" id="get-string-result" onclick="calculate('stringtype')">Result for string</button>
</div>
</div>
<div class="card row is-center">
<h5 class="is-center" id="result"></h5>
</div>
</div>
</div>
</div>
<script>
async function calculate(resulttype) {
const val1 = document.getElementById("val1").value
const val2 = document.getElementById("val2").value
const op = document.getElementById("operation").value
if (op == 'sum') {
document.getElementById("result").innerHTML = await (await fetch(`http://127.0.0.1:8080/sum?val1=${val1}&val2=${val2}&type=${resulttype}`)).text()
} else if (op == 'sub') {
document.getElementById("result").innerHTML = await (await fetch(`http://127.0.0.1:8080/sub?val1=${val1}&val2=${val2}&type=${resulttype}`)).text()
} else if (op == 'mul') {
document.getElementById("result").innerHTML = await (await fetch(`http://127.0.0.1:8080/mul?val1=${val1}&val2=${val2}&type=${resulttype}`)).text()
} else {
document.getElementById("result").innerHTML = await (await fetch(`http://127.0.0.1:8080/div?val1=${val1}&val2=${val2}&type=${resulttype}`)).text()
}
}
</script>
</body>
</html>

View File

@ -1,12 +0,0 @@
const fs = require('fs')
const http = require('http')
const requestListener = async function (req, res) {
res.writeHead(200);
fs.readFile('index.html', (err, data) => {
res.end(data);
});
};
const server = http.createServer(requestListener)
server.listen(5050)

9
frontend/node_modules/fs/README.md generated vendored
View File

@ -1,9 +0,0 @@
# Security holding package
This package name is not currently in use, but was formerly occupied
by another package. To avoid malicious use, npm is hanging on to the
package name, but loosely, and we'll probably give it to you if you
want it.
You may adopt this package by contacting support@npmjs.com and
requesting the name.

View File

@ -1,46 +0,0 @@
{
"_from": "fs",
"_id": "fs@0.0.1-security",
"_inBundle": false,
"_integrity": "sha512-3XY9e1pP0CVEUCdj5BmfIZxRBTSDycnbqhIOGec9QYtmVH2fbLpj86CFWkrNOkt/Fvty4KZG5lTglL9j/gJ87w==",
"_location": "/fs",
"_phantomChildren": {},
"_requested": {
"type": "tag",
"registry": true,
"raw": "fs",
"name": "fs",
"escapedName": "fs",
"rawSpec": "",
"saveSpec": null,
"fetchSpec": "latest"
},
"_requiredBy": [
"#USER",
"/"
],
"_resolved": "https://registry.npmjs.org/fs/-/fs-0.0.1-security.tgz",
"_shasum": "8a7bd37186b6dddf3813f23858b57ecaaf5e41d4",
"_spec": "fs",
"_where": "C:\\Users\\user\\Desktop\\something\\frontend",
"author": "",
"bugs": {
"url": "https://github.com/npm/security-holder/issues"
},
"bundleDependencies": false,
"deprecated": false,
"description": "This package name is not currently in use, but was formerly occupied by another package. To avoid malicious use, npm is hanging on to the package name, but loosely, and we'll probably give it to you if you want it.",
"homepage": "https://github.com/npm/security-holder#readme",
"keywords": [],
"license": "ISC",
"main": "index.js",
"name": "fs",
"repository": {
"type": "git",
"url": "git+https://github.com/npm/security-holder.git"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"version": "0.0.1-security"
}

View File

@ -1,9 +0,0 @@
# Security holding package
This package name is not currently in use, but was formerly occupied
by another package. To avoid malicious use, npm is hanging on to the
package name, but loosely, and we'll probably give it to you if you
want it.
You may adopt this package by contacting support@npmjs.com and
requesting the name.

View File

@ -1,39 +0,0 @@
{
"_from": "http",
"_id": "http@0.0.1-security",
"_inBundle": false,
"_integrity": "sha512-RnDvP10Ty9FxqOtPZuxtebw1j4L/WiqNMDtuc1YMH1XQm5TgDRaR1G9u8upL6KD1bXHSp9eSXo/ED+8Q7FAr+g==",
"_location": "/http",
"_phantomChildren": {},
"_requested": {
"type": "tag",
"registry": true,
"raw": "http",
"name": "http",
"escapedName": "http",
"rawSpec": "",
"saveSpec": null,
"fetchSpec": "latest"
},
"_requiredBy": [
"#USER",
"/"
],
"_resolved": "https://registry.npmjs.org/http/-/http-0.0.1-security.tgz",
"_shasum": "3aac09129d12dc2747bbce4157afde20ad1f7995",
"_spec": "http",
"_where": "C:\\Users\\user\\Desktop\\something\\frontend",
"bugs": {
"url": "https://github.com/npm/security-holder/issues"
},
"bundleDependencies": false,
"deprecated": false,
"description": "security holding package",
"homepage": "https://github.com/npm/security-holder#readme",
"name": "http",
"repository": {
"type": "git",
"url": "git+https://github.com/npm/security-holder.git"
},
"version": "0.0.1-security"
}

View File

@ -1,18 +0,0 @@
{
"name": "frontend",
"version": "1.0.0",
"lockfileVersion": 1,
"requires": true,
"dependencies": {
"fs": {
"version": "0.0.1-security",
"resolved": "https://registry.npmjs.org/fs/-/fs-0.0.1-security.tgz",
"integrity": "sha512-3XY9e1pP0CVEUCdj5BmfIZxRBTSDycnbqhIOGec9QYtmVH2fbLpj86CFWkrNOkt/Fvty4KZG5lTglL9j/gJ87w=="
},
"http": {
"version": "0.0.1-security",
"resolved": "https://registry.npmjs.org/http/-/http-0.0.1-security.tgz",
"integrity": "sha512-RnDvP10Ty9FxqOtPZuxtebw1j4L/WiqNMDtuc1YMH1XQm5TgDRaR1G9u8upL6KD1bXHSp9eSXo/ED+8Q7FAr+g=="
}
}
}

View File

@ -1,15 +0,0 @@
{
"name": "frontend",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev": "node index.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"fs": "0.0.1-security",
"http": "0.0.1-security"
}
}

View File

@ -0,0 +1,38 @@
package ru.ulstu.is.labwork.Lab4.DTO;
import ru.ulstu.is.labwork.Lab4.model.Comment;
public class CommentDto {
public final Long id;
public final String content;
public final String customerName;
public final String postTitle;
public final String postAuthor;
public final long postAuthorId;
public CommentDto(Comment comment) {
this.id = comment.getId();
this.content = comment.getContent();
this.customerName = comment.getCustomer().getUsername();
this.postTitle = comment.getPost().getTitle();
this.postAuthor = comment.getPost().getCustomer().getUsername();
this.postAuthorId = comment.getPost().getCustomer().getId();
}
public long getId() {
return id;
}
public String getContent() {
return content;
}
public String getCustomerName() {
return customerName;
}
public String getPostTitle() {return postTitle;}
public String getPostAuthor() {
return postAuthor;
}
public long getPostAuthorId() {
return postAuthorId;
}
}

View File

@ -0,0 +1,30 @@
package ru.ulstu.is.labwork.Lab4.DTO;
import ru.ulstu.is.labwork.Lab4.model.Comment;
import ru.ulstu.is.labwork.Lab4.model.Customer;
import ru.ulstu.is.labwork.Lab4.model.Post;
import java.util.ArrayList;
import java.util.List;
public class CustomerDto {
public final Long id;
public final String username;
public final String password;
public final List<CommentDto> comments;
public final List<PostDto> posts;
public CustomerDto(Customer customer){
this.id = customer.getId();
this.username = customer.getUsername();
this.password = customer.getPassword();
this.comments = customer.getComments().stream().map(CommentDto::new).toList();
this.posts = customer.getPosts().stream().map(PostDto::new).toList();
}
public Long getId() {return id;}
public String getUsername() {return username;}
public String getPassword() {return password;}
public List<CommentDto> getComments() {return comments;}
public List<PostDto> getPosts() {return posts;}
}

View File

@ -0,0 +1,36 @@
package ru.ulstu.is.labwork.Lab4.DTO;
import ru.ulstu.is.labwork.Lab4.model.Comment;
import ru.ulstu.is.labwork.Lab4.model.Post;
import java.util.ArrayList;
import java.util.List;
public class PostDto {
public final Long id;
public final String title;
public final String content;
public final String customerName;
public final long customerId;
public final List<CommentDto> comments;
public PostDto(Post post){
this.id = post.getId();
this.title = post.getTitle();
this.content = post.getContent();
this.customerName = post.getCustomer().getUsername();
this.customerId = post.getCustomer().getId();
this.comments = post.getComments().stream().map(CommentDto::new).toList();
}
public Long getId() { return id; }
public String getTitle() { return title; }
public String getContent() { return content; }
public String getCustomerName() {
return customerName;
}
public List<CommentDto> getComments() { return comments; }
public long getCustomerId() {
return customerId;
}
}

View File

@ -0,0 +1,56 @@
package ru.ulstu.is.labwork.Lab4.controller;
import org.springframework.web.bind.annotation.*;
import ru.ulstu.is.labwork.Lab4.DTO.CommentDto;
import ru.ulstu.is.labwork.Lab4.model.Comment;
import ru.ulstu.is.labwork.Lab4.services.CommentService;
import ru.ulstu.is.labwork.Lab4.services.CustomerService;
import ru.ulstu.is.labwork.Lab4.services.PostService;
import java.util.List;
@RestController
@RequestMapping("/comment")
public class CommentController {
private final CommentService commentService;
private final CustomerService customerService;
private final PostService postService;
public CommentController(CommentService commentService, CustomerService customerService, PostService postService) {
this.commentService = commentService;
this.customerService = customerService;
this.postService = postService;
}
@GetMapping("/{id}")
public CommentDto getComment(@PathVariable Long id) {
return new CommentDto(commentService.findComment(id));
}
@GetMapping
public List<CommentDto> getComments() {
return commentService.findAllComments().stream()
.map(CommentDto::new)
.toList();
}
@PostMapping
public CommentDto createComment(@RequestParam("text") String text, @RequestParam("ownerId") Long ownerId, @RequestParam("postId") Long postId){
final Comment comment = commentService.addComment(customerService.findCustomer(ownerId), postService.findPost(postId), text);
return new CommentDto(comment);
}
@PutMapping("/{id}")
public CommentDto updateComment(@RequestParam("text") String text, @PathVariable Long id) {
return new CommentDto(commentService.updateComment(id, text));
}
@DeleteMapping("/{id}")
public CommentDto deleteComment(@PathVariable Long id) {
return new CommentDto(commentService.deleteComment(id));
}
@DeleteMapping
public void deleteAllComments(){
commentService.deleteAllComments();
}
}

View File

@ -0,0 +1,51 @@
package ru.ulstu.is.labwork.Lab4.controller;
import org.springframework.web.bind.annotation.*;
import ru.ulstu.is.labwork.Lab4.DTO.CustomerDto;
import ru.ulstu.is.labwork.Lab4.model.Customer;
import ru.ulstu.is.labwork.Lab4.services.CustomerService;
import java.util.List;
@RestController
@RequestMapping("/customer")
public class CustomerController {
private final CustomerService customerService;
public CustomerController(CustomerService customerService) {
this.customerService = customerService;
}
@GetMapping("/{id}")
public CustomerDto getCustomer(@PathVariable Long id) {
return new CustomerDto(customerService.findCustomer(id));
}
@GetMapping
public List<CustomerDto> getCustomers() {
return customerService.findAllCustomers().stream()
.map(CustomerDto::new)
.toList();
}
@PostMapping
public CustomerDto createCustomer(@RequestParam("username") String username, @RequestParam("password") String password){
final Customer customer = customerService.addCustomer(username, password);
return new CustomerDto(customer);
}
@PutMapping("/{id}")
public CustomerDto updateCustomer(@RequestParam("username") String username, @RequestParam("password") String password, @PathVariable Long id) {
return new CustomerDto(customerService.updateCustomer(id, username, password));
}
@DeleteMapping("/{id}")
public CustomerDto deleteCustomer(@PathVariable Long id) {
return new CustomerDto(customerService.deleteCustomer(id));
}
@DeleteMapping
public void deleteAllCustomers(){
customerService.deleteAllCustomers();
}
}

View File

@ -0,0 +1,62 @@
package ru.ulstu.is.labwork.Lab4.controller;
import org.springframework.web.bind.annotation.*;
import ru.ulstu.is.labwork.Lab4.DTO.PostDto;
import ru.ulstu.is.labwork.Lab4.services.CustomerService;
import ru.ulstu.is.labwork.Lab4.services.PostService;
import java.util.List;
@RestController
@RequestMapping("/post")
public class PostController {
private final PostService postService;
private final CustomerService customerService;
public PostController(PostService postService, CustomerService customerService) {
this.postService = postService;
this.customerService = customerService;
}
@GetMapping("/{id}")
public PostDto getPost(@PathVariable Long id) {
return new PostDto(postService.findPost(id));
}
@GetMapping
public List<PostDto> getPosts() {
return postService.findAllPosts().stream()
.map(PostDto::new)
.toList();
}
@PostMapping
public PostDto createPost(
@RequestParam("title") String title,
@RequestParam("content") String content,
@RequestParam("authorId") Long authorId
)
{
return new PostDto(postService.addPost(customerService.findCustomer(authorId), title, content));
}
@PutMapping("/{id}")
public PostDto updatePost(
@PathVariable Long id,
@RequestParam("title") String title,
@RequestParam("content") String content
)
{
return new PostDto(postService.updatePost(id, title, content));
}
@DeleteMapping("/{id}")
public PostDto deletePost (@PathVariable Long id) {
return new PostDto(postService.deletePost(id));
}
@DeleteMapping
public void deleteAllPosts() {
postService.deleteAllPosts();
}
}

View File

@ -1,4 +1,5 @@
package ru.ulstu.is.labwork.dbLab3.model;
package ru.ulstu.is.labwork.Lab4.model;
import jakarta.persistence.*;
import java.util.Objects;

View File

@ -1,4 +1,5 @@
package ru.ulstu.is.labwork.dbLab3.model;
package ru.ulstu.is.labwork.Lab4.model;
import jakarta.persistence.*;
import java.util.*;
@ -10,7 +11,7 @@ public class Customer {
@Column
private String username;
@Column
private String hashedPassword;
private String password;
@OneToMany(fetch = FetchType.EAGER, mappedBy = "customer", cascade = CascadeType.ALL)
private List<Comment> comments;
@OneToMany(fetch = FetchType.EAGER, mappedBy = "customer", cascade = CascadeType.ALL)
@ -20,9 +21,9 @@ public class Customer {
}
public Customer(String username, String hashedPassword) {
public Customer(String username, String password) {
this.username = username;
this.hashedPassword = hashedPassword;
this.password = password;
this.comments = new ArrayList<>();
this.posts = new ArrayList<>();
}
@ -35,8 +36,8 @@ public class Customer {
return username;
}
public String getHashedPassword() {
return hashedPassword;
public String getPassword() {
return password;
}
public List<Comment> getComments() {
@ -51,8 +52,8 @@ public class Customer {
this.username = username;
}
public void setHashedPassword(String hashedPassword) {
this.hashedPassword = hashedPassword;
public void setPassword(String password) {
this.password = password;
}
@Override

View File

@ -1,4 +1,5 @@
package ru.ulstu.is.labwork.dbLab3.model;
package ru.ulstu.is.labwork.Lab4.model;
import jakarta.persistence.*;
import java.util.ArrayList;
import java.util.List;

View File

@ -0,0 +1,7 @@
package ru.ulstu.is.labwork.Lab4.repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import ru.ulstu.is.labwork.Lab4.model.Comment;
public interface CommentRepository extends JpaRepository<Comment, Long> {
}

View File

@ -0,0 +1,7 @@
package ru.ulstu.is.labwork.Lab4.repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import ru.ulstu.is.labwork.Lab4.model.Customer;
public interface CustomerRepository extends JpaRepository<Customer, Long> {
}

View File

@ -0,0 +1,7 @@
package ru.ulstu.is.labwork.Lab4.repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import ru.ulstu.is.labwork.Lab4.model.Post;
public interface PostRepository extends JpaRepository<Post, Long> {
}

View File

@ -1,34 +1,33 @@
package ru.ulstu.is.labwork.dbLab3.service;
import jakarta.persistence.EntityManager;
package ru.ulstu.is.labwork.Lab4.services;
import jakarta.persistence.EntityNotFoundException;
import jakarta.persistence.PersistenceContext;
import jakarta.transaction.Transactional;
import ru.ulstu.is.labwork.dbLab3.model.Comment;
import ru.ulstu.is.labwork.dbLab3.model.Customer;
import ru.ulstu.is.labwork.dbLab3.model.Post;
import ru.ulstu.is.labwork.Lab4.model.Comment;
import ru.ulstu.is.labwork.Lab4.model.Customer;
import ru.ulstu.is.labwork.Lab4.model.Post;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import ru.ulstu.is.labwork.Lab4.repositories.CommentRepository;
import java.util.List;
import java.util.Optional;
@Service
public class CommentService {
@PersistenceContext
private EntityManager em;
private final CommentRepository commentRepository;
public CommentService(CommentRepository commentRepository) {
this.commentRepository = commentRepository;
}
@Transactional
public Comment findComment(Long id) {
final Comment comment = em.find(Comment.class, id);
if (comment == null) {
throw new EntityNotFoundException(String.format("Comment with id [%s] is not found", id));
}
return comment;
final Optional<Comment> comment = commentRepository.findById(id);
return comment.orElseThrow(EntityNotFoundException::new);
}
@Transactional
public List<Comment> findAllComments() {
return em.createQuery("select c from Comment c", Comment.class).getResultList();
return commentRepository.findAll();
}
@Transactional
@ -39,11 +38,11 @@ public class CommentService {
if (!StringUtils.hasText(content)) {
throw new IllegalArgumentException("Invalid comment's content");
}
final Comment comment = new Comment(customer, post, content);
comment.getCustomer().getComments().add(comment);
comment.getPost().getComments().add(comment);
em.persist(comment);
return comment;
customer.getComments().add(comment);
post.getComments().add(comment);
return commentRepository.save(comment);
}
@Transactional
@ -51,22 +50,23 @@ public class CommentService {
if (!StringUtils.hasText(content)) {
throw new IllegalArgumentException("Comment's content is empty");
}
final Comment comment = findComment(id);
comment.setContent(content);
return em.merge(comment);
final Comment currentComment = findComment(id);
currentComment.setContent(content);
return commentRepository.save(currentComment);
}
@Transactional
public Comment deleteComment(Long id) {
final Comment currentComment = findComment(id);
commentRepository.delete(currentComment);
currentComment.getPost().getComments().remove(currentComment);
currentComment.getCustomer().getComments().remove(currentComment);
em.remove(currentComment);
return currentComment;
}
@Transactional
public void deleteAllComment() {
em.createQuery("delete from Comment").executeUpdate();
public void deleteAllComments() {
commentRepository.deleteAll();
}
}

View File

@ -1,30 +1,31 @@
package ru.ulstu.is.labwork.dbLab3.service;
import jakarta.persistence.EntityManager;
package ru.ulstu.is.labwork.Lab4.services;
import jakarta.persistence.EntityNotFoundException;
import jakarta.persistence.PersistenceContext;
import jakarta.transaction.Transactional;
import ru.ulstu.is.labwork.dbLab3.model.Customer;
import ru.ulstu.is.labwork.Lab4.model.Customer;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import ru.ulstu.is.labwork.Lab4.repositories.CustomerRepository;
import java.util.List;
import java.util.Optional;
@Service
public class CustomerService {
@PersistenceContext
private EntityManager em;
private final CustomerRepository customerRepository;
public CustomerService(CustomerRepository customerRepository) {
this.customerRepository = customerRepository;
}
@Transactional
public Customer findCustomer(Long id) {
final Customer customer = em.find(Customer.class, id);
if (customer == null) {
throw new EntityNotFoundException(String.format("User with id [%s] is not found", id));
}
return customer;
final Optional<Customer> customer = customerRepository.findById(id);
return customer.orElseThrow(EntityNotFoundException::new);
}
@Transactional
public List<Customer> findAllCustomers() {
return em.createQuery("select c from Customer c", Customer.class).getResultList();
return customerRepository.findAll();
}
@Transactional
@ -32,9 +33,8 @@ public class CustomerService {
if (!StringUtils.hasText(username) || !StringUtils.hasText(password)) {
throw new IllegalArgumentException("Customer's username or password is empty");
}
final Customer customer = new Customer(username, password);
em.persist(customer);
return customer;
Customer customer = new Customer(username, password);
return customerRepository.save(customer);
}
@Transactional
@ -42,21 +42,21 @@ public class CustomerService {
if (!StringUtils.hasText(username) || !StringUtils.hasText(password)) {
throw new IllegalArgumentException("Customer's username or password is empty");
}
final Customer customer = findCustomer(id);
Customer customer = findCustomer(id);
customer.setUsername(username);
customer.setHashedPassword(password);
return em.merge(customer);
customer.setPassword(password);
return customerRepository.save(customer);
}
@Transactional
public Customer deleteCustomer(Long id) {
final Customer currentCustomer = findCustomer(id);
em.remove(currentCustomer);
return currentCustomer;
Customer customer = findCustomer(id);
customerRepository.delete(customer);
return customer;
}
@Transactional
public void deleteAllCustomers() {
em.createQuery("delete from Customer").executeUpdate();
customerRepository.deleteAll();
}
}

View File

@ -1,34 +1,33 @@
package ru.ulstu.is.labwork.dbLab3.service;
package ru.ulstu.is.labwork.Lab4.services;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityNotFoundException;
import jakarta.persistence.PersistenceContext;
import jakarta.transaction.Transactional;
import ru.ulstu.is.labwork.dbLab3.model.Comment;
import ru.ulstu.is.labwork.dbLab3.model.Customer;
import ru.ulstu.is.labwork.dbLab3.model.Post;
import ru.ulstu.is.labwork.Lab4.model.Customer;
import ru.ulstu.is.labwork.Lab4.model.Post;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import ru.ulstu.is.labwork.Lab4.repositories.PostRepository;
import java.util.List;
import java.util.Optional;
@Service
public class PostService {
@PersistenceContext
private EntityManager em;
private final PostRepository postRepository;
public PostService(PostRepository postRepository) {
this.postRepository = postRepository;
}
@Transactional
public Post findPost(Long id) {
final Post post = em.find(Post.class, id);
if (post == null) {
throw new EntityNotFoundException(String.format("Post with id [%s] is not found", id));
}
return post;
final Optional<Post> post = postRepository.findById(id);
return post.orElseThrow(EntityNotFoundException::new);
}
@Transactional
public List<Post> findAllPosts() {
return em.createQuery("select p from Post p", Post.class).getResultList();
return postRepository.findAll();
}
@Transactional
@ -39,10 +38,9 @@ public class PostService {
if (!StringUtils.hasText(title) | !StringUtils.hasText(content)) {
throw new IllegalArgumentException("Invalid post's content or title");
}
final Post post = new Post(customer, title, content);
post.getCustomer().getPosts().add(post);
em.persist(post);
return post;
Post post = new Post(customer, title, content);
customer.getPosts().add(post);
return postRepository.save(post);
}
@Transactional
@ -50,22 +48,22 @@ public class PostService {
if (!StringUtils.hasText(content) | !StringUtils.hasText(title)) {
throw new IllegalArgumentException("Post's content or title is empty");
}
final Post post = findPost(id);
Post post = findPost(id);
post.setTitle(title);
post.setContent(content);
return em.merge(post);
return postRepository.save(post);
}
@Transactional
public Post deletePost(Long id) {
final Post currentPost = findPost(id);
currentPost.getCustomer().getPosts().remove(currentPost);
em.remove(currentPost);
return currentPost;
Post post = findPost(id);
post.getCustomer().getPosts().remove(post);
postRepository.delete(post);
return post;
}
@Transactional
public void deleteAllPosts() {
em.createQuery("delete from Post").executeUpdate();
postRepository.deleteAll();
}
}

View File

@ -2,14 +2,10 @@ package ru.ulstu.is.labwork;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
//@RequestMapping("/lab1")
public class LabworkApplication {
public static void main(String[] args) {
SpringApplication.run(LabworkApplication.class, args);

View File

@ -1,67 +0,0 @@
package ru.ulstu.is.labwork.dbLab3.AdditionalTask;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import jakarta.transaction.Transactional;
import ru.ulstu.is.labwork.dbLab3.model.Comment;
import ru.ulstu.is.labwork.dbLab3.model.Post;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
@Service
public class SearchService {
@PersistenceContext
private EntityManager em;
@Transactional
public List<Object> finder(String searchWord){
List<Post> postResult = em.createQuery("SELECT p FROM Post p WHERE p.content LIKE :word", Post.class)
.setParameter("word", searchWord)
.getResultList();
List<Comment> commentResult = em.createQuery("SELECT c FROM Comment c WHERE c.content LIKE :word", Comment.class)
.setParameter("word", searchWord)
.getResultList();
List<Object> result = new ArrayList<>();
result.addAll(postResult);
result.addAll(commentResult);
return result;
}
}
//
// @Autowired
// SearchService searchService;
//
// @Test
// void testFinder(){
// commentService.deleteAllComment();
// postService.deleteAllPosts();
// customerService.deleteAllCustomers();
//
// Customer c1 = customerService.addCustomer("first", "1");
// Customer c2 = customerService.addCustomer("second", "2");
// Customer c3 = customerService.addCustomer("third", "3");
//
// Post p1 = postService.addPost(c1, "first title", "nonsense");
// Post p2 = postService.addPost(c2, "second title", "ordinal");
// Post p3 = postService.addPost(c3, "third title", "searchword");
//
// Comment com1 = commentService.addComment(c1, p2, "What");
// Comment com2 = commentService.addComment(c2, p3, "searchword");
// Comment com3 = commentService.addComment(c3, p1, "How");
//
// List<Object> expectedResult = new ArrayList<>();
// expectedResult.add((Object)p3);
// expectedResult.add((Object)com2);
//
// List<Object> actualResult = searchService.finder("searchword");
//
// Assertions.assertEquals(expectedResult.size(),actualResult.size());
//
// Assertions.assertEquals(expectedResult.get(0),actualResult.get(0));
// Assertions.assertEquals(expectedResult.get(1),actualResult.get(1));
// }

View File

@ -1,125 +1,118 @@
package ru.ulstu.is.labwork;
import ru.ulstu.is.labwork.dbLab3.model.*;
import ru.ulstu.is.labwork.dbLab3.service.CommentService;
import ru.ulstu.is.labwork.dbLab3.service.CustomerService;
import ru.ulstu.is.labwork.dbLab3.service.PostService;
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;
@SpringBootTest
class LabworkApplicationTests {
@Autowired
CustomerService customerService;
@Autowired
CommentService commentService;
@Autowired
PostService postService;
@Test
void testCustomers() {
commentService.deleteAllComment();
postService.deleteAllPosts();
customerService.deleteAllCustomers();
Customer c1 = customerService.addCustomer("first", "1");
Customer c2 = customerService.addCustomer("second", "2");
Customer c3 = customerService.addCustomer("third", "3");
Assertions.assertEquals("first", c1.getUsername());
Assertions.assertEquals("second", c2.getUsername());
Assertions.assertEquals("third", c3.getUsername());
Assertions.assertEquals(c1, customerService.findCustomer(c1.getId()));
customerService.deleteCustomer(c2.getId());
Assertions.assertEquals(2, customerService.findAllCustomers().size());
Customer c4 = customerService.updateCustomer(c3.getId(), "fourth", "4");
Assertions.assertNotEquals(c3.getUsername(), c4.getUsername());
Assertions.assertNotEquals(c3.getHashedPassword(), c4.getHashedPassword());
commentService.deleteAllComment();
postService.deleteAllPosts();
customerService.deleteAllCustomers();
}
@Test
void testPost() {
commentService.deleteAllComment();
postService.deleteAllPosts();
customerService.deleteAllCustomers();
Customer c1 = customerService.addCustomer("first", "1");
Customer c2 = customerService.addCustomer("second", "2");
Post p1 = postService.addPost(c1, "first title", "nonsense");
Post p2 = postService.addPost(c2, "second title", "ordinal");
Assertions.assertEquals(2, postService.findAllPosts().size());
Assertions.assertEquals(p1.getCustomer(), c1);
Assertions.assertEquals(p2.getCustomer(), c2);
Assertions.assertEquals(c1.getPosts().get(0), p1);
Assertions.assertEquals(c2.getPosts().get(0), p2);
Assertions.assertEquals(p1, postService.findPost(p1.getId()));
Assertions.assertEquals(p2, postService.findPost(p2.getId()));
Post p3 = postService.addPost(c1, "asdf", "asd");
postService.deletePost(p1.getId());
Assertions.assertEquals(1, customerService.findCustomer(c1.getId()).getPosts().size());
Post p4 = postService.updatePost(p2.getId(), "third title", "wow");
Assertions.assertNotEquals(p2.getTitle(), p4.getTitle());
Assertions.assertNotEquals(p2.getContent(), p4.getContent());
commentService.deleteAllComment();
postService.deleteAllPosts();
customerService.deleteAllCustomers();
}
@Test
void testComment() {
commentService.deleteAllComment();
postService.deleteAllPosts();
customerService.deleteAllCustomers();
Customer c1 = customerService.addCustomer("first", "1");
Customer c2 = customerService.addCustomer("second", "2");
Post p1 = postService.addPost(c1, "first title", "nonsense");
Post p2 = postService.addPost(c2, "second title", "ordinal");
Assertions.assertEquals(2, postService.findAllPosts().size());
Comment com1 = commentService.addComment(c1, p2, "What");
Comment com2 = commentService.addComment(c2, p1, "How");
Assertions.assertEquals(c1, p2.getComments().get(0).getCustomer());
Assertions.assertEquals(c2, p1.getComments().get(0).getCustomer());
Comment com3 = commentService.addComment(c1, p1, "Really");
Assertions.assertEquals(com2, commentService.findComment(p1.getComments().get(0).getId()));
Comment com4 = commentService.updateComment(com3.getId(), "Not really");
Assertions.assertNotEquals(com3.getContent(), com4.getContent());
Assertions.assertEquals(com3.getCustomer().getId(), com4.getCustomer().getId());
commentService.deleteAllComment();
postService.deleteAllPosts();
customerService.deleteAllCustomers();
}
// @Autowired
// CustomerService customerService;
//
// @Autowired
// CommentService commentService;
//
// @Autowired
// PostService postService;
//
// @Test
// void testCustomers() {
// commentService.deleteAllComment();
// postService.deleteAllPosts();
// customerService.deleteAllCustomers();
//
// Customer c1 = customerService.addCustomer("first", "1");
// Customer c2 = customerService.addCustomer("second", "2");
// Customer c3 = customerService.addCustomer("third", "3");
//
// Assertions.assertEquals("first", c1.getUsername());
// Assertions.assertEquals("second", c2.getUsername());
// Assertions.assertEquals("third", c3.getUsername());
//
// Assertions.assertEquals(c1, customerService.findCustomer(c1.getId()));
//
// customerService.deleteCustomer(c2.getId());
//
// Assertions.assertEquals(2, customerService.findAllCustomers().size());
//
// Customer c4 = customerService.updateCustomer(c3.getId(), "fourth", "4");
//
// Assertions.assertNotEquals(c3.getUsername(), c4.getUsername());
// Assertions.assertNotEquals(c3.getHashedPassword(), c4.getHashedPassword());
//
// commentService.deleteAllComment();
// postService.deleteAllPosts();
// customerService.deleteAllCustomers();
// }
//
// @Test
// void testPost() {
// commentService.deleteAllComment();
// postService.deleteAllPosts();
// customerService.deleteAllCustomers();
//
// Customer c1 = customerService.addCustomer("first", "1");
// Customer c2 = customerService.addCustomer("second", "2");
//
// Post p1 = postService.addPost(c1, "first title", "nonsense");
// Post p2 = postService.addPost(c2, "second title", "ordinal");
//
// Assertions.assertEquals(2, postService.findAllPosts().size());
//
// Assertions.assertEquals(p1.getCustomer(), c1);
// Assertions.assertEquals(p2.getCustomer(), c2);
//
// Assertions.assertEquals(c1.getPosts().get(0), p1);
// Assertions.assertEquals(c2.getPosts().get(0), p2);
//
// Assertions.assertEquals(p1, postService.findPost(p1.getId()));
// Assertions.assertEquals(p2, postService.findPost(p2.getId()));
//
// Post p3 = postService.addPost(c1, "asdf", "asd");
// postService.deletePost(p1.getId());
// Assertions.assertEquals(1, customerService.findCustomer(c1.getId()).getPosts().size());
//
// Post p4 = postService.updatePost(p2.getId(), "third title", "wow");
//
// Assertions.assertNotEquals(p2.getTitle(), p4.getTitle());
// Assertions.assertNotEquals(p2.getContent(), p4.getContent());
//
// commentService.deleteAllComment();
// postService.deleteAllPosts();
// customerService.deleteAllCustomers();
// }
//
// @Test
// void testComment() {
// commentService.deleteAllComment();
// postService.deleteAllPosts();
// customerService.deleteAllCustomers();
//
// Customer c1 = customerService.addCustomer("first", "1");
// Customer c2 = customerService.addCustomer("second", "2");
//
// Post p1 = postService.addPost(c1, "first title", "nonsense");
// Post p2 = postService.addPost(c2, "second title", "ordinal");
//
// Assertions.assertEquals(2, postService.findAllPosts().size());
//
// Comment com1 = commentService.addComment(c1, p2, "What");
// Comment com2 = commentService.addComment(c2, p1, "How");
//
// Assertions.assertEquals(c1, p2.getComments().get(0).getCustomer());
// Assertions.assertEquals(c2, p1.getComments().get(0).getCustomer());
//
// Comment com3 = commentService.addComment(c1, p1, "Really");
//
// Assertions.assertEquals(com2, commentService.findComment(p1.getComments().get(0).getId()));
//
// Comment com4 = commentService.updateComment(com3.getId(), "Not really");
//
// Assertions.assertNotEquals(com3.getContent(), com4.getContent());
// Assertions.assertEquals(com3.getCustomer().getId(), com4.getCustomer().getId());
//
// commentService.deleteAllComment();
// postService.deleteAllPosts();
// customerService.deleteAllCustomers();
// }
}