Compare commits

...

61 Commits
master ... lab4

Author SHA1 Message Date
1f973eec1d Отчет 2023-05-26 10:40:29 +04:00
bbf08f2a71 Merge branch 'lab3' into lab4 2023-05-26 10:40:01 +04:00
02342f4b1d Отчет 2023-05-26 10:39:40 +04:00
50946a1014 Merge branch 'lab2' into lab3 2023-05-26 10:39:21 +04:00
7d85282929 Отчет 2023-05-26 10:37:41 +04:00
c7a0109c00 Merge branch 'lab1' into lab2 2023-05-26 10:37:02 +04:00
a8e6af5269 Отчет 2023-05-26 10:36:22 +04:00
c61553b284 4 lab fixes 2023-04-21 10:44:50 +04:00
dcb1c381c9 4 lab alga jsonIgnore 2023-04-17 18:34:47 +04:00
a22ff8d8bb 5 lab 2023-04-10 17:58:28 +04:00
ee165d350a 4 lab что то 2023-04-09 16:45:02 +04:00
62627de1ee 4 lab full 2023-04-09 16:38:34 +04:00
58188e1dbe 4 lab img 8,9 2023-04-09 16:24:27 +04:00
23af234a27 4 lab img 7 2023-04-09 16:24:07 +04:00
534654ffd5 4 lab img 6 2023-04-09 16:23:49 +04:00
bd695a00ba 4 lab img 5 2023-04-09 16:23:31 +04:00
4977f33ed1 4 lab img 4 2023-04-09 16:23:12 +04:00
12d79028c6 4 lab img 3 2023-04-09 16:22:51 +04:00
d45c220d50 4 lab img 2 2023-04-09 16:22:33 +04:00
3acc25cbc6 4 lab img 1 2023-04-09 16:21:33 +04:00
6aa51bc74e 4 lab front) 2023-04-09 16:14:20 +04:00
ab9181004e 4 lab front) 2023-04-09 16:13:07 +04:00
e40639a883 4 lab front) 2023-04-09 16:10:31 +04:00
18ee5ece77 4 lab front) 2023-04-09 16:09:51 +04:00
26f94dab02 4 lab front) 2023-04-09 16:08:13 +04:00
9cd8ce211d 4 lab pre front 2023-04-09 15:49:28 +04:00
c88068f489 4 lab pls push 2023-04-09 15:44:44 +04:00
688fd255c6 4 lab УРАААААААААААА 2023-04-07 22:15:50 +04:00
4b9638ad2f 4 lab попытка сделать добавление постов (неудачно) 2023-04-07 20:33:54 +04:00
62d5bd2394 4 lab сделал круды для клиентов(типо регистрации) и в клиенте метод для получения его постов 2023-04-07 16:33:36 +04:00
1335f82494 4 lab прикол 2023-04-07 12:00:07 +04:00
eecfe393e4 4 lab fix 2023-04-04 15:29:47 +04:00
6a071071e2 4 lab CommentController 2023-04-04 13:47:11 +04:00
419eb0b15a 4 lab PostController 2023-04-04 13:41:16 +04:00
08dad1b6a4 4 lab кто придумал спикера соболезную 2023-04-04 13:24:17 +04:00
0c1764ab47 4 lab юзер вроде функционирует (тесты проходят) 2023-04-04 12:13:31 +04:00
ee923e986d 4 lab посты вроде функционируют 2023-04-04 11:43:08 +04:00
cbf337eea6 4 lab репозитории (не законченные очевидно) и сервис под репозитории для коммента (тесты отрабатывают) 2023-04-04 10:26:49 +04:00
33f6f1dd21 4 lab начало неизбежного.... 2023-04-04 10:13:40 +04:00
55b8db56c7 3 lab (она готовая просто лишнее убираю) 2023-04-03 19:30:09 +04:00
b016ee75a3 full 3 lab 2023-04-03 16:06:40 +04:00
32498b023a 3 лаба (тесты верные) 2023-04-02 09:36:05 +04:00
c1a8b9fe81 3 лаба вроде работает 2023-03-30 15:04:28 +04:00
45a590f145 3 лаба вроде клиент нормально добавляет посты и удаляет их
Осталось сделать +- тоже самое с комментариями с ссылкой на юзера
2023-03-29 10:38:32 +04:00
071d001e08 3 лаба Я наверное скоро умру 2023-03-27 23:08:33 +04:00
2cb40754c1 3 лаба доделать тесты и функционал 2023-03-27 17:50:16 +04:00
ca9a45d0b8 3 лаба название исправил 2023-03-26 21:37:30 +04:00
b620bbf62d 3 лаба название исправил 2023-03-24 08:56:17 +04:00
6bee6f84ee 3 лаба тест для новостей (Вроде конец) 2023-03-20 18:01:03 +04:00
b24242b20f 3 лаба тест для клиента(пользователя) 2023-03-20 17:40:20 +04:00
903e6051e8 3 лаба тест для избранного 2023-03-20 17:25:34 +04:00
5ca10677cf 3 лаба (Переписал сущности под ПО Школы) (Тесты?) 2023-03-20 17:06:26 +04:00
b43f9e4ffa 3 лаба (Остались тесты?) 2023-03-16 15:58:22 +04:00
58bf3c0d25 3 лаба (В покупку(сервис) добавил добавление и удаление техники) 2023-03-16 15:57:28 +04:00
a55af823c6 3 лаба (Прикольчик) (Тесты и в сервисе некоторые методы исправить) 2023-03-16 15:43:29 +04:00
c65125a48e 3 лаба (Прикольчик) (Осталость один ко многим) 2023-03-14 18:13:45 +04:00
f0e3f4374b 3 лаба (Многие ко многим) (вроде работает). 2023-03-13 20:52:56 +04:00
0df1eca957 3 лаба (надо фиксить). 2023-03-13 18:13:19 +04:00
41fff9ad53 Готовая лабораторная работа №2. 2023-02-27 17:41:33 +04:00
23bb2f4187 Готовая лабораторная работа. (FIX) 2023-02-13 17:35:14 +04:00
843cf0b815 Готовая лабораторная работа 2023-02-13 17:25:03 +04:00
79 changed files with 4651 additions and 27 deletions

4
.gitignore vendored
View File

@ -4,7 +4,9 @@ build/
!gradle/wrapper/gradle-wrapper.jar
!**/src/main/**/build/
!**/src/test/**/build/
node_modules
data.mv.db
data.trace.db
### STS ###
.apt_generated
.classpath

24
FrontEnd/.gitignore vendored Normal file
View File

@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

BIN
FrontEnd/Ped.pdf Normal file

Binary file not shown.

BIN
FrontEnd/Rasp(1-4).pdf Normal file

Binary file not shown.

BIN
FrontEnd/Rasp(5-11).pdf Normal file

Binary file not shown.

53
FrontEnd/build.gradle Normal file
View File

@ -0,0 +1,53 @@
import com.github.gradle.node.util.PlatformHelper
import groovy.text.SimpleTemplateEngine
plugins {
id 'java'
id 'com.github.node-gradle.node' version '3.5.1'
id "de.undercouch.download" version '5.3.1'
}
node {
version = '18.15.0'
download = true
}
jar.dependsOn 'npmBuild'
clean.dependsOn 'npmClean'
nodeSetup.dependsOn 'downloadNode'
jar {
from 'dist'
into 'static'
}
task downloadNode(type: Download) {
final helper = new PlatformHelper()
final templateData = [
"url" : node.distBaseUrl.get(),
"version": node.version.get(),
"os" : helper.osName,
"arch" : helper.osArch,
"ext" : helper.windows ? 'zip' : 'tar.gz'
]
final urlTemplate = '${url}/v${version}/node-v${version}-${os}-${arch}.${ext}'
final engine = new SimpleTemplateEngine()
final url = engine.createTemplate(urlTemplate).make(templateData).toString()
final String destDir = '.gradle/'
file(destDir).mkdirs()
src url
dest destDir
overwrite false
}
tasks.register('npmBuild', NpmTask) {
dependsOn npmInstall
args = ['run-script', 'build']
}
tasks.register('npmClean', NpmTask) {
dependsOn npmInstall
args = ['run-script', 'clean']
}

BIN
FrontEnd/img/6666.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 60 KiB

BIN
FrontEnd/img/Emblema.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 77 KiB

BIN
FrontEnd/img/Rasp.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 67 KiB

BIN
FrontEnd/img/Shkola.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 166 KiB

BIN
FrontEnd/img/banner1.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 522 KiB

BIN
FrontEnd/img/banner2.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 903 KiB

BIN
FrontEnd/img/banner3.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 471 KiB

BIN
FrontEnd/img/icon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 54 KiB

BIN
FrontEnd/img/owl.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 147 KiB

16
FrontEnd/index.html Normal file
View File

@ -0,0 +1,16 @@
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="img/icon.png" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="/node_modules/bootstrap/dist/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="/node_modules/bootstrap/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="/node_modules/@fortawesome/fontawesome-free/css/all.min.css">
<title>МБОУ средняя общеобразовательная школа №10</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.jsx"></script>
</body>
</html>

18
FrontEnd/js/banner.js Normal file
View File

@ -0,0 +1,18 @@
document.addEventListener('DOMContentLoaded', function () {
console.info('Loaded');
const banners = document.querySelectorAll("#banner img");
var old = banners.length - 1;
var current = 0;
function loop() {
banners[current].setAttribute('className', 'show');
banners[old].setAttribute('className', 'hide');
console.info('Banner changed');
old = current;
current++;
if (current === banners.length) {
current = 0;
}
setTimeout(loop, 5000);
}
loop();
});

1641
FrontEnd/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

26
FrontEnd/package.json Normal file
View File

@ -0,0 +1,26 @@
{
"name": "spa-react",
"private": true,
"source": "index.html",
"version": "1.0.0",
"type": "module",
"scripts": {
"start": "vite",
"build": "vite build",
"preview": "vite preview"
},
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.4.4",
"axios": "^1.1.3",
"bootstrap": "^5.2.2",
"@fortawesome/fontawesome-free": "^6.2.1"
},
"devDependencies": {
"@types/react": "^18.0.24",
"@types/react-dom": "^18.0.8",
"vite": "^3.2.3",
"@vitejs/plugin-react": "^2.2.0"
}
}

View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><!--! Font Awesome Pro 6.2.1 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license (Commercial License) Copyright 2022 Fonticons, Inc. --><path d="M96 0C43 0 0 43 0 96V416c0 53 43 96 96 96H384h32c17.7 0 32-14.3 32-32s-14.3-32-32-32V384c17.7 0 32-14.3 32-32V32c0-17.7-14.3-32-32-32H384 96zm0 384H352v64H96c-17.7 0-32-14.3-32-32s14.3-32 32-32zm32-240c0-8.8 7.2-16 16-16H336c8.8 0 16 7.2 16 16s-7.2 16-16 16H144c-8.8 0-16-7.2-16-16zm16 48H336c8.8 0 16 7.2 16 16s-7.2 16-16 16H144c-8.8 0-16-7.2-16-16s7.2-16 16-16z"/></svg>

After

Width:  |  Height:  |  Size: 611 B

48
FrontEnd/src/App.jsx Normal file
View File

@ -0,0 +1,48 @@
import { useRoutes, Outlet, BrowserRouter } from 'react-router-dom';
import Header from './components/common/Header';
import Catalogs from './components/catalogs/MainPage';
import CatalogGroups from './components/catalogs/Autorize';
import CatalogStudents from './components/catalogs/News';
import Post from './components/catalogs/Post';
import Reports from './components/catalogs/RezhimRaboty';
import ReportGroupStudents from './components/catalogs/Raspisanie';
import Footer from './components/common/Footer';
function Router(props) {
return useRoutes(props.rootRoute);
}
export default function App() {
const routes = [
{ index: true, element: <Catalogs /> },
{ path: 'Main_page', element: <Catalogs />, label: 'Главная' },
{ path: 'News', element: <CatalogStudents/>, label:'Новости' },
{ path: 'Autorize', element: <CatalogGroups />, label:'Авторизация'},
{ path: 'RezhimRaboty', element: <Reports />, label: 'Режим работы' },
{ path: 'Raspisanie', element: <ReportGroupStudents />,label:'Расписание' },
{ path: 'Post', element: <Post/>}
];
const links = routes.filter(route => route.hasOwnProperty('label'));
const rootRoute = [
{ path: '/', element: render(links), children: routes }
];
function render(links) {
return (
<div className='body_app'>
<Header links={links} />
<div className="d-flex text-white bg-info bg-gradient fw-bold">
<Outlet />
</div>
<Footer links={links}/>
</div>
);
}
return (
<BrowserRouter>
<Router rootRoute={ rootRoute } />
</BrowserRouter>
);
}

View File

@ -0,0 +1,22 @@
.myModal {
position: fixed;
top: 0;
bottom: 0;
right: 0;
left: 0;
display: none;
background: rgba(0,0,0, 0.5);
}
.myModalContent {
padding: 25px;
background: white;
border-radius: 16px;
max-width: 600px;
}
.myModal.active {
display: flex;
justify-content: center;
align-items: center;
}

View File

@ -0,0 +1,146 @@
import React from "react";
import { useState } from 'react';
import {useEffect} from 'react';
import UserDto from '../../models/UserDto';
export default function CatalogGroups(props) {
const formRef = React.createRef();
const [output, setOutput] = useState([]);
const FirstInput = document.getElementById("validationCustom01");
const LastInput = document.getElementById("validationCustom02");
const emailInput = document.getElementById("validationCustomMail");
const getAll = async function () {
const requestUrl = "http://localhost:8080/user";
const response = await fetch(requestUrl);
const users = await response.json();
setOutput(users);
}
useEffect(() => {
getAll();
}, []);
const remove = async function(id){
const requestParams = {
method: "DELETE",
headers:{
"Content-Type":"application/json",
}
};
const requestUrl = "http://localhost:8080" + "/user/" + id;
const response=await fetch(requestUrl,requestParams);
return await response.json;
};
const create = async function (firstName, lastName,Email) {
const requestParams = {
method: "POST",
headers: {
"Content-Type": "application/json",
}
};
const response = await fetch("http://localhost:8080" + `/user?firstName=${firstName}&lastName=${lastName}&email=${Email}`, requestParams);
return await response.json();
}
const refresh = async function(id,firstName, lastName,Email)
{
const requestParams={
method:"PUT",
headers:{
"Content-Type":"application/json",
}
};
const response=await fetch(`http://localhost:8080/user/${id}?firstName=${firstName}&lastName=${lastName}&email=${Email}`,requestParams);
return await response.json();
}
const add_but = function(event)
{
event.preventDefault();
create(FirstInput.value, LastInput.value,emailInput.value).then((result) => {
getAll();
FirstInput.value = "";
LastInput.value = "";
emailInput.value="";
alert(`User[id=${result.id}, firstName=${result.firstName}, lastName=${result.lastName},email=${result.email}]`);
});
}
const edit_btn = function(id,event)
{
console.log("Обновление")
refresh(id,FirstInput.value, LastInput.value,emailInput.value).then((result)=>{
getAll();
FirstInput.value = "";
LastInput.value = "";
emailInput.value="";
});
}
const rem_but = function(id,event)
{
console.log("Удаление")
remove(id).then((result)=>{
getAll();
});
}
return (
<div className="p-2">
<form className="row g-3 needs-validation">
<div className="col-md-4">
<label className="form-label" htmlFor="validationCustom01">Имя</label>
<input className="form-control" id="validationCustom01" type="text" defaultValue="" required/>
<div className="valid-feedback">Отлично!</div>
<div className="invalid-feedback">Введите имя!</div>
</div>
<div className="col-md-4">
<label className="form-label" htmlFor="validationCustom02">Фамилия</label>
<input className="form-control" id="validationCustom02" type="text" defaultValue="" required/>
<div className="valid-feedback">Отлично! </div>
<div className="invalid-feedback">Введите Фамилию!</div>
</div>
<div className="col-md-4">
<label className="form-label" htmlFor="validationCustomMail">Почта</label>
<div className="input-group has-validation">
<input className="form-control" id="validationCustomMail" type="email" aria-describedby="inputGroupPrepend" required/>
<div className="valid-feedback">Отлично!</div>
<div className="invalid-feedback">Введите почту!</div>
</div>
</div>
<div className="col-12">
<div className="form=check">
<input className="form-check-input" id="invalidCheck" type="checkbox" defaultValue="" required/>
<label className="form-check-label" htmlFor="invalidCheck">Согласие на обработку персональных данных</label>
<div className="valid-feedback">Отлично!</div>
<div className="invalid-feedback">Введите пароль!</div>
</div>
</div>
<div className="col-12 d-flex">
<div className="d-grid col-sm-4 mx-auto">
<button type="button" id="add_btn" className="btn btn-outline-light btn-lg float-end" onClick={add_but}>Add</button>
</div>
</div>
</form>
<div className="row table-responsive mx-2">
<table className="table mt-3">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Last Name</th>
<th scope="col">First Name</th>
<th scope="col">Email</th>
<th scope="col"></th>
<th scope="col"></th>
</tr>
</thead>
<tbody id="tbody">
{output.map((user) => (
<tr key={user.id}>
<th scope="row">{user.id}</th>
<td>{user.firstName}</td>
<td>{user.lastName}</td>
<td>{user.email}</td>
<td><button type="button" className="btn btn-outline-light text-center mx-2" onClick={(e) => edit_btn(user.id, e)}><i className="fa-sharp fa-solid fa-pen"></i></button></td>
<td><button type="button" className="btn btn-outline-light text-center mx-2" onClick={(e) => rem_but(user.id, e)}><i className="fa-sharp fa-solid fa-trash"></i></button></td>
</tr>
))}
</tbody>
</table>
</div>
</div>
);
}

View File

@ -0,0 +1,150 @@
import { useState, useEffect } from "react";
import Toolbar from "../common/Toolbar";
import Table from "../common/Card";
import Modal from "../common/Modal";
export default function Catalog(props) {
const [items, setItems] = useState([]);
const [modalHeader, setModalHeader] = useState('');
const [modalConfirm, setModalConfirm] = useState('');
const [modalVisible, setModalVisible] = useState(false);
const [isEdit, setEdit] = useState(false);
const [userId,setUserId] = useState(0);
const [value,setvalue]=useState('');
useEffect(() => {
loadItems();
}, []);
useEffect(()=>
{
loadItems();
},[userId])
useEffect(()=>
{
loadItems2();
},[value])
const setUserIDd = async function(id)
{
setUserId(id);
}
const loadItems = async function() {
const requestUrl = `http://localhost:8080/user/${userId}/posts`;
const response = await fetch(requestUrl);
const posts = await response.json();
setItems(posts);
}
const loadItems2 = async function() {
const requestUrl = `http://localhost:8080/post/filteredposts?Text=${value}`;
const response = await fetch(requestUrl);
const posts = await response.json();
console.log(posts);
setItems(posts);
}
const saveItem = async function() {
if (!isEdit) {
const requestUrl = `http://localhost:8080/user/${userId}/Post`;
const temppost=JSON.stringify(props.data)
const requestParams = {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: temppost,
};
await fetch(requestUrl,requestParams).then(() => loadItems());
} else {
const requestUrl = "http://localhost:8080/post/"+props.data.id;
const temppost=JSON.stringify(props.data)
const requestParams = {
method: "PUT",
headers: {
"Content-Type": "application/json",
},
body: temppost,
};
await fetch(requestUrl,requestParams).then(() => loadItems());
}
}
function handleAdd() {
setEdit(false);
setModalHeader('Добавление элемента');
setModalConfirm('Добавить');
setModalVisible(true);
props.onAdd();
}
const edit = async function(editedId) {
const requestUrl = "http://localhost:8080/post/"+editedId;
const requestParams = {
mode: 'cors'
}
await fetch(requestUrl,requestParams)
.then(data => {
setEdit(true);
setModalHeader('Редактирование элемента');
setModalConfirm('Сохранить');
setModalVisible(true);
//props.onEdit(data);
return data.json();
}).then(data =>{
props.onEdit(data);
});
}
const handleRemove = async function(id) {
if (confirm('Удалить выбранные элементы?')) {
const requestUrl = `http://localhost:8080/user/${userId}/Post/`+id;
const requestParams = {
method: "DELETE",
headers: {
"Content-Type": "application/json",
},
};
await fetch(requestUrl,requestParams).then(()=>loadItems());
}
}
function handleModalHide() {
setModalVisible(false);
}
function handleModalDone() {
saveItem();
}
return (
<>
<div className="mx-3 my-2"><input type="text" id="search" className="form-control" required onChange={(event)=> setvalue(event.target.value)}/></div>
<Toolbar
onAdd={handleAdd}
getUser={setUserIDd}
/>
<Table
headers={props.headers}
items={items}
value={value}
userId={userId}
selectable={true}
onEdit={edit}
onRemove={handleRemove}/>
<Modal
header={modalHeader}
confirm={modalConfirm}
visible={modalVisible}
onHide={handleModalHide}
onDone={handleModalDone}>
{props.children}
</Modal>
</>
);
}

View File

@ -0,0 +1,23 @@
import { useEffect } from "react";
import { useState } from "react";
import Banner from '../common/Banner'
export default function Catalogs(props) {
return (
<div className="container-fluid">
<Banner />
<div className="lp"><img className="img-fluid img-school float-start my-2" src="img/Shkola.jpg" alt="shkola"/>
<div>
<p className="fs-4">Мы расположены по адресу: 423228, г. Нижневратовск, ул. Корзинова, д. 37</p>
<div>
<div className="fs-4">Контактные телефоны
<p>(8228) 13-77-85</p>
<p>(8800) 55-53-50</p>
<p>факс (8911) 22-44-96</p>
</div>
</div>
</div>
</div><a className="fs-4" href="mailto:Nizhnev.school10@mail.ru">email: Nizhnev.school10@mail.ru</a>
</div>
);
}

View File

@ -0,0 +1,61 @@
import { useState, useEffect } from 'react';
import Catalog from './Catalog';
import New from '../../models/NewDto';
export default function News(props) {
const url = 'post/';
const transformer = (data) => new New(data);
const catalogStudHeaders = [
{ name: 'image', label: 'Картинка' },
{ name: 'heading', label: 'Заголовок' },
{ name: 'content', label: 'Новости' },
];
const [data, setData] = useState(new New());
const fileReader=new FileReader();
fileReader.onloadend=()=>{
const tempval=fileReader.result;
setData({ ...data, ['image']: tempval})
}
const handleOnChange=(event)=>{
event.preventDefault();
const file=event.target.files[0];
fileReader.readAsDataURL(file);
};
function handleOnAdd() {
setData(new New());
}
function handleOnEdit(data) {
setData(new New(data));
}
function handleFormChange(event) {
setData({ ...data, [event.target.id]: event.target.value })
}
return (
<Catalog
headers={catalogStudHeaders}
url={url}
transformer={transformer}
data={data}
onAdd={handleOnAdd}
onEdit={handleOnEdit}>
<div className="mb-3 text-black">
<label htmlFor="image" className="form-label">Изображение</label>
<input type="file" id="image" className="form-control" required onChange={handleOnChange}/>
</div>
<div className="mb-3">
<label htmlFor="heading" className="form-label text-black">Заголовок</label>
<input type="text" id="heading" className="form-control" required
value={data.heading} onChange={handleFormChange}/>
</div>
<div className="mb-3">
<label htmlFor="content" className="form-label text-black">Содержание</label>
<input type="text" id="content" className="form-control" required
value={data.content} onChange={handleFormChange}/>
</div>
</Catalog>
);
}

View File

@ -0,0 +1,159 @@
import React from "react";
import { useState } from 'react';
import {useEffect} from 'react';
import New from '../../models/NewDto';
import TableComment from "../common/TableComment";
export default function Post(props) {
useEffect(() => {
getAll();
}, []);
const [output, setOutput] = useState([]);
const [userId,setUserId] = useState();
const commentInput = document.getElementById("commentText");
const getAll = async function () {
const queryString=window.location.search;
const urlParams=new URLSearchParams(queryString);
const id=urlParams.get('id');
getCurrentPost(id).then(curPost => setad(curPost));
getComments(id)
const requestUrl = "http://localhost:8080/user";
const response = await fetch(requestUrl);
const users = await response.json();
setOutput(users);
}
const refresh = async function(id,text)
{
const requestParams={
method:"PUT",
headers:{
"Content-Type":"application/json",
}
};
const response=await fetch(`http://localhost:8080/comment/${id}?Text=${text}`,requestParams);
return await response.json();
}
const create = async function (text, id) {
const requestParams = {
method: "POST",
headers: {
"Content-Type": "application/json",
}
};
const response = await fetch(`http://localhost:8080/post/${ad.id}/Comment/${id}?Text=${text}`,requestParams);
}
const getCurrentPost = async function (id) {
const requestUrl = "http://localhost:8080/post/"+id;
const response = await fetch(requestUrl);
const product = await response.json();
return product;
}
const remove = async function(id){
const requestParams = {
method: "DELETE",
headers:{
"Content-Type":"application/json",
}
};
const requestUrl = `http://localhost:8080/post/${ad.id}/Comment/${id}`;
const response=await fetch(requestUrl,requestParams);
return await response.json;
};
function getuser(){
var selectBox = document.getElementById("selectBox");
var selectedValue = selectBox.options[selectBox.selectedIndex].value;
setUserId(selectedValue);
}
const getComments = async function(id)
{
const requesturl = "http://localhost:8080/post/"+id+"/comments"
const response = await fetch(requesturl);
const comments = await response.json();
setComments(comments);
}
const [ad, setad] = useState([]);
const [comments,setComments] = useState([]);
const rem_but = function(id,event)
{
remove(id).then((result)=>{
getAll();
});
}
const add_but = function(event)
{
event.preventDefault();
create(commentInput.value, userId).then((result) => {
getAll();
commentInput.value = "";
alert(`Comment[id=${result.id}, text=${result.firstName}]`);
});
}
const edit_btn = function(id,event)
{
console.log("Обновление")
refresh(id, commentInput.value).then((result)=>{
getAll();
commentInput.value = "";
});
}
return(
<div>
<div className="da d-flex my-2">
<div><img className="imga img-fluid float-start mx-2" style={{width: "500px" ,height: "300px" }} src={ad.image}/></div>
<div className="container-fluid my-2 mx-1">
<h1>{ad.heading}</h1>
<p>{ad.content}</p>
</div>
</div>
<div className="d-flex mx-2">
<select id="selectBox" onChange={getuser}>
<option disabled value="">Выбор...</option>
{
output.map((client) => (
<option className='text-black' key={client.id} value={client.id}>{client.firstName}</option>
))}
</select>
<input className="form-control" id="commentText" type="text" defaultValue="" required/>
<button type="button" className="btn btn-primary" onClick={(e)=>add_but(e)}>
+
</button>
</div>
<div className="row table-responsive mx-2">
<TableComment
comments={comments}
onRemove={rem_but}
onEdit={edit_btn}
/>
</div>
</div>
);
}

View File

@ -0,0 +1,13 @@
export default function ReportGroupStudents(props) {
return (
<div className="container-fluid justify-content-center align-items-center d-flex flex-column my-2">
<div>
<h6>Расписание<img className="pdf-size " src="img/Rasp.png" alt="Rasp"/></h6>
</div>
<div> <a href="Rasp(1-4).pdf" target="_blank"><img className="pdf-size" src="img/6666.png"/></a><a href="Rasp(1-4).pdf" target="_blank">Расписание 1 - 4 кл. (.pdf)</a></div><br/><br/>
<div> <a href="Rasp(5-11).pdf" target="_blank"><img className="pdf-size" src="img/6666.png"/></a><a href="Rasp(5-11).pdf" target="_blank">Расписание 5 - 11 кл. (.pdf)</a></div>
</div>
);
}

View File

@ -0,0 +1,135 @@
export default function Reports(props) {
return (
<div className="container-fluid my-2">
<div className="float-start me-5">
<h3 className="text-wrap">Расписание звонков</h3>
<table className="Vnov1 float-start table-bordered">
<tbody>
<tr>
<th colSpan="2">1 смена</th>
<th colSpan="2">2 смена</th>
</tr>
<tr>
<td> </td>
<td> </td>
<td></td>
<td> </td>
</tr>
<tr>
<td>1 урок</td>
<td>8.00-8.45</td>
<td>0 урок</td>
<td>12.55-13.40</td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td>2 урок </td>
<td>8.55-9.40 </td>
<td>1 урок </td>
<td>13.50-14.35</td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td>3 урок </td>
<td>10.00-10.45</td>
<td>2 урок</td>
<td>14.50-15.35</td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td></td>
</tr>
<tr>
<td>4 урок</td>
<td>11.05-11.50</td>
<td>3 урок</td>
<td>12.00-12.45</td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td></td>
</tr>
<tr>
<td>5 урок</td>
<td>12.00-12.45</td>
<td>4 урок</td>
<td>16.45-17.30</td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td></td>
</tr>
<tr>
<td>6 урок</td>
<td>12.55-13.40 </td>
<td>5 урок</td>
<td>17.40-18.25 </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td></td>
</tr>
<tr>
<td>7 урок</td>class
<td>13.50-14.35</td>
<td> </td>
<td></td>
</tr>
</tbody>
</table>
</div>
<div>
<h3>Режим работы ОУ:
<div className="align-items-justify text-wrap fs-5">Учебный год в МБОУ средняя общеобразовательная школа 10 начинается 2 сентября, состоит из 3-х триместров, включает каникулы по графику. МБОУ средняя общеобразовательная школа 10 работает в две смены. Школа работает в течение 5 дней в неделю с понедельника по пятницу, выходной день суббота и воскресенье в 1-11 классах. Продолжительность учебного года 33 учебных недели для учащихся 1-х классов, 34 учебных недель для учащихся 2-11 классов. Для учащихся, обучающихся на дому, продолжительность учебного года составляет 34 недели. Начало учебных занятий в 8-00.
<table className="table-bordered">
<tbody>
<th>Триместр</th>
<th>Дата начала/дата окончания</th>
<th colSpan="2">Каникулы</th>
<tr>
<td>I</td>
<td>02.09.2022 - 19.11.2022</td>
<td>08.10.2022 - 13.10.2022</td>
<td>20.11.2022 - 25.11.2022</td>
</tr>
<tr>
<td>II</td>
<td>26.11.2022 - 19.02.2023</td>
<td>28.12.2022 - 07.01.2023 </td>
<td>20.02.2023 - 25.02.2023</td>
</tr>
<tr>
<td>III</td>
<td>26.02.2023 - 29.05.2023</td>
<td>10.04.2023 - 15.04.2023</td>
<td>30.05.2023 - 31.08.2023</td>
</tr>
</tbody>
</table>
</div>
</h3>
</div>
</div>
);
}

View File

@ -0,0 +1,24 @@
import { useState, useEffect } from 'react';
import '../../style.css'
export default function Banner(props) {
const[bannerNum,setBanner]=useState(['show','hide','hide']);
useEffect(() => {
const length=3;
var old = length-1;
var current = 0;
const timer = window.setInterval(()=>{
setBanner([...bannerNum, bannerNum[current] = 'show', bannerNum[old] = 'hide']);
old = current;
current++;
if (current ===length) {
current = 0;
}
},5000);
return()=>{
window.clearInterval(timer);
}
},[]);
return(
<div id="banner"><img className={bannerNum[0]} src="img/banner1.png"/><img className={bannerNum[1]} src="img/banner2.png"/><img className={bannerNum[2]} src="img/banner3.png"/></div>
);
}

View File

@ -0,0 +1,98 @@
import { useEffect, useState } from 'react';
import ModalEdit from './ModalComment';
import TablePostAndComment from './TablePostAndComment';
export default function Card(props) {
function edit(id) {
props.onEdit(id);
}
function remove(id) {
props.onRemove(id);
}
useEffect(() => {
getAll();
}, []);
const [clients, setClientst] = useState([]);
const getAll = async function () {
const requestUrl = "http://localhost:8080/user";
const response = await fetch(requestUrl);
const users = await response.json();
setClientst(users);
}
const [modalTable, setModalTable] = useState(false);
const [currEditItem, setCurrEditItem] = useState(0);
const [text, setText] = useState('');
function handleEdit(id) {
console.info("Start edit script");
setCurrEditItem(id);
setModalTable(true)
console.info('End edit script');
};
const handleSubmitEdit = async (e, id) => {
console.info('Start synchronize edit');
e.preventDefault(); // страница перестает перезагружаться
const requestUrl = `http://localhost:8080/post/${id}/Comment/${props.userId}?Text=${text}`;
const requestParams = {
method: "POST",
headers: {
"Content-Type": "application/json",
},
};
await fetch(requestUrl,requestParams);
setText('');
setModalTable(false);
};
return (
<div className="container-fluid mt-3">
{
props.items.map((item, index) =>
<div key={item.id}
className="card border-dark mb-3 d-flex flex-row text-black justify-content-between">
<div className=''>
<img className="col" style={{width: "300px" ,height: "200px" }} src={item.image}/>
</div>
<div className='d-flex flex-grow-1 flex-column'>
<div className='flex-grow-1 mx-2'>
{
props.headers.map(header =>
header.name == "image" ? null :
<div className="" key={item.id + header.name}>{item[header.name]}</div>
)
}
</div>
<div className="d-flex flex-row justify-content-end ">
<button type="button" className="btn btn-outline-primary text-center mx-2" data-bs-toggle="modal" data-bs-target="#redact" onClick={(e) => edit(item.id, e)}>
<i className="fa-sharp fa-solid fa-pen"></i>
</button>
<button href="#"
className="btn btn-outline-primary mx-3"
onClick={(e) => remove(item.id, e)}><i className="fa-sharp fa-solid fa-trash"></i></button>
<a href={`/Post?id=${item.id}`} className='btn btn-outline-primary mx-2'><i className="fa-solid fa-envelopes-bulk"></i></a>
</div>
<TablePostAndComment
comments={item.comments}
value={props.value}
/>
</div>
</div>
)
}
<ModalEdit visible={modalTable} setVisible={setModalTable}>
<form className="g-3 fs-4 description fw-bold container" id="frm-items-edit" onSubmit={(e) => handleSubmitEdit(e, currEditItem)}>
<div className="row">
<label className="form-label" htmlFor="priceEdit">Комментарий</label>
<input value={text} onChange={e => setText(e.target.value)} className="form-control" name='priceEdit' id="priceEdit" type="text" placeholder="Введите содержимое комментария" required />
</div>
<div className="text-center mt-3">
<button className="btn btn-primary mx-1" type="submit" id="buttonSaveChanges">Сохранить изменения</button>
<button className="btn btn-secondary mx-1" type="button" data-bs-dismiss="modal" onClick={() => setModalTable(false)}>Отмена</button>
</div>
</form>
</ModalEdit>
</div>
);
}

View File

@ -0,0 +1,7 @@
import { NavLink } from 'react-router-dom';
export default function Footer(props) {
return (
<footer className="container-fluid d-flex text-white bg-primary bg-gradient mt-auto">© 2022 МОУ "СОШ №10"</footer>
);
}

View File

@ -0,0 +1,30 @@
import { NavLink } from 'react-router-dom';
export default function Header(props) {
return (
<header className="fs-4 fw-bold p-1 text-white bg-primary bg-gradient">
<div><img className="img-fluid float-start" src="../img/Emblema.png" alt="Emblema"/>
<p className="fs-5 Cont">Муниципальное бюджетное общеобразовательное учреждение средняя общеобразовательная школа 10</p>
</div>
<nav className="navbar navbar-expand-md navbar-dark">
<div className="container-fluid">
<button className="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span className="navbar-toggler-icon"></span></button>
<div className="navbar-collapse collapse justify-content-end" id="navbarNav">
<nav className="headers-problem navbar navbar-expand-lg d-flex">
{
props.links.map(route =>
<button key={route.path}
className="btn btn-outline-light mx-1">
<NavLink className="nav-link" to={route.path}>
{route.label}
</NavLink>
</button>
)
}
</nav>
</div>
</div>
</nav>
</header>
);
}

View File

@ -0,0 +1,46 @@
import React from "react";
export default function Modal(props) {
const formRef = React.createRef();
function hide() {
props.onHide();
}
function done(e) {
e.preventDefault();
if (formRef.current.checkValidity()) {
props.onDone();
hide();
} else {
formRef.current.reportValidity();
}
}
return (
<div className="modal fade show" tabIndex="-1" aria-hidden="true"
style={{ display: props.visible ? 'block' : 'none' }}>
<div className="modal-dialog">
<div className="modal-content">
<div className="modal-header">
<h1 className="modal-title fs-5" id="exampleModalLabel">{props.header}</h1>
<button className="btn-close" type="button" aria-label="Close"
onClick={hide}></button>
</div>
<div className="modal-body">
<form ref={formRef} onSubmit={done}>
{props.children}
</form>
</div>
<div className="modal-footer">
<button className="btn btn-secondary" type="button" onClick={hide}>Закрыть</button>
<button className="btn btn-primary" type="button" onClick={done}>
{props.confirm}
</button>
</div>
</div>
</div>
</div>
);
}

View File

@ -0,0 +1,18 @@
import { React } from 'react'
import classes from '../../ModalEdit.module.css'
export default function ModalEdit({children, visible, setVisible}) {
const rootClasses = [classes.myModal]
if (visible) {
rootClasses.push(classes.active);
}
//onClick={()=>setVisible(false)}
return (
<div className={rootClasses.join(' ')} >
<div className={classes.myModalContent}>
{children}
</div>
</div>
)
}

View File

@ -0,0 +1,34 @@
export default function TableComment(props) {
function edit(id,e) {
props.onEdit(id);
}
function remove(id,e) {
props.onRemove(id,e);
}
return(
<table className="table mt-3">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Text</th>
<th scope="col"></th>
<th scope="col"></th>
</tr>
</thead>
<tbody id="tbody">
{props.comments.map((comment) => (
<tr key={comment.id}>
{console.log(comment.user)}
<th scope="row">{comment.user}</th>
<td>{comment.text}</td>
<td><button type="button" className="btn btn-outline-light text-center mx-2" onClick={(e) => edit(comment.id, e)}><i className="fa-sharp fa-solid fa-pen"></i></button></td>
<td><button type="button" className="btn btn-outline-light text-center mx-2" onClick={(e) => remove(comment.id, e)}><i className="fa-sharp fa-solid fa-trash"></i></button></td>
</tr>
))}
</tbody>
</table>
);
}

View File

@ -0,0 +1,26 @@
export default function TablePostAndComment(props) {
const filteredads=props.comments.filter(ads=>{
return ads.text.includes(props.value);
})
return(
<table className="table mt-3">
<thead>
<tr>
<th scope="col"></th>
<th scope="col"></th>
<th scope="col"></th>
<th scope="col"></th>
</tr>
</thead>
<tbody id="tbody">
{filteredads.map((comment) => (
<tr key={comment.id}>
{console.log(comment.user)}
<th scope="row">{comment.user}</th>
<td>{comment.text}</td>
</tr>
))}
</tbody>
</table>
);
}

View File

@ -0,0 +1,43 @@
import { useState } from 'react';
import {useEffect} from 'react';
export default function Toolbar(props) {
function add() {
props.onAdd();
}
const [clients, setClientst] = useState([]);
useEffect(() => {
getAll();
}, []);
const getAll = async function () {
const requestUrl = "http://localhost:8080/user";
const response = await fetch(requestUrl);
const users = await response.json();
setClientst(users);
}
function getuser(){
var selectBox = document.getElementById("selectBox");
var selectedValue = selectBox.options[selectBox.selectedIndex].value;
props.getUser(selectedValue);
}
return (
<div className="d-flex float-start my-2">
<div className="mx-1">
<select id="selectBox" onChange={getuser}>
<option disabled value="">Выбор...</option>
{
clients.map((client) => (
<option className='text-black' key={client.id} value={client.id}>{client.firstName}</option>
))}
</select>
</div>
<div>
<button type="button" className="btn btn-primary" onClick={add}>
+
</button>
</div>
</div >
);
}

10
FrontEnd/src/main.jsx Normal file
View File

@ -0,0 +1,10 @@
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App'
import './style.css'
ReactDOM.createRoot(document.getElementById('app')).render(
<React.StrictMode>
<App />
</React.StrictMode>
)

View File

@ -0,0 +1,6 @@
export default class CommentDto {
constructor(args) {
this.id = args.id || null;
this.text = args.text;
}
}

View File

@ -0,0 +1,9 @@
export default class NewDto {
constructor(data) {
this.id = data?.id || null;
this.image = data?.image;
this.heading = data?.heading;
this.content = data?.content;
}
}

View File

@ -0,0 +1,8 @@
export default class BuyerDto {
constructor(args) {
this.id = args.id || null;
this.firstName = args.firstName;
this.lastName = args.lastName;
this.email = args.email;
}
}

146
FrontEnd/src/style.css Normal file
View File

@ -0,0 +1,146 @@
html
{
min-height: 100vh;
}
header .img-fluid
{
width:232px;
height:100px;
}
article .img-fluid
{
height:250px;
}
article .img-fluid1
{
height:100%;
width: 96%;
}
.owl
{
width:300px;
}
.pdf-size
{
width:70px;
}
body
{
min-height: 100vh;
}
.body_app
{
display: grid;
grid-template-rows:auto 1fr auto;
min-height: 100vh;
}
.lp
{
padding-left: 30px;
}
.img-school
{
margin-right: 1em;
float: start;
}
.Vnov
{
margin-right: 1em;
}
.Vnov1
{
margin-right: 1em;
}
.Cont
{
}
@media only screen and (max-width: 800px) {
.owl {
display:none;
}
}
@media only screen and (max-width: 1164px) {
.img-school
{
margin-right: 170px;
}
}
@media only screen and (max-width: 554px) {
.img-school
{
height: 20% !important;
width: 75%;
}
}
@media only screen and (max-width: 727px) {
.headers-problem
{
flex-direction: column;
}
.navbar
{
align-items: flex-start !important;
}
}
@media only screen and (max-width: 959px) {
.navbar
{
float:left !important;
}
}
@media only screen and (max-width: 463px) {
.Vnov
{
margin-right: 140px;
}
}
@media only screen and (max-width: 575px) {
.Vnov1
{
margin-right: 200px;
}
}
@media only screen and (max-width: 585px) {
.Cont
{
margin-right: 200px;
}
}
#banner {
margin: 15px;
display: flex;
align-items: center;
flex-direction: column;
}
#banner img {
border-radius: 5px;
}
#banner img.show {
height: 40%;
width: 60%;
opacity: 1;
transition: opacity 1s, visibility 0s;
}
#banner img.hide {
height: 0;
width: 0;
opacity: 0;
visibility: hidden;
transition: opacity 1s, visibility 0s 1s;
}
.Pole_height
{
height: 80px;
}

7
FrontEnd/vite.config.js Normal file
View File

@ -0,0 +1,7 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()]
})

View File

@ -1,22 +1,32 @@
plugins {
id 'java'
id 'org.springframework.boot' version '3.0.2'
id 'io.spring.dependency-management' version '1.1.0'
}
group = 'ru.ulstu.is'
group = 'np'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '17'
repositories {
mavenCentral()
}
jar {
enabled = false
}
dependencies {
implementation(project(':FrontEnd'))
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.hibernate.validator:hibernate-validator'
implementation group: 'org.springdoc', name: 'springdoc-openapi-ui', version: '1.6.5'
implementation 'org.springframework.boot:spring-boot-starter-validation'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
tasks.named('test') {
useJUnitPlatform()
}
}

186
data.trace.db Normal file
View File

@ -0,0 +1,186 @@
2023-03-27 16:52:44 jdbc[3]: exception
org.h2.jdbc.JdbcSQLSyntaxErrorException: Синтаксическая ошибка в выражении SQL "create table [*]user (id bigint not null, email varchar(255), first_name varchar(255), last_name varchar(255), primary key (id))"; ожидалось "identifier"
Syntax error in SQL statement "create table [*]user (id bigint not null, email varchar(255), first_name varchar(255), last_name varchar(255), primary key (id))"; expected "identifier"; SQL statement:
create table user (id bigint not null, email varchar(255), first_name varchar(255), last_name varchar(255), primary key (id)) [42001-210]
2023-03-27 16:52:44 jdbc[3]: exception
org.h2.jdbc.JdbcSQLSyntaxErrorException: Синтаксическая ошибка в выражении SQL "alter table if exists comment add constraint FK8kcum44fvpupyw6f5baccx25c foreign key (user_id) references [*]user"; ожидалось "identifier"
Syntax error in SQL statement "alter table if exists comment add constraint FK8kcum44fvpupyw6f5baccx25c foreign key (user_id) references [*]user"; expected "identifier"; SQL statement:
alter table if exists comment add constraint FK8kcum44fvpupyw6f5baccx25c foreign key (user_id) references user [42001-210]
2023-03-27 16:52:44 jdbc[3]: exception
org.h2.jdbc.JdbcSQLSyntaxErrorException: Синтаксическая ошибка в выражении SQL "alter table if exists post add constraint FK72mt33dhhs48hf9gcqrq4fxte foreign key (user_id) references [*]user"; ожидалось "identifier"
Syntax error in SQL statement "alter table if exists post add constraint FK72mt33dhhs48hf9gcqrq4fxte foreign key (user_id) references [*]user"; expected "identifier"; SQL statement:
alter table if exists post add constraint FK72mt33dhhs48hf9gcqrq4fxte foreign key (user_id) references user [42001-210]
2023-03-27 21:45:28 database: wrong user or password; user: "SA"
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
2023-03-27 21:45:50 database: wrong user or password; user: "SA"
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
2023-04-10 17:11:04 database: wrong user or password; user: "SA"
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

BIN
reports/Отчёт 1.docx Normal file

Binary file not shown.

BIN
reports/Отчёт 2.docx Normal file

Binary file not shown.

BIN
reports/Отчёт 3.docx Normal file

Binary file not shown.

BIN
reports/Отчёт 4.docx Normal file

Binary file not shown.

View File

@ -1 +1,2 @@
rootProject.name = 'sbapp'
include 'FrontEnd'

View File

@ -0,0 +1,39 @@
package ru.ulstu.is.sbapp.Comment.controller;
import org.springframework.web.bind.annotation.*;
import ru.ulstu.is.sbapp.Comment.service.CommentService;
import java.util.List;
@RestController
@RequestMapping("/comment")
public class CommentController {
private final CommentService commentService;
public CommentController(CommentService commentService) {
this.commentService = commentService;
}
@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){
return new CommentDto(commentService.addComment(Text));
}
@PutMapping("/{id}")
public CommentDto updateComment(@PathVariable Long id,
@RequestParam("Text") String Text){
return new CommentDto(commentService.updateComment(id,Text));
}
@DeleteMapping("/{id}")
public CommentDto deleteComment(@PathVariable Long id) {
return new CommentDto(commentService.deleteComment(id));
}
}

View File

@ -0,0 +1,30 @@
package ru.ulstu.is.sbapp.Comment.controller;
import ru.ulstu.is.sbapp.Comment.model.Comment;
import ru.ulstu.is.sbapp.Post.model.Post;
import ru.ulstu.is.sbapp.User.model.User;
public class CommentDto {
private Long id;
private String Text;
private String userName;
public CommentDto(){}
public CommentDto(Comment comment)
{
this.id= comment.getId();
this.Text=comment.getText();
this.userName=comment.getUser().getFirstName() + " " + comment.getUser().getLastName();
}
public Long getId()
{
return id;
}
public String getText() {return Text;}
public String getUser()
{
return userName;
}
}

View File

@ -0,0 +1,81 @@
package ru.ulstu.is.sbapp.Comment.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import jakarta.persistence.*;
import jakarta.validation.constraints.NotBlank;
import ru.ulstu.is.sbapp.Post.model.Post;
import ru.ulstu.is.sbapp.User.model.User;
import java.util.Objects;
@Entity
public class Comment {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@NotBlank(message = "Text cannot be null")
private String Text;
@ManyToOne(fetch = FetchType.EAGER,cascade = CascadeType.MERGE)
private Post post;
@ManyToOne(fetch = FetchType.EAGER,cascade = CascadeType.MERGE)
private User user;
public Comment()
{
}
public Comment(String text)
{
this.Text=text;
}
public Long getId()
{
return id;
}
public String getText() {return Text;}
public void setText(String text){this.Text=text;}
public User getUser()
{
return user;
}
public Post getPost()
{
return post;
}
public void setPost(Post post, User user){
if(post!=null)
{
post.getComments().add(this);
this.post = post;
this.user = user;
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Comment comment = (Comment) o;
return Objects.equals(id, comment.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
@Override
public String toString() {
return "Comment{" +
"id=" + id +
", Text='" + Text + '\'' +
'}';
}
}

View File

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

View File

@ -0,0 +1,7 @@
package ru.ulstu.is.sbapp.Comment.service;
public class CommentNotFoundException extends RuntimeException{
public CommentNotFoundException(Long id) {
super(String.format("Comment with id [%s] is not found", id));
}
}

View File

@ -0,0 +1,68 @@
package ru.ulstu.is.sbapp.Comment.service;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ru.ulstu.is.sbapp.Comment.model.Comment;
import ru.ulstu.is.sbapp.Comment.repository.CommentRepository;
import ru.ulstu.is.sbapp.Util.validation.ValidatorUtil;
import java.util.List;
import java.util.Optional;
@Service
public class CommentService {
private final CommentRepository commentRepository;
private final ValidatorUtil validatorUtil;
public CommentService(CommentRepository commentRepository, ValidatorUtil validatorUtil)
{
this.commentRepository=commentRepository;
this.validatorUtil=validatorUtil;
}
@Transactional
public Comment addComment(String Text) {
final Comment comment = new Comment(Text);
validatorUtil.validate(comment);
return commentRepository.save(comment);
}
@Transactional
public void saveComment(Comment comment) {
commentRepository.save(comment);
}
@Transactional(readOnly = true)
public Comment findComment(Long id) {
final Optional<Comment> client = commentRepository.findById(id);
return client.orElseThrow(() -> new CommentNotFoundException(id));
}
@Transactional(readOnly = true)
public List<Comment> findAllComments() {
return commentRepository.findAll();
}
@Transactional
public Comment updateComment(Long id,String Text) {
final Comment currentComment = findComment(id);
currentComment.setText(Text);
validatorUtil.validate(currentComment);
return commentRepository.save(currentComment);
}
@Transactional
public Comment deleteComment(Long id) {
final Comment currentComment = findComment(id);
commentRepository.delete(currentComment);
return currentComment;
}
@Transactional
public void deleteAllComments() {
commentRepository.deleteAll();
}
}

View File

@ -0,0 +1,77 @@
package ru.ulstu.is.sbapp.Post.controller;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*;
import ru.ulstu.is.sbapp.Comment.controller.CommentDto;
import ru.ulstu.is.sbapp.Post.model.Post;
import ru.ulstu.is.sbapp.Post.service.PostService;
import ru.ulstu.is.sbapp.User.controller.UserDto;
import ru.ulstu.is.sbapp.User.service.UserService;
import java.util.List;
@RestController
@RequestMapping("/post")
public class PostController {
private final PostService postService;
public PostController(PostService postService) {
this.postService = postService;
}
@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();
}
@GetMapping("/{id}/comments")
public List<CommentDto> getComments(@PathVariable Long id) {
return postService.GetPostComments(id).stream()
.map(CommentDto::new)
.toList();
}
@PostMapping
public PostDto createPost(@RequestBody @Valid PostDto postDto){
return new PostDto(postService.addPost(postDto));
}
@PutMapping("/{id}")
public PostDto updatePost(@PathVariable Long id,
@RequestBody @Valid PostDto postDto){
return new PostDto(postService.updatePost(id,postDto));
}
@PostMapping("/{id}/Comment/{userId}")
public void addComment(@PathVariable Long id,
@PathVariable Long userId,
@RequestParam("Text") String Text) {
postService.addCommentToPost(id, userId,Text);
}
@DeleteMapping("/{id}/Comment/{commentId}")
public void removeComment(@PathVariable Long id,
@PathVariable Long commentId)
{
postService.removeCommentFromPost(id,commentId);
}
@DeleteMapping("/{id}")
public void deletePost(@PathVariable Long id) {
postService.deletePost(id);
}
@DeleteMapping
public void deleteall()
{
postService.deleteAllPosts();
}
@GetMapping("/filteredposts")
public List<PostDto> getPostsAndComments(@RequestParam("Text") String Text){
return postService.getPostsAndComments(Text).stream()
.map(PostDto::new)
.toList();
}
}

View File

@ -0,0 +1,56 @@
package ru.ulstu.is.sbapp.Post.controller;
import ru.ulstu.is.sbapp.Comment.controller.CommentDto;
import ru.ulstu.is.sbapp.Comment.model.Comment;
import ru.ulstu.is.sbapp.Post.model.Post;
import ru.ulstu.is.sbapp.User.model.User;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
public class PostDto {
private Long id;
private String heading;
private String content;
private List<CommentDto> comments = new ArrayList<>();
private String image;
public PostDto(){}
public PostDto(Post post) {
this.id = post.getId();
this.heading = post.getHeading();
this.content = post.getContent();
this.image = new String(post.getImage(), StandardCharsets.UTF_8);
if (post.getComments() != null) {
comments = post.getComments().stream()
.map(CommentDto::new).toList();
}
}
public Long getId()
{
return id;
}
public String getHeading()
{
return heading;
}
public String getContent()
{
return content;
}
public List<CommentDto> getComments()
{
return comments;
}
public String getImage() {
return image;
}
}

View File

@ -0,0 +1,110 @@
package ru.ulstu.is.sbapp.Post.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import jakarta.persistence.*;
import jakarta.validation.constraints.NotBlank;
import ru.ulstu.is.sbapp.Comment.model.Comment;
import ru.ulstu.is.sbapp.Post.controller.PostDto;
import ru.ulstu.is.sbapp.User.model.User;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
@Entity
public class Post {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column
@NotBlank(message = "heading cannot be null")
private String heading;
@NotBlank(message = "content cannot be null")
private String content;
@Lob
private byte[] image;
@ManyToOne(fetch = FetchType.EAGER,cascade = CascadeType.MERGE)
private User user;
@OneToMany(mappedBy = "post",fetch = FetchType.EAGER,cascade = {CascadeType.MERGE,CascadeType.REMOVE},orphanRemoval = true)
private List<Comment> comments=new ArrayList<>();
public Post(){}
public Post(String Heading, String Content,byte[] image)
{
this.heading = Heading;
this.content = Content;
this.image=image;
}
public Post(PostDto postDto) {
this.heading = postDto.getHeading();
this.content = postDto.getContent();
this.image = postDto.getImage().getBytes();
}
public Long getId()
{
return id;
}
public String getHeading()
{
return heading;
}
public String getContent()
{
return content;
}
public void setHeading(String Heading){
this.heading =Heading;
}
public void setContent(String Content)
{
this.content = Content;
}
public void setUser(User user) {
this.user = user;
}
public User getUser()
{
return user;
}
public byte[] getImage() {
return image;
}
public void setImage(byte[] image) {
this.image = image;
}
public void deleteUser() {
this.user = null;
}
public List<Comment> getComments()
{
return comments;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Post post = (Post) o;
return Objects.equals(id, post.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
@Override
public String toString() {
return "Post{" +
"id=" + id +
", heading='" + heading + '\'' +
", content ='" + content + '\'' +
'}';
}
}

View File

@ -0,0 +1,20 @@
package ru.ulstu.is.sbapp.Post.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import ru.ulstu.is.sbapp.Comment.model.Comment;
import ru.ulstu.is.sbapp.Post.model.Post;
import java.util.List;
import java.util.Optional;
public interface PostRepository extends JpaRepository<Post, Long>{
@Query("Select c from Comment c where post.id = :id")
List<Comment> getPostComments(Long id);
@Query("Select p from Post p join p.comments c Where p.content Like concat('%', :text, '%') or c.Text Like concat('%', :text, '%')")
List<Post> getPostsAndComments(String text);
}

View File

@ -0,0 +1,7 @@
package ru.ulstu.is.sbapp.Post.service;
public class PostNotFoundException extends RuntimeException{
public PostNotFoundException(Long id) {
super(String.format("Post with id [%s] is not found", id));
}
}

View File

@ -0,0 +1,105 @@
package ru.ulstu.is.sbapp.Post.service;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ru.ulstu.is.sbapp.Comment.model.Comment;
import ru.ulstu.is.sbapp.Comment.service.CommentService;
import ru.ulstu.is.sbapp.Post.controller.PostDto;
import ru.ulstu.is.sbapp.Post.model.Post;
import ru.ulstu.is.sbapp.Post.repository.PostRepository;
import ru.ulstu.is.sbapp.User.service.UserService;
import ru.ulstu.is.sbapp.Util.validation.ValidatorUtil;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Optional;
@Service
public class PostService {
private final PostRepository postRepository;
private final CommentService commentService;
private final UserService userService;
private final ValidatorUtil validatorUtil;
public PostService(PostRepository postRepository, CommentService commentService, ValidatorUtil validatorUtil, UserService userService)
{
this.postRepository=postRepository;
this.commentService = commentService;
this.validatorUtil=validatorUtil;
this.userService = userService;
}
@Transactional
public Post addPost(PostDto postDto) {
final Post post = new Post(postDto);
validatorUtil.validate(post);
return postRepository.save(post);
}
@Transactional
public void savePost(Post post) {
postRepository.save(post);
}
@Transactional(readOnly = true)
public Post findPost(Long id) {
final Optional<Post> post = postRepository.findById(id);
return post.orElseThrow(() -> new PostNotFoundException(id));
}
@Transactional(readOnly = true)
public List<Post> findAllPosts() {
return postRepository.findAll();
}
@Transactional
public Post updatePost(Long id, PostDto postDto) {
final Post currentPost = findPost(id);
currentPost.setHeading(postDto.getHeading());
currentPost.setContent(postDto.getContent());
currentPost.setImage(postDto.getImage().getBytes(StandardCharsets.UTF_8));
validatorUtil.validate(currentPost);
return postRepository.save(currentPost);
}
@Transactional
public List<Comment> GetPostComments(Long id)
{
return postRepository.getPostComments(id);
}
@Transactional
public void deletePost(Long id) {
postRepository.deleteById(id);
}
@Transactional
public void deleteAllPosts() {
commentService.deleteAllComments();
postRepository.deleteAll();
}
@Transactional
public void addCommentToPost(Long id, Long userId, String text){
Optional<Post> optionalPost = postRepository.findById(id);
if(optionalPost.isPresent()) {
Comment comment = new Comment(text);
comment.setPost(optionalPost.get(), userService.findUser(userId));
commentService.saveComment(comment);
}
postRepository.save(optionalPost.get());
}
@Transactional
public void removeCommentFromPost(Long id, Long commentId){
Comment optionalComment = commentService.findComment(commentId);
optionalComment.setPost(null, null);
Optional <Post> postOptional = postRepository.findById(id);
postOptional.get().getComments().remove(optionalComment);
commentService.deleteComment(commentId);
}
@Transactional
public List<Post> getPostsAndComments(String text)
{
return postRepository.getPostsAndComments(text);
}
}

View File

@ -2,20 +2,10 @@ package ru.ulstu.is.sbapp;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
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 SbappApplication {
public static void main(String[] args) {
SpringApplication.run(SbappApplication.class, args);
}
@GetMapping("/String")
public String Vvod(@RequestParam(value = "str", defaultValue = "none") String str) {
return String.format("Вы ввели %s!", str);
}
}

View File

@ -0,0 +1,65 @@
package ru.ulstu.is.sbapp.User.controller;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*;
import ru.ulstu.is.sbapp.Post.controller.PostDto;
import ru.ulstu.is.sbapp.Post.model.Post;
import ru.ulstu.is.sbapp.User.service.UserService;
import java.util.List;
@RestController
@RequestMapping("/user")
public class UserController {
private final UserService userService;
public UserController(UserService userService) {
this.userService = userService;
}
@GetMapping("/{id}")
public UserDto getUser(@PathVariable Long id) {
return new UserDto(userService.findUser(id));
}
@GetMapping
public List<UserDto> getUsers() {
return userService.findAllUsers().stream()
.map(UserDto::new)
.toList();
}
@GetMapping("/{id}/posts")
public List<PostDto> getPosts(@PathVariable Long id) {
return userService.GetUserPosts(id).stream()
.map(PostDto::new)
.toList();
}
@PostMapping
public UserDto createUser(@RequestParam("firstName") String firstName,
@RequestParam("lastName") String lastname,
@RequestParam("email") String email) {
return new UserDto(userService.addUser(firstName, lastname,email));
}
@PutMapping("/{id}")
public UserDto updateClient(@PathVariable Long id,
@RequestParam("firstName") String firstName,
@RequestParam("lastName") String lastname,
@RequestParam("email") String email){
return new UserDto(userService.updateUser(id, firstName, lastname,email));
}
@PostMapping("/{id}/Post")
public void addPost(@PathVariable Long id,
@RequestBody @Valid PostDto postDto) {
userService.addNewPost(id, postDto);
}
@DeleteMapping("/{id}/Post/{postId}")
public void removePost(@PathVariable Long id,
@PathVariable Long postId)
{
userService.deletePost(id,postId);
}
@DeleteMapping("/{id}")
public void deleteUser(@PathVariable Long id) {
userService.deleteUser(id);
}
}

View File

@ -0,0 +1,55 @@
package ru.ulstu.is.sbapp.User.controller;
import ru.ulstu.is.sbapp.Comment.model.Comment;
import ru.ulstu.is.sbapp.Post.model.Post;
import ru.ulstu.is.sbapp.User.model.User;
import java.util.ArrayList;
import java.util.List;
public class UserDto {
private Long id;
private String firstName;
private String lastName;
private String email;
private List<Post> posts = new ArrayList<>();
private List<Comment> comments = new ArrayList<>();
public UserDto(){}
public UserDto(User user) {
this.id=user.getId();
this.firstName = user.getFirstName();
this.lastName = user.getLastName();
this.email= user.getEmail();
}
public Long getId() {
return id;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public List<Post> getPosts()
{
return posts;
}
public List<Comment> getComments()
{
return comments;
}
public String getEmail()
{
return email;
}
}

View File

@ -0,0 +1,107 @@
package ru.ulstu.is.sbapp.User.model;
import jakarta.persistence.*;
import jakarta.validation.constraints.NotBlank;
import ru.ulstu.is.sbapp.Comment.model.Comment;
import ru.ulstu.is.sbapp.Post.model.Post;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
@Entity
@Table(name="tab_user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column()
@NotBlank(message = "firstName cannot be null")
private String firstName;
@NotBlank(message = "lastName cannot be null")
private String lastName;
@NotBlank(message = "email cannot be null")
private String email;
@OneToMany(mappedBy ="user",cascade = {CascadeType.MERGE,CascadeType.REMOVE},fetch = FetchType.EAGER)
private List<Post> posts =new ArrayList<>();
@OneToMany(mappedBy ="user",cascade = {CascadeType.MERGE,CascadeType.REMOVE},fetch = FetchType.EAGER)
private List<Comment> comments =new ArrayList<>();
public User() {
}
public User(String firstName, String lastName, String email) {
this.firstName = firstName;
this.lastName = lastName;
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 List<Post> getPosts()
{
return posts;
}
public List<Comment> getComments()
{
return comments;
}
public void addNewPost(Post post) {
posts.add(post);
post.setUser(this);
}
public String getEmail()
{
return email;
}
public void setEmail(String email){
this.email=email;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
return Objects.equals(id, user.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
@Override
public String toString() {
return "Client{" +
"id=" + id +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", email='" + email + '\'' +
", posts=" + posts +'\''+
'}';
}
}

View File

@ -0,0 +1,15 @@
package ru.ulstu.is.sbapp.User.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import ru.ulstu.is.sbapp.Post.model.Post;
import ru.ulstu.is.sbapp.User.model.User;
import java.util.List;
public interface UserRepository extends JpaRepository<User, Long> {
@Query("Select p from Post p where user.id = :id")
List<Post> getUsersPosts(Long id);
}

View File

@ -0,0 +1,7 @@
package ru.ulstu.is.sbapp.User.service;
public class UserNotFoundException extends RuntimeException{
public UserNotFoundException(Long id) {
super(String.format("User with id [%s] is not found", id));
}
}

View File

@ -0,0 +1,95 @@
package ru.ulstu.is.sbapp.User.service;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ru.ulstu.is.sbapp.Comment.service.CommentService;
import ru.ulstu.is.sbapp.Post.controller.PostDto;
import ru.ulstu.is.sbapp.Post.model.Post;
import ru.ulstu.is.sbapp.Post.repository.PostRepository;
import ru.ulstu.is.sbapp.Post.service.PostService;
import ru.ulstu.is.sbapp.User.model.User;
import ru.ulstu.is.sbapp.User.repository.UserRepository;
import ru.ulstu.is.sbapp.Util.validation.ValidatorUtil;
import java.util.List;
import java.util.Optional;
@Service
public class UserService {
private final UserRepository userRepository;
private final PostRepository postRepository;
private final CommentService commentService;
private final ValidatorUtil validatorUtil;
public UserService(UserRepository userRepository, ValidatorUtil validatorUtil, PostRepository postRepository, CommentService commentService)
{
this.userRepository=userRepository;
this.validatorUtil=validatorUtil;
this.postRepository = postRepository;
this.commentService = commentService;
}
@Transactional
public User addUser(String firstName, String lastName, String email) {
final User user = new User(firstName, lastName, email);
validatorUtil.validate(user);
return userRepository.save(user);
}
@Transactional(readOnly = true)
public User findUser(Long id) {
final Optional<User> user = userRepository.findById(id);
return user.orElseThrow(() -> new UserNotFoundException(id));
}
@Transactional(readOnly = true)
public List<User> findAllUsers() {
return userRepository.findAll();
}
@Transactional
public User updateUser(Long id, String firstName, String lastName, String email) {
final User currentUser = findUser(id);
currentUser.setFirstName(firstName);
currentUser.setLastName(lastName);
currentUser.setEmail(email);
validatorUtil.validate(currentUser);
return userRepository.save(currentUser);
}
@Transactional
public void deleteUser(Long id) {
userRepository.deleteById(id);
}
@Transactional
public void deleteAllUsers() {
commentService.deleteAllComments();
postRepository.deleteAll();
userRepository.deleteAll();
}
@Transactional
public void addNewPost(Long id, PostDto postDto)
{
Optional<User> currentUser = userRepository.findById(id);
if(currentUser.isPresent())
{
Post post = new Post(postDto);
post.setUser(currentUser.get());
postRepository.save(post);
}
}
@Transactional
public List<Post> GetUserPosts(Long id)
{
return userRepository.getUsersPosts(id);
}
@Transactional
public void deletePost(Long id, Long postId) {
postRepository.deleteById(postId);
}
}

View File

@ -0,0 +1,41 @@
package ru.ulstu.is.sbapp.Util.error;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import ru.ulstu.is.sbapp.Comment.service.CommentNotFoundException;
import ru.ulstu.is.sbapp.Post.service.PostNotFoundException;
import ru.ulstu.is.sbapp.User.service.UserNotFoundException;
import ru.ulstu.is.sbapp.Util.validation.ValidationException;
import java.util.stream.Collectors;
@ControllerAdvice
public class AdviceController {
@ExceptionHandler({
CommentNotFoundException.class,
UserNotFoundException.class,
PostNotFoundException.class,
ValidationException.class
})
public ResponseEntity<Object> handleException(Throwable e) {
return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<Object> handleBindException(MethodArgumentNotValidException e) {
final ValidationException validationException = new ValidationException(
e.getBindingResult().getAllErrors().stream()
.map(DefaultMessageSourceResolvable::getDefaultMessage)
.collect(Collectors.toSet()));
return handleException(validationException);
}
@ExceptionHandler(Exception.class)
public ResponseEntity<Object> handleUnknownException(Throwable e) {
e.printStackTrace();
return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}

View File

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

View File

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

View File

@ -1 +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=sa
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,112 @@
/*
package ru.ulstu.is.sbapp;
import jakarta.persistence.EntityNotFoundException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import ru.ulstu.is.sbapp.Comment.model.Comment;
import ru.ulstu.is.sbapp.Post.model.Post;
import ru.ulstu.is.sbapp.Post.service.PostNotFoundException;
import ru.ulstu.is.sbapp.Post.service.PostService;
import ru.ulstu.is.sbapp.User.model.User;
import ru.ulstu.is.sbapp.User.service.UserNotFoundException;
import ru.ulstu.is.sbapp.User.service.UserService;
import java.util.Arrays;
import java.util.List;
@SpringBootTest
public class JpaClientTests {
private static final Logger log = LoggerFactory.getLogger(JpaClientTests.class);
@Autowired
private UserService userService;
@Autowired
private PostService postService;
@Test
void testClientCreate() {
userService.deleteAllUsers();
final User user = userService.addUser("Pasha","Sorokin","sorokin.zxcv@gmail.com");
log.info("testUserCreate: " + user.toString());
Assertions.assertNotNull(user.getId());
userService.deleteAllUsers();
}
@Test
void testReadClient()
{
userService.deleteAllUsers();
final User user = userService.addUser("Pasha","Sorokin","sorokin.zxcv@gmail.com");
log.info("testUserRead[0]: " + user.toString());
final User curuser=userService.findUser(user.getId());
log.info("testUserRead[1]: " + curuser.toString());
Assertions.assertEquals(user, curuser);
userService.deleteAllUsers();
}
@Test
void testClientReadNotFound() {
userService.deleteAllUsers();
Assertions.assertThrows(UserNotFoundException.class, () -> userService.findUser(-1L));
}
@Test
void testClientReadAll() {
userService.deleteAllUsers();
userService.addUser("Pupa","Lupa","sasdfdsf@gmail.com");
userService.addUser("Pasha","Sorokin","sorokin.zxcv@gmail.com");
final List<User> users = userService.findAllUsers();
log.info("testUserReadAll: " + users.toString());
Assertions.assertEquals(users.size(), 2);
userService.deleteAllUsers();
}
@Test
void testClientReadAllEmpty() {
userService.deleteAllUsers();
final List<User> users = userService.findAllUsers();
log.info("testUserReadAllEmpty: " + users.toString());
Assertions.assertEquals(users.size(), 0);
}
@Test
void testDeletePostwithcomments()
{
final User user = userService.addUser("Pasha","Sorokin","sorokin.zxcv@gmail.com");
final User user12 = userService.addUser("Anton","Sorokin","zxcv@gmail.com");
userService.addNewPost(user.getId(),"text","tezt");
final List<Post> post = postService.findAllPosts();
final Post post1 = post.get(0);
postService.addCommentToPost(post1.getId(),user12.getId(),"Da");
userService.deleteUser(user.getId());
}
@Test
void testAddAndDeletePost()
{
postService.deleteAllPosts();
userService.deleteAllUsers();
final User user = userService.addUser("Pasha","Sorokin","sorokin.zxcv@gmail.com");
final User user12 = userService.addUser("Anton","Sorokin","zxcv@gmail.com");
userService.addNewPost(user.getId(),"Text1","Text2"); //post
userService.addNewPost(user.getId(),"Привет","Да"); //post1
final List<Post> posts =postService.findAllPosts();
final User user1 = userService.findUser(user.getId());
final List<Post> posts1 = user1.getPosts();
log.info("testAddAndDeletePost :: ADD " + posts.toString() + " and " + posts1.toString());
Assertions.assertEquals(posts.get(0).getUser(), user);
Assertions.assertEquals(posts.toString(), posts1.toString());
log.info("testAddAndDeletePost :: Delete ");
userService.deletePost(user.getId(),posts.get(0).getId());
final User us = userService.findUser(user.getId());
Assertions.assertThrows(PostNotFoundException.class, () -> postService.findPost(posts.get(0).getId()));
final List<Post> postss =postService.findAllPosts();
log.info(us.getPosts().toString());
log.info(postss.toString());
userService.deleteAllUsers();
postService.deleteAllPosts();
}
//посты и коментарии содержащие определенный текст
}
*/

View File

@ -0,0 +1,86 @@
/*
package ru.ulstu.is.sbapp;
import jakarta.persistence.EntityNotFoundException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import ru.ulstu.is.sbapp.Comment.controller.CommentDto;
import ru.ulstu.is.sbapp.Comment.model.Comment;
import ru.ulstu.is.sbapp.Comment.service.CommentNotFoundException;
import ru.ulstu.is.sbapp.Comment.service.CommentService;
import ru.ulstu.is.sbapp.User.service.UserService;
import java.util.Date;
import java.util.List;
@SpringBootTest
public class JpaCommentTest {
private static final Logger log = LoggerFactory.getLogger(JpaCommentTest.class);
@Autowired
private CommentService commentService;
@Test
void testTidingCreate()
{
commentService.deleteAllComments();
final Comment comment=commentService.addComment("Net");
log.info("testCommentCreate: " + comment.toString());
Assertions.assertNotNull(comment.getId());
commentService.deleteAllComments();
}
@Test
void testTidingRead()
{
commentService.deleteAllComments();
final Comment comment=commentService.addComment("Net");
log.info("testCommentRead[0]: " + comment.toString());
final Comment findComment=commentService.findComment(comment.getId());
log.info("testCommentRead[1]: " + findComment.toString());
Assertions.assertEquals(comment, findComment);
commentService.deleteAllComments();
}
@Test
void testTidingReadNotFound() {
commentService.deleteAllComments();
Assertions.assertThrows(CommentNotFoundException.class, () -> commentService.findComment(-1L));
}
@Test
void testAllTidingRead()
{
commentService.deleteAllComments();
commentService.addComment("Net");
commentService.addComment("yep");
final List<Comment> comments = commentService.findAllComments();
log.info("testAllCommentRead: " + comments.toString());
Assertions.assertEquals(comments.size(), 2);
commentService.deleteAllComments();
}
@Test
void testTidingReadAllEmpty() {
commentService.deleteAllComments();
final List<Comment> comments = commentService.findAllComments();
log.info("testCommentReadAllEmpty: " + comments.toString());
Assertions.assertEquals(comments.size(), 0);
}
@Test
void testUpdateTiding()
{
commentService.deleteAllComments();
final Comment comment=commentService.addComment("Net");
log.info("testUpdateComment: " + comment.toString());
commentService.updateComment(comment.getId(),"Ladno");
final Comment comment1=commentService.findComment(comment.getId());
log.info("testUpdateComment: " + comment1.toString());
Assertions.assertEquals(comment1.getText(), "Ladno");
commentService.deleteAllComments();
}
}
*/

View File

@ -0,0 +1,155 @@
/*
package ru.ulstu.is.sbapp;
import jakarta.persistence.EntityNotFoundException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import ru.ulstu.is.sbapp.Comment.model.Comment;
import ru.ulstu.is.sbapp.Comment.service.CommentService;
import ru.ulstu.is.sbapp.Post.model.Post;
import ru.ulstu.is.sbapp.Post.service.PostNotFoundException;
import ru.ulstu.is.sbapp.Post.service.PostService;
import ru.ulstu.is.sbapp.User.model.User;
import ru.ulstu.is.sbapp.User.service.UserService;
import java.util.List;
@SpringBootTest
public class JpaPostTests {
private static final Logger log = LoggerFactory.getLogger(JpaPostTests.class);
@Autowired
private CommentService commentService;
@Autowired
private UserService userService;
@Autowired
private PostService postService;
@Test
void TestAddPost(){
postService.deleteAllPosts();
final Post post = postService.addPost("Test","Test");
Assertions.assertNotNull(post.getId());
}
@Test
void TestFindPost(){
postService.deleteAllPosts();
final Post post = postService.addPost("Test","Test");
final Post findPost = postService.findPost(post.getId());
Assertions.assertEquals(post, findPost);
}
@Test
void TestPostReadNotFound(){
postService.deleteAllPosts();
Assertions.assertThrows(PostNotFoundException.class, () -> postService.findPost(-1L));
}
@Test
void TestFindAllPost(){
postService.deleteAllPosts();
final Post firstPost = postService.addPost("Test1","Test1");
final Post secondPost = postService.addPost("Test2","Test2");
final List<Post> posts = postService.findAllPosts();
Assertions.assertEquals(posts.size(), 2);
}
@Test
void TestPostReadAllEmpty() {
postService.deleteAllPosts();
final List<Post> posts = postService.findAllPosts();
Assertions.assertEquals(posts.size(), 0);
}
@Test
void TestPostUpdate(){
postService.deleteAllPosts();
Post post = postService.addPost("Test1", "Test1");
post = postService.updatePost(post.getId(), "Test2", "Test2");
Assertions.assertEquals(post.getHeading(), "Test2");
Assertions.assertEquals(post.getContent(), "Test2");
}
@Test
void TestDeleteAllPosts()
{
log.info("Удаление всех постов");
Post post = postService.addPost("Test1", "Test1");
Post post2 = postService.addPost("Test1", "Test1");
List<Post> posts1 = postService.findAllPosts();
log.info(posts1.toString());
postService.deleteAllPosts();
List<Post> posts = postService.findAllPosts();
log.info(posts.toString());
}
@Test
void TestDeletePost(){
postService.deleteAllPosts();
final Post post = postService.addPost("Test","Test");
postService.deletePost(post.getId());
Assertions.assertThrows(PostNotFoundException.class, () -> postService.findPost(1L));
}
@Test
void TestAddComment()
{
log.info("Добавление комментария");
postService.deleteAllPosts();
userService.deleteAllUsers();
final User user = userService.addUser("Pasha","Sorokin","sorokin.zxcv@gmail.com");
userService.addNewPost(user.getId(),"Text1","Text2");
final User user2=userService.findUser(user.getId());
log.info(user2.getPosts().toString());
final List<Post> posts = postService.findAllPosts();
final Post post2=postService.findPost(posts.get(0).getId());
log.info(post2.toString());
postService.addCommentToPost(posts.get(0).getId(),user.getId(),"Крутой пост");
final List<Comment> comments = commentService.findAllComments();
log.info(comments.toString());
final User user1=userService.findUser(user.getId());
log.info(user1.getComments().toString());
final Post post1=postService.findPost(posts.get(0).getId());
log.info(post1.getComments().toString());
}
@Test
void TestDeleteCommentFromPost()
{
log.info("Удаление коммента");
postService.deleteAllPosts();
userService.deleteAllUsers();
final User user = userService.addUser("Pasha","Sorokin","sorokin.zxcv@gmail.com");
userService.addNewPost(user.getId(),"Text1","Text2");
final User user2=userService.findUser(user.getId());
log.info("Посты юзера (добавили)"+user2.getPosts().toString());
final List<Post> posts = postService.findAllPosts();
final Post post2=postService.findPost(posts.get(0).getId());
log.info("Пост который добавили"+post2.toString());
postService.addCommentToPost(posts.get(0).getId(),user.getId(),"Крутой пост");
postService.addCommentToPost(posts.get(0).getId(),user.getId(),"Пост плохой");
final List<Comment> comments = commentService.findAllComments();
log.info("Добавили коммент"+comments.toString());
final User user1=userService.findUser(user.getId());
log.info("Комменты юзера"+user1.getComments().toString());
final Post post1=postService.findPost(posts.get(0).getId());
log.info("Комменты к посту"+post1.getComments().toString());
Comment comment1 = commentService.findComment(comments.get(0).getId());
log.info("Удаляем коммент");
postService.removeCommentFromPost(posts.get(0).getId(),comment1.getId());
final User user3=userService.findUser(user.getId());
log.info(user3.getPosts().toString());
log.info("Комменты юзера после удаления"+user3.getComments().toString());
final Post post3 = postService.findPost(posts.get(0).getId());
log.info(post3.toString());
log.info(post3.getComments().toString());
final List<Comment> comment4=commentService.findAllComments();
log.info(comment4.toString());
commentService.deleteAllComments();
postService.deleteAllPosts();
userService.deleteAllUsers();
}
}
*/

View File

@ -1,13 +0,0 @@
package ru.ulstu.is.sbapp;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class SbappApplicationTests {
@Test
void contextLoads() {
}
}

View File

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