Compare commits
9 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 9b3faa72e2 | |||
| 0e637791ef | |||
| 93464f7382 | |||
| 72166d3a35 | |||
| c8f79a0d98 | |||
| a3de182a22 | |||
| 1423f5da0b | |||
| 21c085917a | |||
| f3f0e851ed |
4
.idea/misc.xml
generated
4
.idea/misc.xml
generated
@@ -1,6 +1,10 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ExternalStorageConfigurationManager" enabled="true" />
|
||||
<component name="ProjectRootManager" version="2" languageLevel="JDK_17" project-jdk-name="openjdk-19" project-jdk-type="JavaSDK">
|
||||
<output url="file://$PROJECT_DIR$/out" />
|
||||
</component>
|
||||
<component name="ProjectType">
|
||||
<option name="id" value="jpab" />
|
||||
</component>
|
||||
</project>
|
||||
18
build.gradle
18
build.gradle
@@ -14,6 +14,24 @@ repositories {
|
||||
|
||||
dependencies {
|
||||
implementation 'org.springframework.boot:spring-boot-starter-web'
|
||||
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
|
||||
implementation 'org.springframework.boot:spring-boot-devtools'
|
||||
implementation 'nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect'
|
||||
|
||||
implementation 'org.webjars:bootstrap:5.1.3'
|
||||
implementation 'org.webjars:jquery:3.6.0'
|
||||
implementation 'org.webjars:font-awesome:6.1.0'
|
||||
|
||||
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
|
||||
implementation 'com.h2database:h2:2.1.210'
|
||||
|
||||
implementation 'org.hibernate.validator:hibernate-validator'
|
||||
|
||||
implementation 'org.springframework.boot:spring-boot-starter-security'
|
||||
implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity5'
|
||||
|
||||
implementation 'org.springdoc:springdoc-openapi-ui:1.6.5'
|
||||
|
||||
testImplementation 'org.springframework.boot:spring-boot-starter-test'
|
||||
}
|
||||
|
||||
|
||||
BIN
data.mv.db
Normal file
BIN
data.mv.db
Normal file
Binary file not shown.
@@ -1,44 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=edge">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<link rel="stylesheet" href="./node_modules/bootstrap/dist/css/bootstrap.min.css">
|
||||
<title>Калькулятор</title>
|
||||
</head>
|
||||
<body class="m-5">
|
||||
<h1>Калькулятор</h1>
|
||||
|
||||
<form class="" id="form">
|
||||
<div class="row my-3">
|
||||
<div class="col-md-3">
|
||||
<input name="num1" input type="text" class="form-control" placeholder="Первый аргумент">
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<input name="num2" input type="text" class="form-control" placeholder="Второй аргумент">
|
||||
</div>
|
||||
<div class = "col-md-2">
|
||||
<select class="form-select" name="selected" aria-label="Default select example">
|
||||
<option selected>Действие</option>
|
||||
<option value="1">+</option>
|
||||
<option value="2">-</option>
|
||||
<option value="3">*</option>
|
||||
<option value="4">/</option>
|
||||
<option value="5">%</option>
|
||||
<option value="6">con</option>
|
||||
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<button type="submit" class="btn btn-success">Выполнить</button>
|
||||
<div class="my-2 col-md-3">
|
||||
<input name="res" input type="text" class="form-control " placeholder="Результат">
|
||||
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<script src="./node_modules/bootstrap/dist/js/bootstrap.min.js"></script>
|
||||
<script src="../js/script.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,70 +0,0 @@
|
||||
let form = document.getElementById("form");
|
||||
let info = document.getElementById("res");
|
||||
|
||||
form.onsubmit = async (e) => {
|
||||
e.preventDefault();
|
||||
|
||||
if(form.num1.value === "") return;
|
||||
if(form.num2.value === "") return;
|
||||
|
||||
let index = form.selected.selectedIndex;
|
||||
let op = form.selected.options[index].textContent;
|
||||
let res = "";
|
||||
|
||||
function chooseOperation(oper){
|
||||
switch(oper){
|
||||
case "+":
|
||||
return "sum"
|
||||
case "-":
|
||||
return "diff"
|
||||
case "*":
|
||||
return "mul"
|
||||
case "/":
|
||||
return "div"
|
||||
case "%":
|
||||
return "ost"
|
||||
case "con":
|
||||
return "con"
|
||||
}
|
||||
}
|
||||
|
||||
let operstor = chooseOperation(op)
|
||||
if(form.num2.value == 0) return;
|
||||
res = await fetch(`http://localhost:8080/${operstor}?num1=${form.num1.value}&num2=${form.num2.value}`)
|
||||
res = await res.text();
|
||||
|
||||
// switch(op) {
|
||||
// case "+":
|
||||
// res = await fetch(`http://localhost:8080/sum?num1=${form.num1.value}&num2=${form.num2.value}`)
|
||||
// res = await res.text();
|
||||
// break;
|
||||
// case "-":
|
||||
// res = await fetch(`http://localhost:8080/diff?num1=${form.num1.value}&num2=${form.num2.value}`)
|
||||
// res = await res.text();
|
||||
// break;
|
||||
|
||||
// case "*":
|
||||
// res = await fetch(`http://localhost:8080/mul?num1=${form.num1.value}&num2=${form.num2.value}`)
|
||||
// res = await res.text();
|
||||
// break;
|
||||
|
||||
// case "/":
|
||||
// if(form.num2.value == 0) return;
|
||||
// res = await fetch(`http://localhost:8080/div?num1=${form.num1.value}&num2=${form.num2.value}`)
|
||||
// res = await res.text();
|
||||
// break;
|
||||
|
||||
// case "%":
|
||||
// if(form.num2.value == 0) return;
|
||||
// res = await fetch(`http://localhost:8080/ost?num1=${form.num1.value}&num2=${form.num2.value}`)
|
||||
// res = await res.text();
|
||||
// break;
|
||||
|
||||
// case "con":
|
||||
// res = await fetch(`http://localhost:8080/con?num1=${form.num1.value}&num2=${form.num2.value}`)
|
||||
// res = await res.text();
|
||||
// break;
|
||||
// }
|
||||
|
||||
form.res.value = res;
|
||||
}
|
||||
30223
front/package-lock.json
generated
30223
front/package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -1,15 +1,43 @@
|
||||
{
|
||||
"name": "front",
|
||||
"version": "1.0.0",
|
||||
"description": "",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"start": "http-server -p 3000 -c-1 -o ./"
|
||||
},
|
||||
"author": "",
|
||||
"license": "ISC",
|
||||
"name": "my-app",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"dependencies": {
|
||||
"@testing-library/jest-dom": "^5.16.5",
|
||||
"@testing-library/react": "^13.4.0",
|
||||
"@testing-library/user-event": "^13.5.0",
|
||||
"bootstrap": "^5.2.3",
|
||||
"http-server": "^14.1.1"
|
||||
"json-server": "^0.17.1",
|
||||
"npm-run-all": "^4.1.5",
|
||||
"react": "^18.2.0",
|
||||
"react-dom": "^18.2.0",
|
||||
"react-router-dom": "^6.4.5",
|
||||
"react-scripts": "5.0.1",
|
||||
"web-vitals": "^2.1.4"
|
||||
},
|
||||
"scripts": {
|
||||
"start": "react-scripts start",
|
||||
"fake-server": "json-server data.json -p 8079",
|
||||
"build": "react-scripts build",
|
||||
"test": "react-scripts test",
|
||||
"eject": "react-scripts eject"
|
||||
},
|
||||
"eslintConfig": {
|
||||
"extends": [
|
||||
"react-app",
|
||||
"react-app/jest"
|
||||
]
|
||||
},
|
||||
"browserslist": {
|
||||
"production": [
|
||||
">0.2%",
|
||||
"not dead",
|
||||
"not op_mini all"
|
||||
],
|
||||
"development": [
|
||||
"last 1 chrome version",
|
||||
"last 1 firefox version",
|
||||
"last 1 safari version"
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
47
front/src/components/catalogs/CatalogCommunities.jsx
Normal file
47
front/src/components/catalogs/CatalogCommunities.jsx
Normal file
@@ -0,0 +1,47 @@
|
||||
import Catalog from "../common/Catalog";
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
import DataService from "../../services/DataService";
|
||||
|
||||
let headers = [
|
||||
{label: "name", text: "Имя"},
|
||||
]
|
||||
|
||||
export default function CatalogActors() {
|
||||
const url = "/communities";
|
||||
|
||||
const [data, setData] = useState({
|
||||
name: "",
|
||||
});
|
||||
|
||||
const [communities, setCommunities] = useState([]);
|
||||
|
||||
function handleFormChange(e) {
|
||||
setData({ ...data, [e.target.id]: e.target.value })
|
||||
}
|
||||
|
||||
//уточнить
|
||||
function onAdd() {
|
||||
setData({name: "", music: communities[0]});
|
||||
}
|
||||
|
||||
|
||||
function onChange(data) {
|
||||
setData(data);
|
||||
}
|
||||
|
||||
function validate(data) {
|
||||
if(data.name === "") return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
return (
|
||||
<Catalog url={url} headers={headers} data={data} onAdd={onAdd} onChange={onChange} validate={validate}>
|
||||
<div className="mb-3">
|
||||
<label htmlFor="name" className="form-label">Имя</label>
|
||||
<input type="text" value={data.name} id="name" className="form-control" required autoComplete="off"
|
||||
onChange={handleFormChange}/>
|
||||
</div>
|
||||
</Catalog>
|
||||
)
|
||||
}
|
||||
169
front/src/components/catalogs/CatalogUsers.jsx
Normal file
169
front/src/components/catalogs/CatalogUsers.jsx
Normal file
@@ -0,0 +1,169 @@
|
||||
import Catalog from "../common/Catalog";
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
import DataService from "../../services/DataService"
|
||||
|
||||
let headers = [
|
||||
{label: "name", text: "Имя"},
|
||||
{label: "music", text: "Музыка"},
|
||||
{label: "community", text: "Группы"},
|
||||
{ label: "city", text: "Город" }
|
||||
]
|
||||
export default function CatalogUsers() {
|
||||
const url = "/users";
|
||||
|
||||
const [data, setData] = useState({
|
||||
name: "",
|
||||
music: [],
|
||||
community: [],
|
||||
city: ""
|
||||
});
|
||||
|
||||
const [selectedData, setSelectedData] = useState({
|
||||
music: "",
|
||||
community: ""
|
||||
});
|
||||
|
||||
const [musics, setMusics] = useState([]);
|
||||
const [communities, setCommunities] = useState([]);
|
||||
|
||||
useEffect(() => {
|
||||
let music;
|
||||
DataService.readAll("/musics").then(res => {
|
||||
setMusics(res)
|
||||
music = res[0].name;
|
||||
}).then(() => (
|
||||
DataService.readAll("/communities")
|
||||
)).then(res => {
|
||||
setCommunities(res)
|
||||
setSelectedData({music, community: res[0].name});
|
||||
});
|
||||
}, [])
|
||||
|
||||
|
||||
function handleFormChange(e) {
|
||||
console.log(e.target.value);
|
||||
setData({ ...data, [e.target.id]: e.target.value })
|
||||
}
|
||||
|
||||
function handleChangeSelected(e) {
|
||||
setSelectedData({...selectedData, [e.target.id]: e.target.value});
|
||||
}
|
||||
|
||||
function addMusic() {
|
||||
for(let g of data.music) {
|
||||
if(g == selectedData.music) return;
|
||||
}
|
||||
let temp = data.music.slice(0);
|
||||
temp.push(selectedData.music);
|
||||
setData({...data, music: temp});
|
||||
}
|
||||
|
||||
function addCommunity() {
|
||||
for(let a of data.community) {
|
||||
if(a == selectedData.community) return;
|
||||
}
|
||||
let temp = data.community.slice(0);
|
||||
temp.push(selectedData.community);
|
||||
setData({...data, community: temp});
|
||||
}
|
||||
|
||||
function deleteMusic(e) {
|
||||
let musicName = e.target.previousSibling.textContent;
|
||||
let temp = data.music.filter(x => (x != musicName));
|
||||
setData({...data, music: temp})
|
||||
}
|
||||
|
||||
function deleteCommunity(e) {
|
||||
let communityName = e.target.previousSibling.textContent;
|
||||
let temp = data.community.filter(x => (x != communityName));
|
||||
setData({...data, community: temp})
|
||||
}
|
||||
|
||||
function onAdd() {
|
||||
setData({name: "", music: [], community: []});
|
||||
}
|
||||
|
||||
|
||||
function onChange(data) {
|
||||
setData(data);
|
||||
}
|
||||
|
||||
function validate(data) {
|
||||
if(data.name === "") return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
return (
|
||||
<Catalog url={url} headers={headers} data={data} onAdd={onAdd} onChange={onChange} validate={validate}>
|
||||
<div>
|
||||
<div className="mb-3">
|
||||
<label htmlFor="name" className="form-label">Название</label>
|
||||
<input
|
||||
type="text"
|
||||
value={data.name}
|
||||
id="name"
|
||||
className="form-control"
|
||||
required
|
||||
autoComplete="off"
|
||||
onChange={handleFormChange}
|
||||
/>
|
||||
</div>
|
||||
<div className="mb-3">
|
||||
<label htmlFor="city" className="form-label">Город</label>
|
||||
<input
|
||||
type="text"
|
||||
value={data.city}
|
||||
id="city"
|
||||
className="form-control"
|
||||
required
|
||||
autoComplete="off"
|
||||
onChange={handleFormChange}
|
||||
/>
|
||||
</div>
|
||||
<select
|
||||
id="music"
|
||||
className="form-select mb-3"
|
||||
required
|
||||
value={selectedData.music}
|
||||
onChange={handleChangeSelected}
|
||||
>
|
||||
<option disabled value="">Укажите музыку</option>
|
||||
{musics.map(({ name, id }) => (
|
||||
<option key={id} value={name}>{name}</option>
|
||||
))}
|
||||
</select>
|
||||
{data.music.map(value => (
|
||||
<div className="badge bg-secondary mb-3" key={value}>
|
||||
<span>{value}</span>
|
||||
<button className="btn-close bg-danger" onClick={deleteMusic}></button>
|
||||
</div>
|
||||
))}
|
||||
|
||||
<br></br>
|
||||
<button onClick={addMusic} className="btn btn-success mb-3">Добавить музыку</button>
|
||||
|
||||
<select
|
||||
id="community"
|
||||
className="form-select mb-3"
|
||||
required
|
||||
value={selectedData.community}
|
||||
onChange={handleChangeSelected}
|
||||
>
|
||||
<option disabled value="">Укажите группу</option>
|
||||
{communities.map(({ name, id }) => (
|
||||
<option key={id} value={name}>{name}</option>
|
||||
))}
|
||||
</select>
|
||||
{data.community.map(value => (
|
||||
<div className="badge bg-secondary mb-3" key={value}>
|
||||
<span>{value}</span>
|
||||
<button className="btn-close bg-danger" onClick={deleteCommunity}></button>
|
||||
</div>
|
||||
))}
|
||||
<br></br>
|
||||
<button onClick={addCommunity} className="btn btn-success mb-3">Добавить группу</button>
|
||||
</div>
|
||||
</Catalog>
|
||||
)
|
||||
}
|
||||
15
front/src/components/pages/User.jsx
Normal file
15
front/src/components/pages/User.jsx
Normal file
@@ -0,0 +1,15 @@
|
||||
import playIcon from "../../img/play.png";
|
||||
import "./Contacts.css";
|
||||
|
||||
export default function User() {
|
||||
return (
|
||||
<main>
|
||||
<div class="player">
|
||||
<div class="player__menu">
|
||||
<button class="player__button"><img class="player__button-img" src={playIcon} alt=""/></button>
|
||||
<div class="player__progress"></div>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
)
|
||||
}
|
||||
21
front/src/components/pages/Users.jsx
Normal file
21
front/src/components/pages/Users.jsx
Normal file
@@ -0,0 +1,21 @@
|
||||
import Banner from "../Banner";
|
||||
|
||||
export default function Users() {
|
||||
return (
|
||||
<main>
|
||||
<section className="categories">
|
||||
|
||||
<h2 className="text-white">Музыка</h2>
|
||||
<div className="btn-group">
|
||||
<button className="btn btn-success">Комедии</button>
|
||||
<button className="btn btn-success">Драмы</button>
|
||||
<button className="btn btn-success">Трилер</button>
|
||||
</div>
|
||||
</section>
|
||||
<section className="banner">
|
||||
<h2 className="text-white">Все фильмы</h2>
|
||||
<Banner images={images}/>
|
||||
</section>
|
||||
</main>
|
||||
)
|
||||
}
|
||||
25
front/src/components/reports/ReportUsers.jsx
Normal file
25
front/src/components/reports/ReportUsers.jsx
Normal file
@@ -0,0 +1,25 @@
|
||||
import Catalog from "../common/Catalog";
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
import DataService from "../../services/DataService"
|
||||
import Table from "../common/Table";
|
||||
|
||||
import ReportSelector from "./ReportSelector";
|
||||
|
||||
let headers = [
|
||||
{label: "name", text: "Имя"},
|
||||
{label: "music", text: "Музыка"}
|
||||
]
|
||||
|
||||
export default function ReportsFilms() {
|
||||
const [url, setUrl] = useState("/users?music=mus1");
|
||||
|
||||
function formData(music) {
|
||||
console.log(music);
|
||||
setUrl("/users?music=" + music);
|
||||
}
|
||||
|
||||
return (
|
||||
<ReportSelector headers={headers} url={url} formData={formData}/>
|
||||
)
|
||||
}
|
||||
BIN
front/src/img/play.png
Normal file
BIN
front/src/img/play.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 54 KiB |
@@ -13,43 +13,4 @@ public class SbappApplication {
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(SbappApplication.class, args);
|
||||
}
|
||||
|
||||
@GetMapping("/hello")
|
||||
public String hello(){
|
||||
return "Hello, world";
|
||||
}
|
||||
|
||||
@GetMapping("/sum")
|
||||
public Integer sum(@RequestParam(defaultValue = "0")Integer num1,
|
||||
@RequestParam(defaultValue = "0")Integer num2){
|
||||
return num1 + num2;
|
||||
}
|
||||
@GetMapping("/div")
|
||||
public Integer div(@RequestParam(defaultValue = "0")Integer num1,
|
||||
@RequestParam(defaultValue = "0")Integer num2){
|
||||
return num1 / num2;
|
||||
}
|
||||
|
||||
@GetMapping("/mul")
|
||||
public Integer mul(@RequestParam(defaultValue = "0")Integer num1,
|
||||
@RequestParam(defaultValue = "0")Integer num2){
|
||||
return num1 * num2;
|
||||
}
|
||||
@GetMapping("/diff")
|
||||
public Integer diff(@RequestParam(defaultValue = "0")Integer num1,
|
||||
@RequestParam(defaultValue = "0")Integer num2){
|
||||
return num1 - num2;
|
||||
}
|
||||
@GetMapping("/ost")
|
||||
public Integer ost(@RequestParam(defaultValue = "0")Integer num1,
|
||||
@RequestParam(defaultValue = "0")Integer num2){
|
||||
return num1 % num2;
|
||||
}
|
||||
@GetMapping("/con")
|
||||
public String con(@RequestParam(defaultValue = "")String num1,
|
||||
@RequestParam(defaultValue = "")String num2){
|
||||
return num1.concat(num2);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -1,13 +0,0 @@
|
||||
package ru.ulstu.is.sbapp;
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.servlet.config.annotation.CorsRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
@Configuration
|
||||
public class WebConfiguration implements WebMvcConfigurer {
|
||||
@Override
|
||||
public void addCorsMappings(CorsRegistry registry) {
|
||||
registry.addMapping("/**").allowedMethods("*");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package ru.ulstu.is.sbapp.calculator.controller;
|
||||
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import ru.ulstu.is.sbapp.calculator.service.CalculatorService;
|
||||
|
||||
@RestController
|
||||
public class CalcController {
|
||||
private final CalculatorService speakerService;
|
||||
|
||||
public CalcController(CalculatorService speakerService) {
|
||||
this.speakerService = speakerService;
|
||||
}
|
||||
|
||||
@GetMapping("/sum")
|
||||
public String Sum(@RequestParam(value = "first", defaultValue = "1") Object first,
|
||||
@RequestParam(value = "second", defaultValue = "1") Object second,
|
||||
@RequestParam(value = "type", defaultValue = "int") String type) {
|
||||
return speakerService.Sum(first, second, type);
|
||||
}
|
||||
|
||||
@GetMapping("/minus")
|
||||
public String Ras(@RequestParam(value = "first", defaultValue = "1") Object first,
|
||||
@RequestParam(value = "second", defaultValue = "1") Object second,
|
||||
@RequestParam(value = "type", defaultValue = "int") String type) {
|
||||
return speakerService.Ras(first, second, type);
|
||||
}
|
||||
|
||||
@GetMapping("/reverse")
|
||||
public String Pros(@RequestParam(value = "first", defaultValue = "1") Object first,
|
||||
@RequestParam(value = "second", defaultValue = "1") Object second,
|
||||
@RequestParam(value = "type", defaultValue = "int") String type) {
|
||||
return speakerService.Rev(first, second, type);
|
||||
}
|
||||
|
||||
@GetMapping("/comparison")
|
||||
public String Del(@RequestParam(value = "first", defaultValue = "1") Object first,
|
||||
@RequestParam(value = "second", defaultValue = "1") Object second,
|
||||
@RequestParam(value = "type", defaultValue = "int") String type) {
|
||||
return speakerService.Com(first, second, type);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package ru.ulstu.is.sbapp.calculator.domain;
|
||||
|
||||
public interface Calculator<T>{
|
||||
public T Sum(T first, T second);
|
||||
|
||||
public T Minus(T first, T second);
|
||||
|
||||
public T Reverse(T first, T second);
|
||||
|
||||
public T Comparison(T first, T second);
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package ru.ulstu.is.sbapp.calculator.domain;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
|
||||
|
||||
@Component(value="date")
|
||||
public class DateCalculator implements Calculator<LocalDate> {
|
||||
|
||||
@Override
|
||||
public LocalDate Sum(LocalDate first, LocalDate second) {
|
||||
return first.plusYears(second.getYear()).
|
||||
plusMonths(second.getMonthValue()).plusDays(second.getDayOfMonth());
|
||||
}
|
||||
|
||||
@Override
|
||||
public LocalDate Minus(LocalDate first, LocalDate second) {
|
||||
return first.minusYears(second.getYear()).
|
||||
minusMonths(second.getMonthValue()).minusDays(second.getDayOfMonth());
|
||||
}
|
||||
|
||||
@Override
|
||||
public LocalDate Reverse(LocalDate first, LocalDate second) {
|
||||
|
||||
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
|
||||
String formattedFirst = first.format(formatter);
|
||||
return LocalDate.parse(formattedFirst, formatter);
|
||||
}
|
||||
|
||||
@Override
|
||||
public LocalDate Comparison(LocalDate first, LocalDate second) {
|
||||
int comparisonResult = first.compareTo(second);
|
||||
|
||||
if (comparisonResult < 0)
|
||||
return second;
|
||||
else return first;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package ru.ulstu.is.sbapp.calculator.domain;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component(value="int")
|
||||
public class IntCalculator implements Calculator<Integer>{
|
||||
@Override
|
||||
public Integer Sum(Integer x, Integer y) {
|
||||
return x + y;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Integer Minus(Integer x, Integer y) {
|
||||
return x - y;
|
||||
}
|
||||
@Override
|
||||
public Integer Reverse(Integer first, Integer second) {
|
||||
return (first + second) * (-1);
|
||||
}
|
||||
@Override
|
||||
public Integer Comparison(Integer first, Integer second) {
|
||||
if (first >= second)
|
||||
return first;
|
||||
else return second;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package ru.ulstu.is.sbapp.calculator.domain;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component(value="string")
|
||||
public class StringCalculator implements Calculator<String>{
|
||||
|
||||
@Override
|
||||
public String Sum(String first, String second) {
|
||||
return first.concat(second);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String Minus(String first, String second) {
|
||||
String[] arr = first.split("");
|
||||
for(int i = 0; i < first.length(); i++){
|
||||
if (second.contains(arr[i])){
|
||||
arr[i] = "";
|
||||
}
|
||||
}
|
||||
return String.join("", arr);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String Reverse(String first, String second) {
|
||||
String ourStr = first.concat(second);
|
||||
StringBuilder newStr = new StringBuilder();
|
||||
for(int i = ourStr.length() - 1; i >= 0; i--){
|
||||
newStr.append(ourStr.charAt(i));
|
||||
}
|
||||
return newStr.toString();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String Comparison(String first, String second) {
|
||||
if (first.length() >= second.length())
|
||||
return first;
|
||||
else return second;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package ru.ulstu.is.sbapp.calculator.service;
|
||||
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.stereotype.Service;
|
||||
import ru.ulstu.is.sbapp.calculator.domain.Calculator;
|
||||
import ru.ulstu.is.sbapp.calculator.domain.DateCalculator;
|
||||
import ru.ulstu.is.sbapp.calculator.domain.StringCalculator;
|
||||
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.time.LocalDate;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
|
||||
@Service
|
||||
public class CalculatorService {
|
||||
private final ApplicationContext _applicationContext;
|
||||
|
||||
public CalculatorService(ApplicationContext applicationContext) {
|
||||
this._applicationContext = applicationContext;
|
||||
}
|
||||
|
||||
public String Sum(Object first, Object second, String type) {
|
||||
final Calculator speaker = (Calculator) _applicationContext.getBean(type);
|
||||
|
||||
|
||||
if (speaker instanceof StringCalculator)
|
||||
return String.format("%s", speaker.Sum(first, second));
|
||||
|
||||
else if (speaker instanceof DateCalculator)
|
||||
return String.format("%s", (speaker.Sum(LocalDate.parse(first.toString()), LocalDate.parse(second.toString()))));
|
||||
|
||||
else return String.format("%s", speaker.Sum(Integer.parseInt(first.toString()), Integer.parseInt(second.toString())));
|
||||
|
||||
}
|
||||
|
||||
public String Ras(Object first, Object second, String type) {
|
||||
final Calculator speaker = (Calculator) _applicationContext.getBean(type);
|
||||
if (speaker instanceof StringCalculator)
|
||||
return String.format("%s", speaker.Minus(first,second));
|
||||
|
||||
else if (speaker instanceof DateCalculator)
|
||||
return String.format("%s", (speaker.Minus(LocalDate.parse(first.toString()), LocalDate.parse(second.toString()))));
|
||||
|
||||
else
|
||||
return String.format("%s", speaker.Minus(Integer.parseInt(first.toString()),Integer.parseInt(second.toString())));
|
||||
}
|
||||
public String Rev(Object first, Object second, String type) {
|
||||
final Calculator speaker = (Calculator) _applicationContext.getBean(type);
|
||||
if (speaker instanceof StringCalculator)
|
||||
return String.format("%s", speaker.Reverse(first,second));
|
||||
|
||||
else if (speaker instanceof DateCalculator)
|
||||
return String.format("%s", (speaker.Reverse(LocalDate.parse(first.toString()), LocalDate.parse(second.toString()))));
|
||||
|
||||
else return String.format("%s", speaker.Reverse(Integer.parseInt(first.toString()),Integer.parseInt(second.toString())));
|
||||
|
||||
}
|
||||
public String Com(Object first, Object second, String type) {
|
||||
final Calculator speaker = (Calculator) _applicationContext.getBean(type);
|
||||
if (speaker instanceof StringCalculator)
|
||||
return String.format("%s", speaker.Comparison(first,second));
|
||||
|
||||
else if (speaker instanceof DateCalculator)
|
||||
return String.format("%s", (speaker.Comparison(LocalDate.parse(first.toString()), LocalDate.parse(second.toString()))));
|
||||
|
||||
else return String.format("%s", speaker.Comparison(Integer.parseInt(first.toString()), Integer.parseInt(second.toString())));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package ru.ulstu.is.sbapp.configuration;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
|
||||
@Configuration
|
||||
public class PasswordEncoderConfiguration {
|
||||
@Bean
|
||||
public PasswordEncoder createPasswordEncoder() {
|
||||
return new BCryptPasswordEncoder();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package ru.ulstu.is.sbapp.configuration;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
|
||||
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.builders.WebSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
|
||||
import ru.ulstu.is.sbapp.socialNetwork.controller.UserSignupMvcController;
|
||||
import ru.ulstu.is.sbapp.socialNetwork.models.UserRole;
|
||||
import ru.ulstu.is.sbapp.socialNetwork.services.MyUserService;
|
||||
import ru.ulstu.is.sbapp.socialNetwork.services.UserService;
|
||||
|
||||
@Configuration
|
||||
@EnableWebSecurity
|
||||
@EnableGlobalMethodSecurity(securedEnabled = true)
|
||||
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
|
||||
private final Logger log = LoggerFactory.getLogger(SecurityConfiguration.class);
|
||||
private static final String LOGIN_URL = "/login";
|
||||
private final UserService userService;
|
||||
|
||||
public SecurityConfiguration(UserService userService) {
|
||||
this.userService = userService;
|
||||
createAdminOnStartup();
|
||||
}
|
||||
|
||||
private void createAdminOnStartup() {
|
||||
final String admin = "admin";
|
||||
if (userService.findByLogin(admin) == null) {
|
||||
log.info("Admin user successfully created");
|
||||
userService.createUser(admin, admin, admin, UserRole.ADMIN);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
http.headers().frameOptions().sameOrigin().and()
|
||||
.cors().and()
|
||||
.csrf().disable()
|
||||
.authorizeRequests()
|
||||
.antMatchers(UserSignupMvcController.SIGNUP_URL).permitAll()
|
||||
.antMatchers(HttpMethod.GET, LOGIN_URL).permitAll()
|
||||
.anyRequest().authenticated()
|
||||
.and()
|
||||
.formLogin()
|
||||
.loginPage(LOGIN_URL).permitAll()
|
||||
.and()
|
||||
.logout().permitAll();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
|
||||
auth.userDetailsService(userService);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void configure(WebSecurity web) {
|
||||
web.ignoring()
|
||||
.antMatchers("/css/**")
|
||||
.antMatchers("/js/**")
|
||||
.antMatchers("/templates/**")
|
||||
.antMatchers("/webjars/**");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package ru.ulstu.is.sbapp.configuration;
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.servlet.config.annotation.CorsRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
@Configuration
|
||||
public class WebConfiguration implements WebMvcConfigurer {
|
||||
@Override
|
||||
public void addCorsMappings(CorsRegistry registry) {
|
||||
registry.addMapping("/**").allowedMethods("*");
|
||||
}
|
||||
public static final String REST_API = "/api";
|
||||
|
||||
@Override
|
||||
public void addViewControllers(ViewControllerRegistry registry) {
|
||||
WebMvcConfigurer.super.addViewControllers(registry);
|
||||
registry.addViewController("users");
|
||||
registry.addViewController("contacts");
|
||||
registry.addViewController("catalogs");
|
||||
registry.addViewController("login");
|
||||
}
|
||||
@Override
|
||||
public void addResourceHandlers(ResourceHandlerRegistry registry) {
|
||||
registry.addResourceHandler("/static/css/**").addResourceLocations("/static/css/");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package ru.ulstu.is.sbapp.socialNetwork.controller;
|
||||
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import ru.ulstu.is.sbapp.configuration.WebConfiguration;
|
||||
import ru.ulstu.is.sbapp.socialNetwork.dto.CommunityDTO;
|
||||
import ru.ulstu.is.sbapp.socialNetwork.services.CommunityService;
|
||||
|
||||
import javax.validation.Valid;
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
@RequestMapping(WebConfiguration.REST_API + "/communities")
|
||||
public class CommunityController {
|
||||
private final CommunityService communityService;
|
||||
|
||||
public CommunityController(CommunityService communityService) {
|
||||
this.communityService = communityService;
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public CommunityDTO getCommunity(@PathVariable Long id) {
|
||||
return new CommunityDTO(communityService.findCommunity(id));
|
||||
}
|
||||
|
||||
@GetMapping("")
|
||||
public List<CommunityDTO> getCommunities() {
|
||||
return communityService.findAllCommunities().stream().map(CommunityDTO::new).toList();
|
||||
}
|
||||
|
||||
@PostMapping("")
|
||||
public CommunityDTO createCommunity(@RequestBody @Valid CommunityDTO community) {
|
||||
return new CommunityDTO(communityService.addCommunity(community.getName()));
|
||||
}
|
||||
|
||||
@PatchMapping("")
|
||||
public CommunityDTO updateCommunity(@PathVariable Long id, @RequestBody @Valid CommunityDTO community) {
|
||||
return new CommunityDTO(communityService.updateCommunity(id, community.getName()));
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
public CommunityDTO deleteCommunity(@PathVariable Long id) {
|
||||
return new CommunityDTO(communityService.deleteCommunity(id));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package ru.ulstu.is.sbapp.socialNetwork.controller;
|
||||
|
||||
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import ru.ulstu.is.sbapp.configuration.WebConfiguration;
|
||||
import ru.ulstu.is.sbapp.socialNetwork.dto.MusicDTO;
|
||||
import ru.ulstu.is.sbapp.socialNetwork.services.MusicService;
|
||||
|
||||
import javax.validation.Valid;
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
@RequestMapping(WebConfiguration.REST_API + "/musics")
|
||||
public class MusicController {
|
||||
|
||||
private final MusicService musicService;
|
||||
|
||||
public MusicController(MusicService musicService){
|
||||
this.musicService = musicService;
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public MusicDTO getMusic(@PathVariable Long id){
|
||||
return new MusicDTO(musicService.findMusic(id));
|
||||
}
|
||||
|
||||
@GetMapping("")
|
||||
public List<MusicDTO> getMusics() {
|
||||
return musicService.findAllMusics().stream().map(MusicDTO::new).toList();
|
||||
}
|
||||
|
||||
@PostMapping("")
|
||||
public MusicDTO createMusic(@RequestBody @Valid MusicDTO music) {
|
||||
return new MusicDTO(musicService.addMusic(music.getName()));
|
||||
}
|
||||
|
||||
@PatchMapping("/{id}")
|
||||
public MusicDTO updateMusic(@PathVariable Long id,
|
||||
@RequestBody @Valid MusicDTO music) {
|
||||
return new MusicDTO(musicService.updateMusic(id, music.getName()));
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
public MusicDTO deleteMusic(@PathVariable Long id) {
|
||||
return new MusicDTO(musicService.deleteMusic(id));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package ru.ulstu.is.sbapp.socialNetwork.controller;
|
||||
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import ru.ulstu.is.sbapp.configuration.WebConfiguration;
|
||||
import ru.ulstu.is.sbapp.socialNetwork.dto.MyUserDTO;
|
||||
import ru.ulstu.is.sbapp.socialNetwork.models.UserModel;
|
||||
import ru.ulstu.is.sbapp.socialNetwork.services.MyUserService;
|
||||
|
||||
|
||||
import javax.validation.Valid;
|
||||
import java.util.List;
|
||||
|
||||
|
||||
@RestController
|
||||
@RequestMapping(WebConfiguration.REST_API + "/users")
|
||||
public class UserController {
|
||||
private final MyUserService userService;
|
||||
|
||||
public UserController(MyUserService userService){
|
||||
this.userService = userService;
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public MyUserDTO getUser(@PathVariable Long id) {
|
||||
return new MyUserDTO(userService.findUser(id));
|
||||
}
|
||||
|
||||
@GetMapping("")
|
||||
public List<MyUserDTO> getUsers() {
|
||||
return userService.findAllUsers().stream().map(MyUserDTO::new).toList();
|
||||
}
|
||||
|
||||
@PostMapping("")
|
||||
public MyUserDTO createUser(@RequestBody @Valid MyUserDTO user) {
|
||||
UserModel result = userService.addUser(user.getName(), user.getCity());
|
||||
userService.updateCommunities(result.getId(), user.getCommunity());
|
||||
return new MyUserDTO(userService.updateMusics(result.getId(), user.getMusic()));
|
||||
}
|
||||
|
||||
@PatchMapping("/{id}")
|
||||
public MyUserDTO updateUser(@PathVariable Long id,
|
||||
@RequestBody @Valid MyUserDTO user) {
|
||||
UserModel result = userService.updateUser(id, user.getName());
|
||||
userService.updateCommunities(result.getId(), user.getCommunity());
|
||||
return new MyUserDTO(userService.updateMusics(result.getId(), user.getMusic()));
|
||||
}
|
||||
|
||||
@PatchMapping("/add_music/{id}")
|
||||
public MyUserDTO addMusic(@PathVariable Long id, @RequestParam Long music_id) {
|
||||
return new MyUserDTO(userService.addMusic(id, music_id));
|
||||
}
|
||||
|
||||
@PatchMapping("/add_community/{id}")
|
||||
public MyUserDTO addCommunity(@PathVariable Long id, @RequestParam Long community_id) {
|
||||
return new MyUserDTO(userService.addCommunity(id, community_id));
|
||||
}
|
||||
@GetMapping("/search")
|
||||
public List<MyUserDTO> searchUsers(@RequestParam("city") String city) {
|
||||
List<UserModel> users = userService.findUserByCity(city);
|
||||
return users.stream().map(MyUserDTO::new).toList();
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
public MyUserDTO deleteUser(@PathVariable Long id) {
|
||||
return new MyUserDTO(userService.deleteUser(id));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package ru.ulstu.is.sbapp.socialNetwork.controller;
|
||||
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.security.access.annotation.Secured;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import ru.ulstu.is.sbapp.socialNetwork.dto.UserDto;
|
||||
import ru.ulstu.is.sbapp.socialNetwork.models.UserRole;
|
||||
import ru.ulstu.is.sbapp.socialNetwork.services.UserService;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
@Controller
|
||||
@RequestMapping("/users")
|
||||
public class UserMvcController {
|
||||
private final UserService userService;
|
||||
|
||||
public UserMvcController(UserService userService) {
|
||||
this.userService = userService;
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
@Secured({UserRole.AsString.ADMIN})
|
||||
public String getUsers(@RequestParam(defaultValue = "1") int page,
|
||||
@RequestParam(defaultValue = "5") int size,
|
||||
Model model) {
|
||||
final Page<UserDto> users = userService.findAllPages(page, size)
|
||||
.map(UserDto::new);
|
||||
model.addAttribute("users", users);
|
||||
final int totalPages = users.getTotalPages();
|
||||
final List<Integer> pageNumbers = IntStream.rangeClosed(1, totalPages)
|
||||
.boxed()
|
||||
.toList();
|
||||
model.addAttribute("pages", pageNumbers);
|
||||
model.addAttribute("totalPages", totalPages);
|
||||
return "users";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package ru.ulstu.is.sbapp.socialNetwork.controller;
|
||||
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.validation.BindingResult;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.ModelAttribute;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import ru.ulstu.is.sbapp.socialNetwork.models.User;
|
||||
import ru.ulstu.is.sbapp.socialNetwork.models.UserSignupDto;
|
||||
import ru.ulstu.is.sbapp.socialNetwork.services.UserService;
|
||||
import ru.ulstu.is.sbapp.socialNetwork.util.validation.ValidationException;
|
||||
|
||||
import javax.validation.Valid;
|
||||
|
||||
@Controller
|
||||
@RequestMapping(UserSignupMvcController.SIGNUP_URL)
|
||||
public class UserSignupMvcController {
|
||||
public static final String SIGNUP_URL = "/signup";
|
||||
|
||||
private final UserService userService;
|
||||
|
||||
public UserSignupMvcController(UserService userService) {
|
||||
this.userService = userService;
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public String showSignupForm(Model model) {
|
||||
model.addAttribute("userDto", new UserSignupDto());
|
||||
return "signup";
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public String signup(@ModelAttribute("userDto") @Valid UserSignupDto userSignupDto,
|
||||
BindingResult bindingResult,
|
||||
Model model) {
|
||||
if (bindingResult.hasErrors()) {
|
||||
model.addAttribute("errors", bindingResult.getAllErrors());
|
||||
return "signup";
|
||||
}
|
||||
try {
|
||||
final User user = userService.createUser(
|
||||
userSignupDto.getLogin(), userSignupDto.getPassword(), userSignupDto.getPasswordConfirm());
|
||||
return "redirect:/login?created=" + user.getLogin();
|
||||
} catch (ValidationException e) {
|
||||
model.addAttribute("errors", e.getMessage());
|
||||
return "signup";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package ru.ulstu.is.sbapp.socialNetwork.dto;
|
||||
|
||||
import ru.ulstu.is.sbapp.socialNetwork.models.Community;
|
||||
import ru.ulstu.is.sbapp.socialNetwork.models.UserModel;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class CommunityDTO {
|
||||
private Long id;
|
||||
private String name;
|
||||
|
||||
public CommunityDTO(){
|
||||
}
|
||||
public CommunityDTO(Community community){
|
||||
this.id = community.getId();
|
||||
this.name = community.getName();
|
||||
}
|
||||
|
||||
private List<UserModel> users;
|
||||
|
||||
public List<UserModel> getUsers() {
|
||||
return users;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return "User{" +
|
||||
"id=" + id +
|
||||
", name='" + name + '\'' +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package ru.ulstu.is.sbapp.socialNetwork.dto;
|
||||
|
||||
import ru.ulstu.is.sbapp.socialNetwork.models.Music;
|
||||
|
||||
public class MusicDTO {
|
||||
private Long id;
|
||||
public String name;
|
||||
|
||||
public MusicDTO(){
|
||||
}
|
||||
public MusicDTO(Music music){
|
||||
this.id = music.getId();
|
||||
this.name = music.getName();
|
||||
}
|
||||
public Long getId() {return id;}
|
||||
|
||||
public String getName() {return name;}
|
||||
public void setName(String name) {this.name = name;}
|
||||
|
||||
@Override
|
||||
public String toString(){
|
||||
return "Music{" +
|
||||
"id = " + id +
|
||||
"name = " + name + '\'' +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package ru.ulstu.is.sbapp.socialNetwork.dto;
|
||||
|
||||
import ru.ulstu.is.sbapp.socialNetwork.models.Community;
|
||||
import ru.ulstu.is.sbapp.socialNetwork.models.Music;
|
||||
import ru.ulstu.is.sbapp.socialNetwork.models.UserModel;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class MyUserDTO {
|
||||
private Long id;
|
||||
private String name;
|
||||
private String city;
|
||||
|
||||
public MyUserDTO(){}
|
||||
|
||||
public MyUserDTO(UserModel user){
|
||||
|
||||
this.id = user.getId();
|
||||
this.name = user.getName();
|
||||
this.city = user.getCity();
|
||||
if(user.getMusics() != null) {
|
||||
this.music = user.getMusics().stream().map(Music::getName).toList();
|
||||
}
|
||||
if(user.getGroups() != null) {
|
||||
this.community = user.getGroups().stream().map(Community::getName).toList();
|
||||
}
|
||||
}
|
||||
public MyUserDTO(Long id, String name) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
}
|
||||
private List<String> music;
|
||||
private List<String> community;
|
||||
|
||||
public Long getId(){return id;}
|
||||
|
||||
public String getName(){return name;}
|
||||
public void setName(String firstName){this.name = firstName;}
|
||||
|
||||
public List<String> getMusic() {
|
||||
return music;
|
||||
}
|
||||
|
||||
public List<String> getCommunity() {
|
||||
return community;
|
||||
}
|
||||
|
||||
public void setCommunities(List<String> communities) {
|
||||
this.community = communities;
|
||||
}
|
||||
|
||||
public void setMusics(List<String> musics) {
|
||||
this.music = musics;
|
||||
}
|
||||
|
||||
public void setCity(String city){
|
||||
this.city = city;
|
||||
}
|
||||
|
||||
public String getCity(){
|
||||
return city;
|
||||
}
|
||||
|
||||
public void setMusic(List<String> music) {
|
||||
this.music = music;
|
||||
}
|
||||
|
||||
public void setCommunity(List<String> community) {
|
||||
this.community = community;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "User{" +
|
||||
"id=" + id +
|
||||
", name='" + name + '\'' +
|
||||
", city='" + city + '\'' +
|
||||
'}';
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package ru.ulstu.is.sbapp.socialNetwork.dto;
|
||||
|
||||
import ru.ulstu.is.sbapp.socialNetwork.models.User;
|
||||
import ru.ulstu.is.sbapp.socialNetwork.models.UserRole;
|
||||
|
||||
public class UserDto {
|
||||
private final long id;
|
||||
private final String login;
|
||||
private final UserRole role;
|
||||
|
||||
public UserDto(User user) {
|
||||
this.id = user.getId();
|
||||
this.login = user.getLogin();
|
||||
this.role = user.getRole();
|
||||
}
|
||||
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public String getLogin() {
|
||||
return login;
|
||||
}
|
||||
|
||||
public UserRole getRole() {
|
||||
return role;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package ru.ulstu.is.sbapp.socialNetwork.models;
|
||||
|
||||
import javax.persistence.*;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
@Entity
|
||||
public class Community {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
private Long id;
|
||||
private String name;
|
||||
|
||||
@ManyToMany(fetch = FetchType.EAGER, mappedBy = "communities")
|
||||
private List<UserModel> users;
|
||||
|
||||
public Community() {
|
||||
}
|
||||
|
||||
public Community(String name){
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
public List<UserModel> getUsers() {
|
||||
return users;
|
||||
}
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(id);
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return "User{" +
|
||||
"id=" + id +
|
||||
", name='" + name + '\'' +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
package ru.ulstu.is.sbapp.socialNetwork.models;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
import java.util.Objects;
|
||||
|
||||
@Entity
|
||||
public class Music {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
private Long id;
|
||||
public String name;
|
||||
|
||||
|
||||
public Music() {
|
||||
}
|
||||
|
||||
public Music(String name){
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "User{" +
|
||||
"id=" + id +
|
||||
", name='" + name + '\'' +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
package ru.ulstu.is.sbapp.socialNetwork.models;
|
||||
|
||||
import javax.persistence.*;
|
||||
import javax.validation.constraints.NotBlank;
|
||||
import javax.validation.constraints.Size;
|
||||
import java.util.Objects;
|
||||
|
||||
@Entity
|
||||
@Table(name = "users")
|
||||
public class User {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
private Long id;
|
||||
@Column(nullable = false, unique = true, length = 64)
|
||||
@NotBlank
|
||||
@Size(min = 3, max = 64)
|
||||
private String login;
|
||||
@Column(nullable = false, length = 64)
|
||||
@NotBlank
|
||||
@Size(min = 6, max = 64)
|
||||
private String password;
|
||||
private UserRole role;
|
||||
|
||||
public User() {
|
||||
}
|
||||
|
||||
public User(String login, String password) {
|
||||
this(login, password, UserRole.USER);
|
||||
}
|
||||
|
||||
public User(String login, String password, UserRole role) {
|
||||
this.login = login;
|
||||
this.password = password;
|
||||
this.role = role;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public String getLogin() {
|
||||
return login;
|
||||
}
|
||||
|
||||
public void setLogin(String login) {
|
||||
this.login = login;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
public UserRole getRole() {
|
||||
return role;
|
||||
}
|
||||
|
||||
@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) && Objects.equals(login, user.login);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(id, login);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package ru.ulstu.is.sbapp.socialNetwork.models;
|
||||
import org.hibernate.annotations.LazyCollection;
|
||||
import org.hibernate.annotations.LazyCollectionOption;
|
||||
|
||||
import javax.persistence.*;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Entity
|
||||
public class UserModel {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
|
||||
private Long id;
|
||||
private String name;
|
||||
private String city;
|
||||
//поиск людей по городу
|
||||
|
||||
@ManyToMany
|
||||
@LazyCollection(LazyCollectionOption.FALSE)
|
||||
@JoinTable(name="usermodels_musics",
|
||||
joinColumns = @JoinColumn(name="usermodel_id"),
|
||||
inverseJoinColumns = @JoinColumn(name="music_id")
|
||||
)
|
||||
private List<Music> musics;
|
||||
|
||||
@ManyToMany
|
||||
@LazyCollection(LazyCollectionOption.FALSE)
|
||||
@JoinTable(name="usermodels_communities",
|
||||
joinColumns = @JoinColumn(name="usermodel_id"),
|
||||
inverseJoinColumns = @JoinColumn(name="community_id")
|
||||
)
|
||||
private List<Community> communities;
|
||||
|
||||
public UserModel(){
|
||||
}
|
||||
public UserModel(String name){
|
||||
this.name = name;
|
||||
this.city = "Mosscow";
|
||||
}
|
||||
public UserModel(String name, String city){
|
||||
this.name = name;
|
||||
this.city = city;
|
||||
}
|
||||
public void deleteMusics() {
|
||||
musics = null;
|
||||
}
|
||||
public void deleteCommunities() {
|
||||
communities = null;
|
||||
}
|
||||
|
||||
public Long getId(){return id;}
|
||||
|
||||
public String getName(){return name;}
|
||||
public void setName(String firstName){this.name = firstName;}
|
||||
|
||||
public void addMusic(Music g) {
|
||||
if(musics == null) musics = new ArrayList<>();
|
||||
musics.add(g);
|
||||
}
|
||||
public List<Music> getMusics() {
|
||||
return musics;
|
||||
}
|
||||
|
||||
public void addCommunity(Community g) {
|
||||
if(communities == null) communities = new ArrayList<>();
|
||||
communities.add(g);
|
||||
}
|
||||
public List<Community> getGroups() {
|
||||
return communities;
|
||||
}
|
||||
|
||||
public void setCity(String city){
|
||||
this.city = city;
|
||||
}
|
||||
public String getCity(){
|
||||
return city;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "User{" +
|
||||
"id=" + id +
|
||||
", name='" + name + '\'' +
|
||||
", city='" + city + '\'' +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package ru.ulstu.is.sbapp.socialNetwork.models;
|
||||
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
|
||||
public enum UserRole implements GrantedAuthority {
|
||||
ADMIN,
|
||||
USER;
|
||||
|
||||
private static final String PREFIX = "ROLE_";
|
||||
|
||||
@Override
|
||||
public String getAuthority() {
|
||||
return PREFIX + this.name();
|
||||
}
|
||||
|
||||
public static final class AsString {
|
||||
public static final String ADMIN = PREFIX + "ADMIN";
|
||||
public static final String USER = PREFIX + "USER";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package ru.ulstu.is.sbapp.socialNetwork.models;
|
||||
|
||||
import javax.validation.constraints.NotBlank;
|
||||
import javax.validation.constraints.Size;
|
||||
|
||||
public class UserSignupDto {
|
||||
@NotBlank
|
||||
@Size(min = 3, max = 64)
|
||||
private String login;
|
||||
@NotBlank
|
||||
@Size(min = 6, max = 64)
|
||||
private String password;
|
||||
@NotBlank
|
||||
@Size(min = 6, max = 64)
|
||||
private String passwordConfirm;
|
||||
|
||||
public String getLogin() {
|
||||
return login;
|
||||
}
|
||||
|
||||
public void setLogin(String login) {
|
||||
this.login = login;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
public String getPasswordConfirm() {
|
||||
return passwordConfirm;
|
||||
}
|
||||
|
||||
public void setPasswordConfirm(String passwordConfirm) {
|
||||
this.passwordConfirm = passwordConfirm;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package ru.ulstu.is.sbapp.socialNetwork.repository;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import ru.ulstu.is.sbapp.socialNetwork.models.Community;
|
||||
|
||||
public interface CommunityRepository extends JpaRepository<Community, Long> {
|
||||
Community findByName(String name);
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package ru.ulstu.is.sbapp.socialNetwork.repository;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import ru.ulstu.is.sbapp.socialNetwork.models.Community;
|
||||
import ru.ulstu.is.sbapp.socialNetwork.models.Music;
|
||||
import ru.ulstu.is.sbapp.socialNetwork.models.UserModel;
|
||||
|
||||
public interface MusicRepository extends JpaRepository<Music, Long> {
|
||||
Music findByName(String name);
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package ru.ulstu.is.sbapp.socialNetwork.repository;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import ru.ulstu.is.sbapp.socialNetwork.models.UserModel;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface MyUserRepository extends JpaRepository<UserModel, Long> {
|
||||
List<UserModel> findByCity(String city);
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package ru.ulstu.is.sbapp.socialNetwork.repository;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import ru.ulstu.is.sbapp.socialNetwork.models.User;
|
||||
|
||||
public interface UserRepository extends JpaRepository<User, Long> {
|
||||
User findOneByLoginIgnoreCase(String login);
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package ru.ulstu.is.sbapp.socialNetwork.services;
|
||||
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.EntityNotFoundException;
|
||||
import javax.persistence.PersistenceContext;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.util.StringUtils;
|
||||
import ru.ulstu.is.sbapp.socialNetwork.models.Community;
|
||||
import ru.ulstu.is.sbapp.socialNetwork.repository.CommunityRepository;
|
||||
|
||||
@Service
|
||||
public class CommunityService {
|
||||
|
||||
private CommunityRepository repo;
|
||||
|
||||
public CommunityService(CommunityRepository repo){
|
||||
this.repo = repo;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public Community addCommunity(String name) {
|
||||
if (!StringUtils.hasText(name)) {
|
||||
throw new IllegalArgumentException("Community name is null or empty");
|
||||
}
|
||||
Community community = new Community(name);
|
||||
return repo.save(community);
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public Community findCommunity(Long id) {
|
||||
final Optional<Community> сommunity = repo.findById(id);
|
||||
if (сommunity.isEmpty()) {
|
||||
throw new EntityNotFoundException(String.format("Community with id [%s] is not found", id));
|
||||
}
|
||||
return сommunity.get();
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<Community> findAllCommunities() {
|
||||
return repo.findAll();
|
||||
}
|
||||
|
||||
|
||||
@Transactional
|
||||
public Community updateCommunity(Long id, String name) {
|
||||
if (!StringUtils.hasText(name)) {
|
||||
throw new IllegalArgumentException("Music name is null or empty");
|
||||
}
|
||||
final Optional<Community> currentCommunityOpt = repo.findById(id);
|
||||
|
||||
if(currentCommunityOpt.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
final Community currentCommunity = currentCommunityOpt.get();
|
||||
|
||||
currentCommunity.setName(name);
|
||||
return repo.save(currentCommunity);
|
||||
}
|
||||
@Transactional
|
||||
public Community findByName(String name) {
|
||||
if (!StringUtils.hasText(name)) {
|
||||
throw new IllegalArgumentException("Genre name is null or empty");
|
||||
}
|
||||
return repo.findByName(name);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public Community deleteCommunity(Long id) {
|
||||
final Optional<Community> currentCommunity = repo.findById(id);
|
||||
if(currentCommunity.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
repo.deleteById(id);
|
||||
return currentCommunity.get();
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void deleteAllCommunities() {
|
||||
repo.deleteAll();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
package ru.ulstu.is.sbapp.socialNetwork.services;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.util.StringUtils;
|
||||
import ru.ulstu.is.sbapp.socialNetwork.models.Community;
|
||||
import ru.ulstu.is.sbapp.socialNetwork.models.Music;
|
||||
import ru.ulstu.is.sbapp.socialNetwork.models.UserModel;
|
||||
import ru.ulstu.is.sbapp.socialNetwork.repository.CommunityRepository;
|
||||
import ru.ulstu.is.sbapp.socialNetwork.repository.MusicRepository;
|
||||
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.EntityNotFoundException;
|
||||
import javax.persistence.PersistenceContext;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
|
||||
@Service
|
||||
public class MusicService {
|
||||
|
||||
private MusicRepository repo;
|
||||
|
||||
public MusicService(MusicRepository repo) {
|
||||
this.repo = repo;
|
||||
}
|
||||
@Transactional
|
||||
public Music addMusic(String name) {
|
||||
if (!StringUtils.hasText(name)) {
|
||||
throw new IllegalArgumentException("Music name is null or empty");
|
||||
}
|
||||
|
||||
Music music = new Music(name);
|
||||
|
||||
return repo.save(music);
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public Music findMusic(Long id) {
|
||||
|
||||
final Optional<Music> music = repo.findById(id);
|
||||
if (music.isEmpty()) {
|
||||
throw new EntityNotFoundException(String.format("Music with id [%s] is not found", id));
|
||||
}
|
||||
return music.get();
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<Music> findAllMusics() {
|
||||
return repo.findAll();
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public Music updateMusic(Long id, String name) {
|
||||
|
||||
if (!StringUtils.hasText(name)) {
|
||||
throw new IllegalArgumentException("Music name is null or empty");
|
||||
}
|
||||
final Optional<Music> currentMusicOpt = repo.findById(id);
|
||||
|
||||
if(currentMusicOpt.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
final Music currentMusic = currentMusicOpt.get();
|
||||
|
||||
currentMusic.setName(name);
|
||||
return repo.save(currentMusic);
|
||||
}
|
||||
@Transactional
|
||||
public Music findByName(String name) {
|
||||
if (!StringUtils.hasText(name)) {
|
||||
throw new IllegalArgumentException("Music name is null or empty");
|
||||
}
|
||||
return repo.findByName(name);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public Music deleteMusic(Long id) {
|
||||
|
||||
final Optional<Music> currentMusic = repo.findById(id);
|
||||
if(currentMusic.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
repo.deleteById(id);
|
||||
return currentMusic.get();
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void deleteAllMusics() {
|
||||
repo.deleteAll();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,211 @@
|
||||
package ru.ulstu.is.sbapp.socialNetwork.services;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.util.StringUtils;
|
||||
import ru.ulstu.is.sbapp.socialNetwork.models.Community;
|
||||
import ru.ulstu.is.sbapp.socialNetwork.models.Music;
|
||||
import ru.ulstu.is.sbapp.socialNetwork.models.UserModel;
|
||||
import ru.ulstu.is.sbapp.socialNetwork.repository.MyUserRepository;
|
||||
|
||||
import javax.persistence.EntityNotFoundException;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
@Service
|
||||
public class MyUserService {
|
||||
|
||||
private MyUserRepository repo;
|
||||
|
||||
private CommunityService communityService;
|
||||
private MusicService musicService;
|
||||
|
||||
public MyUserService(MyUserRepository repo, MusicService musicService, CommunityService communityService) {
|
||||
this.repo = repo;
|
||||
this.musicService = musicService;
|
||||
this.communityService = communityService;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public UserModel addUser(String name, String city) {
|
||||
if (!StringUtils.hasText(name)) {
|
||||
throw new IllegalArgumentException("User name is null or empty");
|
||||
}
|
||||
UserModel user = new UserModel(name, city);
|
||||
return repo.save(user);
|
||||
}
|
||||
@Transactional
|
||||
public UserModel addUser(String name, String city, List<String> musics, List<String> communities) {
|
||||
|
||||
if (!StringUtils.hasText(name)) {
|
||||
throw new IllegalArgumentException("Name is null or empty");
|
||||
}
|
||||
|
||||
UserModel user = new UserModel(name, city);
|
||||
UserModel result = repo.save(user);
|
||||
|
||||
updateMusics(result.getId(), musics);
|
||||
return updateCommunities(user.getId(), communities);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public UserModel addMusic(Long userId, Long musicId) {
|
||||
final Optional<UserModel> userOpt= repo.findById(userId);
|
||||
|
||||
if (userOpt.isEmpty()) {
|
||||
throw new EntityNotFoundException(String.format("User with id [%s] is not found", musicId));
|
||||
}
|
||||
|
||||
UserModel user = userOpt.get();
|
||||
|
||||
final Music music = musicService.findMusic(musicId);
|
||||
if (music == null) {
|
||||
throw new EntityNotFoundException(String.format("Music with id [%s] is not found", musicId));
|
||||
}
|
||||
|
||||
user.addMusic(music);
|
||||
return repo.save(user);
|
||||
}
|
||||
@Transactional
|
||||
public UserModel addCommunity(Long userId, Long communityId) {
|
||||
final Optional<UserModel> userOpt = repo.findById(userId);
|
||||
|
||||
if (userOpt.isEmpty()) {
|
||||
throw new EntityNotFoundException(String.format("User with id [%s] is not found", userId));
|
||||
}
|
||||
|
||||
UserModel user = userOpt.get();
|
||||
|
||||
final Community community = communityService.findCommunity(communityId);
|
||||
if (community == null) {
|
||||
throw new EntityNotFoundException(String.format("Community with id [%s] is not found", communityId));
|
||||
}
|
||||
|
||||
user.addCommunity(community);
|
||||
return repo.save(user);
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public UserModel findUser(Long id) {
|
||||
|
||||
final Optional<UserModel> user = repo.findById(id);
|
||||
if (user.isEmpty()) {
|
||||
throw new EntityNotFoundException(String.format("UserModel with id [%s] is not found", id));
|
||||
}
|
||||
return user.get();
|
||||
}
|
||||
|
||||
// @Transactional(readOnly = true)
|
||||
// public List<UserModel> findUserByCity(String city){
|
||||
// Query query = repo.createQuery("select u from UserModel u where u.city = :city",
|
||||
// UserModel.class).setParameter("city", city);
|
||||
// List<UserModel> result = query.getResultList();
|
||||
// return result;
|
||||
// }
|
||||
@Transactional(readOnly = true)
|
||||
public List<UserModel> findUserByCity(String city){
|
||||
List<UserModel> result = repo.findByCity(city);
|
||||
return result;
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<UserModel> findAllUsers() {
|
||||
return repo.findAll();
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public UserModel updateUser(Long id, String name) {
|
||||
|
||||
if (!StringUtils.hasText(name)) {
|
||||
throw new IllegalArgumentException("User name is null or empty");
|
||||
}
|
||||
final Optional<UserModel> currentUserOpt = repo.findById(id);
|
||||
|
||||
if(currentUserOpt.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
final UserModel currentUser = currentUserOpt.get();
|
||||
|
||||
currentUser.setName(name);
|
||||
return repo.save(currentUser);
|
||||
}
|
||||
//update community, musics
|
||||
@Transactional
|
||||
public UserModel updateUser(Long id, String name,String city, List<String> musics, List<String> Communities) {
|
||||
if (!StringUtils.hasText(name)) {
|
||||
throw new IllegalArgumentException("User name is null or empty");
|
||||
}
|
||||
final Optional<UserModel> currentUserOpt = repo.findById(id);
|
||||
|
||||
if(currentUserOpt.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
final UserModel currentUser = currentUserOpt.get();
|
||||
|
||||
currentUser.setName(name);
|
||||
currentUser.setCity(city);
|
||||
repo.save(currentUser);
|
||||
|
||||
updateMusics(id, musics);
|
||||
return updateCommunities(id, Communities);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public UserModel updateCommunities(Long userId , List<String> communities) {
|
||||
final Optional<UserModel> userOpt = repo.findById(userId);
|
||||
|
||||
if (userOpt.isEmpty()) {
|
||||
throw new EntityNotFoundException(String.format("UserModel with id [%s] is not found", userId));
|
||||
}
|
||||
|
||||
UserModel user = userOpt.get();
|
||||
|
||||
user.deleteCommunities();
|
||||
|
||||
for(String c : communities) {
|
||||
Community community = communityService.findByName(c);
|
||||
user.addCommunity(community);
|
||||
}
|
||||
return repo.save(user);
|
||||
}
|
||||
@Transactional
|
||||
public UserModel updateMusics(Long userId , List<String> musics) {
|
||||
final Optional<UserModel> userOpt = repo.findById(userId);
|
||||
|
||||
if (userOpt.isEmpty()) {
|
||||
throw new EntityNotFoundException(String.format("Music with id [%s] is not found", userId));
|
||||
}
|
||||
|
||||
UserModel user = userOpt.get();
|
||||
|
||||
user.deleteMusics();
|
||||
|
||||
for(String m : musics) {
|
||||
Music music = musicService.findByName(m);
|
||||
user.addMusic(music);
|
||||
}
|
||||
return repo.save(user);
|
||||
}
|
||||
|
||||
|
||||
@Transactional
|
||||
public UserModel deleteUser(Long id) {
|
||||
|
||||
final Optional<UserModel> currentUser = repo.findById(id);
|
||||
if(currentUser.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
repo.deleteById(id);
|
||||
return currentUser.get();
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void deleteAllUsers() {
|
||||
repo.deleteAll();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package ru.ulstu.is.sbapp.socialNetwork.services;
|
||||
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Service;
|
||||
import ru.ulstu.is.sbapp.socialNetwork.models.User;
|
||||
import ru.ulstu.is.sbapp.socialNetwork.models.UserRole;
|
||||
import ru.ulstu.is.sbapp.socialNetwork.repository.UserRepository;
|
||||
import ru.ulstu.is.sbapp.socialNetwork.util.validation.ValidationException;
|
||||
import ru.ulstu.is.sbapp.socialNetwork.util.validation.ValidatorUtil;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.Objects;
|
||||
|
||||
@Service
|
||||
public class UserService implements UserDetailsService {
|
||||
private final UserRepository userRepository;
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
private final ValidatorUtil validatorUtil;
|
||||
|
||||
public UserService(UserRepository userRepository,
|
||||
PasswordEncoder passwordEncoder,
|
||||
ValidatorUtil validatorUtil) {
|
||||
this.userRepository = userRepository;
|
||||
this.passwordEncoder = passwordEncoder;
|
||||
this.validatorUtil = validatorUtil;
|
||||
}
|
||||
|
||||
public Page<User> findAllPages(int page, int size) {
|
||||
return userRepository.findAll(PageRequest.of(page - 1, size, Sort.by("id").ascending()));
|
||||
}
|
||||
|
||||
public User findByLogin(String login) {
|
||||
return userRepository.findOneByLoginIgnoreCase(login);
|
||||
}
|
||||
|
||||
public User createUser(String login, String password, String passwordConfirm) {
|
||||
return createUser(login, password, passwordConfirm, UserRole.USER);
|
||||
}
|
||||
|
||||
public User createUser(String login, String password, String passwordConfirm, UserRole role) {
|
||||
if (findByLogin(login) != null) {
|
||||
throw new ValidationException(String.format("User '%s' already exists", login));
|
||||
}
|
||||
final User user = new User(login, passwordEncoder.encode(password), role);
|
||||
validatorUtil.validate(user);
|
||||
if (!Objects.equals(password, passwordConfirm)) {
|
||||
throw new ValidationException("Passwords not equals");
|
||||
}
|
||||
return userRepository.save(user);
|
||||
}
|
||||
|
||||
@Override
|
||||
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
|
||||
final User userEntity = findByLogin(username);
|
||||
if (userEntity == null) {
|
||||
throw new UsernameNotFoundException(username);
|
||||
}
|
||||
return new org.springframework.security.core.userdetails.User(
|
||||
userEntity.getLogin(), userEntity.getPassword(), Collections.singleton(userEntity.getRole()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package ru.ulstu.is.sbapp.socialNetwork.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 org.springframework.web.bind.annotation.RestController;
|
||||
import ru.ulstu.is.sbapp.socialNetwork.util.validation.ValidationException;
|
||||
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@ControllerAdvice(annotations = RestController.class)
|
||||
public class AdviceController {
|
||||
@ExceptionHandler({
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package ru.ulstu.is.sbapp.socialNetwork.util.validation;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
public class ValidationException extends RuntimeException {
|
||||
public <T> ValidationException(Set<String> errors) {
|
||||
super(String.join("\n", errors));
|
||||
}
|
||||
|
||||
public <T> ValidationException(String error) {
|
||||
super(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package ru.ulstu.is.sbapp.socialNetwork.util.validation;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.validation.ConstraintViolation;
|
||||
import javax.validation.Validation;
|
||||
import javax.validation.Validator;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Component
|
||||
public class ValidatorUtil {
|
||||
private final Validator validator;
|
||||
|
||||
public ValidatorUtil() {
|
||||
this.validator = Validation.buildDefaultValidatorFactory().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()));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
30
src/main/resources/templates/login.html
Normal file
30
src/main/resources/templates/login.html
Normal file
@@ -0,0 +1,30 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en"
|
||||
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
|
||||
layout:decorate="~{default}" xmlns:th="http://www.w3.org/1999/xhtml">
|
||||
<body>
|
||||
<div class="container" layout:fragment="content">
|
||||
<div th:if="${param.error}" class="alert alert-danger margin-bottom">
|
||||
Пользователь не найден или пароль указан не верно
|
||||
</div>
|
||||
<div th:if="${param.logout}" class="alert alert-success margin-bottom">
|
||||
Выход успешно произведен
|
||||
</div>
|
||||
<div th:if="${param.created}" class="alert alert-success margin-bottom">
|
||||
Пользователь '<span th:text="${param.created}"></span>' успешно создан
|
||||
</div>
|
||||
<form th:action="@{/login}" method="post" class="container-padding">
|
||||
<div class="mb-3">
|
||||
<input type="text" name="username" id="username" class="form-control"
|
||||
placeholder="Логин" required="true" autofocus="true"/>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<input type="password" name="password" id="password" class="form-control"
|
||||
placeholder="Пароль" required="true"/>
|
||||
</div>
|
||||
<button type="submit" class="btn btn-success button-fixed">Войти</button>
|
||||
<a class="btn btn-primary button-fixed" href="/signup">Регистрация</a>
|
||||
</form>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
28
src/main/resources/templates/signup.html
Normal file
28
src/main/resources/templates/signup.html
Normal file
@@ -0,0 +1,28 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en"
|
||||
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
|
||||
layout:decorate="~{default}">
|
||||
<body>
|
||||
<div class="container container-padding" layout:fragment="content">
|
||||
<div th:if="${errors}" th:text="${errors}" class="margin-bottom alert alert-danger"></div>
|
||||
<form action="#" th:action="@{/signup}" th:object="${userDto}" method="post">
|
||||
<div class="mb-3">
|
||||
<input type="text" class="form-control" th:field="${userDto.login}"
|
||||
placeholder="Логин" required="true" autofocus="true" maxlength="64"/>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<input type="password" class="form-control" th:field="${userDto.password}"
|
||||
placeholder="Пароль" required="true" minlength="6" maxlength="64"/>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<input type="password" class="form-control" th:field="${userDto.passwordConfirm}"
|
||||
placeholder="Пароль (подтверждение)" required="true" minlength="6" maxlength="64"/>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<button type="submit" class="btn btn-success button-fixed">Создать</button>
|
||||
<a class="btn btn-primary button-fixed" href="/login">Назад</a>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
37
src/main/resources/templates/users.html
Normal file
37
src/main/resources/templates/users.html
Normal file
@@ -0,0 +1,37 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en"
|
||||
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
|
||||
layout:decorate="~{default}" xmlns:th="http://www.w3.org/1999/xhtml">
|
||||
<body>
|
||||
<div class="container" layout:fragment="content">
|
||||
<div class="table-responsive">
|
||||
<table class="table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col">#</th>
|
||||
<th scope="col">ID</th>
|
||||
<th scope="col">Логин</th>
|
||||
<th scope="col">Роль</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr th:each="user, iterator: ${users}">
|
||||
<th scope="row" th:text="${iterator.index} + 1"></th>
|
||||
<td th:text="${user.id}"></td>
|
||||
<td th:text="${user.login}" style="width: 60%"></td>
|
||||
<td th:text="${user.role}" style="width: 20%"></td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div th:if="${totalPages > 0}" class="pagination">
|
||||
<span style="float: left; padding: 5px 5px;">Страницы:</span>
|
||||
<a th:each="page : ${pages}"
|
||||
th:href="@{/users(page=${page}, size=${users.size})}"
|
||||
th:text="${page}"
|
||||
th:class="${page == users.number + 1} ? active">
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
94
src/test/java/ru/ulstu/is/sbapp/JpaCommunityTest.java
Normal file
94
src/test/java/ru/ulstu/is/sbapp/JpaCommunityTest.java
Normal file
@@ -0,0 +1,94 @@
|
||||
package ru.ulstu.is.sbapp;
|
||||
|
||||
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.socialNetwork.models.Community;
|
||||
import ru.ulstu.is.sbapp.socialNetwork.models.UserModel;
|
||||
import ru.ulstu.is.sbapp.socialNetwork.services.CommunityService;
|
||||
import ru.ulstu.is.sbapp.socialNetwork.services.MyUserService;
|
||||
|
||||
import javax.persistence.EntityNotFoundException;
|
||||
import java.util.List;
|
||||
|
||||
@SpringBootTest
|
||||
public class JpaCommunityTest {
|
||||
private static final Logger log = LoggerFactory.getLogger(JpaUserTest.class);
|
||||
@Autowired
|
||||
MyUserService userService;
|
||||
|
||||
@Autowired
|
||||
CommunityService communityService;
|
||||
|
||||
@Test
|
||||
void testUserCreate() {
|
||||
communityService.deleteAllCommunities();
|
||||
final Community community = communityService.addCommunity("CodeGPT");
|
||||
log.info(community.toString());
|
||||
Assertions.assertNotNull(community.getId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testUserReadNotFound() {
|
||||
communityService.deleteAllCommunities();
|
||||
Assertions.assertThrows(EntityNotFoundException.class, () -> communityService.findCommunity(-1L));
|
||||
}
|
||||
|
||||
@Test
|
||||
void findUser() {
|
||||
communityService.deleteAllCommunities();
|
||||
final Community community = communityService.addCommunity("CodeGPT");
|
||||
log.info(community.toString());
|
||||
final Community findCommunity = communityService.findCommunity(community.getId());
|
||||
log.info(findCommunity.toString());
|
||||
Assertions.assertEquals(community.toString(), findCommunity.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testReadAll() {
|
||||
communityService.deleteAllCommunities();
|
||||
userService.deleteAllUsers();
|
||||
final Community community = communityService.addCommunity("CodeGPT");
|
||||
log.info(community.toString());
|
||||
final List<Community> communities = communityService.findAllCommunities();
|
||||
Assertions.assertEquals(communities.size(), 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateCommunity() {
|
||||
userService.deleteAllUsers();
|
||||
communityService.deleteAllCommunities();
|
||||
final Community community = communityService.addCommunity("CodeGPT 2");
|
||||
communityService.updateCommunity(community.getId(), "CodeGPT 3");
|
||||
final Community findCommunity = communityService.findCommunity(community.getId());
|
||||
log.info(findCommunity.toString());
|
||||
Assertions.assertEquals(findCommunity.getName(), "CodeGPT 3");
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteCommunity() {
|
||||
userService.deleteAllUsers();
|
||||
communityService.deleteAllCommunities();
|
||||
final Community community = communityService.addCommunity("CodeGPT");
|
||||
log.info(community.toString());
|
||||
communityService.deleteCommunity(community.getId());
|
||||
Assertions.assertThrows(EntityNotFoundException.class, () -> communityService.findCommunity(community.getId()));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
void addUser() {
|
||||
userService.deleteAllUsers();
|
||||
communityService.deleteAllCommunities();
|
||||
userService.findAllUsers();
|
||||
final Community community = communityService.addCommunity("CodeGPT");
|
||||
final UserModel user = userService.addUser("its_mailov", "Moscow");
|
||||
userService.addCommunity(user.getId(), community.getId());
|
||||
final Community findCommunity = communityService.findCommunity(community.getId());
|
||||
Assertions.assertEquals(findCommunity.getUsers().get(0).getId(), user.getId());
|
||||
}
|
||||
}
|
||||
|
||||
77
src/test/java/ru/ulstu/is/sbapp/JpaMusicTest.java
Normal file
77
src/test/java/ru/ulstu/is/sbapp/JpaMusicTest.java
Normal file
@@ -0,0 +1,77 @@
|
||||
package ru.ulstu.is.sbapp;
|
||||
|
||||
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.socialNetwork.models.Music;
|
||||
import ru.ulstu.is.sbapp.socialNetwork.services.MusicService;
|
||||
import ru.ulstu.is.sbapp.socialNetwork.services.MyUserService;
|
||||
|
||||
import javax.persistence.EntityNotFoundException;
|
||||
import java.util.List;
|
||||
|
||||
@SpringBootTest
|
||||
public class JpaMusicTest {
|
||||
private static final Logger log = LoggerFactory.getLogger(JpaUserTest.class);
|
||||
@Autowired
|
||||
MyUserService userService;
|
||||
|
||||
@Autowired
|
||||
MusicService musicService;
|
||||
|
||||
@Test
|
||||
void testMusicCreate() {
|
||||
musicService.deleteAllMusics();
|
||||
final Music music = musicService.addMusic("Song");
|
||||
log.info(music.toString());
|
||||
Assertions.assertNotNull(music.getId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testMusicReadNotFound() {
|
||||
musicService.deleteAllMusics();
|
||||
Assertions.assertThrows(EntityNotFoundException.class, () -> musicService.findMusic(-1L));
|
||||
}
|
||||
|
||||
@Test
|
||||
void findMusic() {
|
||||
musicService.deleteAllMusics();
|
||||
final Music music = musicService.addMusic("Song");
|
||||
log.info(musicService.toString());
|
||||
final Music findMusic = musicService.findMusic(music.getId());
|
||||
log.info(findMusic.toString());
|
||||
Assertions.assertEquals(music.toString(), findMusic.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testReadAll() {
|
||||
musicService.deleteAllMusics();
|
||||
final Music music = musicService.addMusic("Song");
|
||||
log.info(music.toString());
|
||||
final List<Music> musics = musicService.findAllMusics();
|
||||
Assertions.assertEquals(musics.size(), 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateMusic() {
|
||||
musicService.deleteAllMusics();
|
||||
final Music music = musicService.addMusic("Song");
|
||||
musicService.updateMusic(music.getId(), "Song 2");
|
||||
final Music findMusic = musicService.findMusic(music.getId());
|
||||
log.info(findMusic.toString());
|
||||
Assertions.assertEquals(findMusic.getName(), "Song 2");
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteMusic() {
|
||||
musicService.deleteAllMusics();
|
||||
final Music music = musicService.addMusic("Song");
|
||||
log.info(music.toString());
|
||||
musicService.deleteMusic(music.getId());
|
||||
Assertions.assertThrows(EntityNotFoundException.class, () -> userService.findUser(music.getId()));
|
||||
}
|
||||
}
|
||||
|
||||
113
src/test/java/ru/ulstu/is/sbapp/JpaUserTest.java
Normal file
113
src/test/java/ru/ulstu/is/sbapp/JpaUserTest.java
Normal file
@@ -0,0 +1,113 @@
|
||||
package ru.ulstu.is.sbapp;
|
||||
|
||||
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.socialNetwork.models.Community;
|
||||
import ru.ulstu.is.sbapp.socialNetwork.models.Music;
|
||||
import ru.ulstu.is.sbapp.socialNetwork.models.UserModel;
|
||||
import ru.ulstu.is.sbapp.socialNetwork.services.CommunityService;
|
||||
import ru.ulstu.is.sbapp.socialNetwork.services.MusicService;
|
||||
import ru.ulstu.is.sbapp.socialNetwork.services.MyUserService;
|
||||
|
||||
import javax.persistence.EntityNotFoundException;
|
||||
import java.util.List;
|
||||
|
||||
@SpringBootTest
|
||||
public class JpaUserTest {
|
||||
private static final Logger log = LoggerFactory.getLogger(JpaUserTest.class);
|
||||
@Autowired
|
||||
MyUserService userService;
|
||||
|
||||
@Autowired
|
||||
MusicService musicService;
|
||||
|
||||
@Autowired
|
||||
CommunityService communityService;
|
||||
|
||||
@Test
|
||||
void testUserCreate() {
|
||||
userService.deleteAllUsers();
|
||||
final UserModel user = userService.addUser("its_mailov", "Moscow");
|
||||
log.info(user.toString());
|
||||
Assertions.assertNotNull(user.getId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testUserReadNotFound() {
|
||||
userService.deleteAllUsers();
|
||||
Assertions.assertThrows(EntityNotFoundException.class, () -> userService.findUser(-1L));
|
||||
}
|
||||
|
||||
@Test
|
||||
void findUser() {
|
||||
userService.deleteAllUsers();
|
||||
final UserModel user = userService.addUser("its_mailov", "Moscow");
|
||||
log.info(user.toString());
|
||||
final UserModel findUser = userService.findUser(user.getId());
|
||||
log.info(findUser.toString());
|
||||
Assertions.assertEquals(user.toString(), findUser.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateUser() {
|
||||
userService.deleteAllUsers();
|
||||
final UserModel user = userService.addUser("its_mailov", "Moscow");
|
||||
userService.updateUser(user.getId(), "its_mailov 2");
|
||||
final UserModel findUser = userService.findUser(user.getId());
|
||||
log.info(findUser.toString());
|
||||
Assertions.assertEquals(findUser.getName(), "its_mailov 2");
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
void testReadAll() {
|
||||
userService.deleteAllUsers();
|
||||
final UserModel user = userService.addUser("its_mailov", "Moscow");
|
||||
log.info(user.toString());
|
||||
final List<UserModel> users = userService.findAllUsers();
|
||||
Assertions.assertEquals(users.size(), 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteUser() {
|
||||
userService.deleteAllUsers();
|
||||
final UserModel user = userService.addUser("its_mailov", "Moscow");
|
||||
log.info(user.toString());
|
||||
userService.deleteUser(user.getId());
|
||||
Assertions.assertThrows(EntityNotFoundException.class, () -> userService.findUser(user.getId()));
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
@Test
|
||||
void addMusic() {
|
||||
userService.deleteAllUsers();
|
||||
musicService.deleteAllMusics();
|
||||
final UserModel user = userService.addUser("its_mailov", "Moscow");
|
||||
final Music music = musicService.addMusic("Song");
|
||||
|
||||
userService.addMusic(user.getId(), music.getId());
|
||||
|
||||
final UserModel findUser = userService.findUser(user.getId());
|
||||
Assertions.assertEquals(findUser.getMusics().get(0).toString(), music.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void addGroup() {
|
||||
userService.deleteAllUsers();
|
||||
musicService.deleteAllMusics();
|
||||
final UserModel user = userService.addUser("its_mailov", "Moscow");
|
||||
final Community community = communityService.addCommunity("GPT");
|
||||
|
||||
userService.addCommunity(user.getId(), community.getId());
|
||||
|
||||
final UserModel findUser = userService.findUser(user.getId());
|
||||
Assertions.assertEquals(findUser.getGroups().get(0).getId(), community.getId());
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,78 @@
|
||||
package ru.ulstu.is.sbapp;
|
||||
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import ru.ulstu.is.sbapp.calculator.service.CalculatorService;
|
||||
|
||||
|
||||
@SpringBootTest
|
||||
class SbappApplicationTests {
|
||||
|
||||
@Autowired
|
||||
CalculatorService calculatorService;
|
||||
|
||||
@Test
|
||||
void contextLoads() {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testPlusInt() {
|
||||
final String res = calculatorService.Sum(10, 10, "int");
|
||||
Assertions.assertEquals(20, Integer.parseInt(res));
|
||||
}
|
||||
@Test
|
||||
void testMinusInt() {
|
||||
final String res = calculatorService.Ras(8, 4, "int");
|
||||
Assertions.assertEquals(4, Integer.parseInt(res));
|
||||
}
|
||||
@Test
|
||||
void testReverseInt() {
|
||||
final String res = calculatorService.Rev(10, 10, "int");
|
||||
Assertions.assertEquals(-20, Integer.parseInt(res));
|
||||
}
|
||||
@Test
|
||||
void testComparisonInt() {
|
||||
final String res = calculatorService.Com(8, 4, "int");
|
||||
Assertions.assertEquals(8, Integer.parseInt(res));
|
||||
}
|
||||
@Test
|
||||
void testPlusStr() {
|
||||
final String res = calculatorService.Sum("10", "10", "string");
|
||||
Assertions.assertEquals("1010", res);
|
||||
}
|
||||
@Test
|
||||
void testMinusStr() {
|
||||
final String res = calculatorService.Ras("846734", "4", "string");
|
||||
Assertions.assertEquals("8673", res);
|
||||
}
|
||||
@Test
|
||||
void testReverseStr() {
|
||||
final String res = calculatorService.Rev("846734", "312", "string");
|
||||
Assertions.assertEquals("213437648", res);
|
||||
}
|
||||
@Test
|
||||
void testComparisonStr() {
|
||||
final String res = calculatorService.Com("846734", "312", "string");
|
||||
Assertions.assertEquals("846734", res);
|
||||
}
|
||||
@Test
|
||||
void testNumberFormatException() {
|
||||
Assertions.assertThrows(NumberFormatException.class, () -> calculatorService.Sum("п", 3, "int"));
|
||||
}
|
||||
@Test
|
||||
void testSumDate(){
|
||||
final String res = calculatorService.Sum("2023-07-07", "0001-01-03", "date");
|
||||
Assertions.assertEquals("2024-08-10", res);
|
||||
}
|
||||
@Test
|
||||
void testRasDate(){
|
||||
final String res = calculatorService.Ras("2023-07-07", "2020-01-03", "date");
|
||||
Assertions.assertEquals("0003-06-04", res);
|
||||
}
|
||||
@Test
|
||||
void testComDate(){
|
||||
final String res = calculatorService.Com("2023-07-07", "2020-01-03", "date");
|
||||
Assertions.assertEquals("2023-07-07", res);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user