Compare commits
11 Commits
master
...
Lab06_(rea
Author | SHA1 | Date | |
---|---|---|---|
e4299bcfcb | |||
9b3faa72e2 | |||
0e637791ef | |||
93464f7382 | |||
72166d3a35 | |||
c8f79a0d98 | |||
a3de182a22 | |||
1423f5da0b | |||
21c085917a | |||
f3f0e851ed | |||
eed0b46ad4 |
38
.gitignore
vendored
Normal file
38
.gitignore
vendored
Normal file
@ -0,0 +1,38 @@
|
||||
HELP.md
|
||||
.gradle
|
||||
build/
|
||||
!gradle/wrapper/gradle-wrapper.jar
|
||||
!**/src/main/**/build/
|
||||
!**/src/test/**/build/
|
||||
*node_modules/*
|
||||
|
||||
### STS ###
|
||||
.apt_generated
|
||||
.classpath
|
||||
.factorypath
|
||||
.project
|
||||
.settings
|
||||
.springBeans
|
||||
.sts4-cache
|
||||
bin/
|
||||
!**/src/main/**/bin/
|
||||
!**/src/test/**/bin/
|
||||
|
||||
### IntelliJ IDEA ###
|
||||
.idea
|
||||
*.iws
|
||||
*.iml
|
||||
*.ipr
|
||||
out/
|
||||
!**/src/main/**/out/
|
||||
!**/src/test/**/out/
|
||||
|
||||
### NetBeans ###
|
||||
/nbproject/private/
|
||||
/nbbuild/
|
||||
/dist/
|
||||
/nbdist/
|
||||
/.nb-gradle/
|
||||
|
||||
### VS Code ###
|
||||
.vscode/
|
@ -1,6 +1,10 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ProjectRootManager">
|
||||
<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>
|
@ -2,7 +2,9 @@
|
||||
<project version="4">
|
||||
<component name="ProjectModuleManager">
|
||||
<modules>
|
||||
<module fileurl="file://$PROJECT_DIR$/.idea/IP_Ismailov_Pibd-22.iml" filepath="$PROJECT_DIR$/.idea/IP_Ismailov_Pibd-22.iml" />
|
||||
<module fileurl="file://$PROJECT_DIR$/.idea/modules/sbapp.iml" filepath="$PROJECT_DIR$/.idea/modules/sbapp.iml" />
|
||||
<module fileurl="file://$PROJECT_DIR$/.idea/modules/sbapp.main.iml" filepath="$PROJECT_DIR$/.idea/modules/sbapp.main.iml" />
|
||||
<module fileurl="file://$PROJECT_DIR$/.idea/modules/sbapp.test.iml" filepath="$PROJECT_DIR$/.idea/modules/sbapp.test.iml" />
|
||||
</modules>
|
||||
</component>
|
||||
</project>
|
41
build.gradle
Normal file
41
build.gradle
Normal file
@ -0,0 +1,41 @@
|
||||
plugins {
|
||||
id 'java'
|
||||
id 'org.springframework.boot' version '2.7.8'
|
||||
id 'io.spring.dependency-management' version '1.0.15.RELEASE'
|
||||
}
|
||||
|
||||
group = 'ru.ulstu.is'
|
||||
version = '0.0.1-SNAPSHOT'
|
||||
sourceCompatibility = '17'
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
}
|
||||
|
||||
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 'com.auth0:java-jwt:4.4.0'
|
||||
|
||||
implementation 'org.springdoc:springdoc-openapi-ui:1.6.5'
|
||||
|
||||
testImplementation 'org.springframework.boot:spring-boot-starter-test'
|
||||
}
|
||||
|
||||
tasks.named('test') {
|
||||
useJUnitPlatform()
|
||||
}
|
BIN
data.mv.db
Normal file
BIN
data.mv.db
Normal file
Binary file not shown.
30502
front/package-lock.json
generated
Normal file
30502
front/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
43
front/package.json
Normal file
43
front/package.json
Normal file
@ -0,0 +1,43 @@
|
||||
{
|
||||
"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",
|
||||
"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>
|
||||
)
|
||||
}
|
76
front/src/components/pages/Login.jsx
Normal file
76
front/src/components/pages/Login.jsx
Normal file
@ -0,0 +1,76 @@
|
||||
import { useState } from "react"
|
||||
import { NavLink, useNavigate } from "react-router-dom";
|
||||
import './form.css';
|
||||
|
||||
|
||||
export default function Film() {
|
||||
const [data, setData] = useState({
|
||||
login: "",
|
||||
password: ""
|
||||
});
|
||||
const navigate = useNavigate();
|
||||
|
||||
const [isError, setError] = useState(false);
|
||||
|
||||
const handleFormChange = (e) => {
|
||||
setData({ ...data, [e.target.id]: e.target.value });
|
||||
}
|
||||
|
||||
const formSubmit = async (e) => {
|
||||
e.preventDefault();
|
||||
const requestParams = {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({ login: data.login, password: data.password }),
|
||||
};
|
||||
const response = await fetch("http://localhost:8080/jwt/login", requestParams);
|
||||
const result = await response.text();
|
||||
if (response.status === 200) {
|
||||
setError(false);
|
||||
localStorage.setItem("token", result);
|
||||
localStorage.setItem("user", data.login);
|
||||
getRole(result);
|
||||
} else {
|
||||
setError(true);
|
||||
localStorage.removeItem("token");
|
||||
localStorage.removeItem("user");
|
||||
localStorage.removeItem("role");
|
||||
}
|
||||
}
|
||||
|
||||
const getRole = async function (token) {
|
||||
const requestParams = {
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Content-Type": "application/json"
|
||||
}
|
||||
};
|
||||
const requestUrl = `http://localhost:8080/user?token=${token}`;
|
||||
const response = await fetch(requestUrl, requestParams);
|
||||
const result = await response.text();
|
||||
localStorage.setItem("role", result);
|
||||
window.dispatchEvent(new Event("storage"));
|
||||
navigate("/");
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
{isError && <div class="alert alert-warning" role="alert">
|
||||
Неверный логин или пароль
|
||||
</div>}
|
||||
|
||||
<form onSubmit={formSubmit} className="form">
|
||||
<label htmlFor="name" className="form-label">Логин</label>
|
||||
<input type="text" value={data.name} id="login" className="form-control" required autoComplete="off"
|
||||
onChange={handleFormChange} />
|
||||
<label htmlFor="surname" className="form-label">Пароль</label>
|
||||
<input type="password" value={data.surname} id="password" className="form-control" required autoComplete="off"
|
||||
onChange={handleFormChange} />
|
||||
<button type="submit" className="btn btn-success mt-2 me-2">Вход</button>
|
||||
<NavLink type="submit" className="btn btn-info mt-2" to="/signup">Регистрация</NavLink>
|
||||
</form>
|
||||
</>
|
||||
)
|
||||
}
|
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 |
BIN
gradle/wrapper/gradle-wrapper.jar
vendored
Normal file
BIN
gradle/wrapper/gradle-wrapper.jar
vendored
Normal file
Binary file not shown.
5
gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
5
gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
@ -0,0 +1,5 @@
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-7.6-bin.zip
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
240
gradlew
vendored
Normal file
240
gradlew
vendored
Normal file
@ -0,0 +1,240 @@
|
||||
#!/bin/sh
|
||||
|
||||
#
|
||||
# Copyright © 2015-2021 the original authors.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# https://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
|
||||
##############################################################################
|
||||
#
|
||||
# Gradle start up script for POSIX generated by Gradle.
|
||||
#
|
||||
# Important for running:
|
||||
#
|
||||
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
|
||||
# noncompliant, but you have some other compliant shell such as ksh or
|
||||
# bash, then to run this script, type that shell name before the whole
|
||||
# command line, like:
|
||||
#
|
||||
# ksh Gradle
|
||||
#
|
||||
# Busybox and similar reduced shells will NOT work, because this script
|
||||
# requires all of these POSIX shell features:
|
||||
# * functions;
|
||||
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
|
||||
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
|
||||
# * compound commands having a testable exit status, especially «case»;
|
||||
# * various built-in commands including «command», «set», and «ulimit».
|
||||
#
|
||||
# Important for patching:
|
||||
#
|
||||
# (2) This script targets any POSIX shell, so it avoids extensions provided
|
||||
# by Bash, Ksh, etc; in particular arrays are avoided.
|
||||
#
|
||||
# The "traditional" practice of packing multiple parameters into a
|
||||
# space-separated string is a well documented source of bugs and security
|
||||
# problems, so this is (mostly) avoided, by progressively accumulating
|
||||
# options in "$@", and eventually passing that to Java.
|
||||
#
|
||||
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
|
||||
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
|
||||
# see the in-line comments for details.
|
||||
#
|
||||
# There are tweaks for specific operating systems such as AIX, CygWin,
|
||||
# Darwin, MinGW, and NonStop.
|
||||
#
|
||||
# (3) This script is generated from the Groovy template
|
||||
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
||||
# within the Gradle project.
|
||||
#
|
||||
# You can find Gradle at https://github.com/gradle/gradle/.
|
||||
#
|
||||
##############################################################################
|
||||
|
||||
# Attempt to set APP_HOME
|
||||
|
||||
# Resolve links: $0 may be a link
|
||||
app_path=$0
|
||||
|
||||
# Need this for daisy-chained symlinks.
|
||||
while
|
||||
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
|
||||
[ -h "$app_path" ]
|
||||
do
|
||||
ls=$( ls -ld "$app_path" )
|
||||
link=${ls#*' -> '}
|
||||
case $link in #(
|
||||
/*) app_path=$link ;; #(
|
||||
*) app_path=$APP_HOME$link ;;
|
||||
esac
|
||||
done
|
||||
|
||||
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
|
||||
|
||||
APP_NAME="Gradle"
|
||||
APP_BASE_NAME=${0##*/}
|
||||
|
||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||
|
||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||
MAX_FD=maximum
|
||||
|
||||
warn () {
|
||||
echo "$*"
|
||||
} >&2
|
||||
|
||||
die () {
|
||||
echo
|
||||
echo "$*"
|
||||
echo
|
||||
exit 1
|
||||
} >&2
|
||||
|
||||
# OS specific support (must be 'true' or 'false').
|
||||
cygwin=false
|
||||
msys=false
|
||||
darwin=false
|
||||
nonstop=false
|
||||
case "$( uname )" in #(
|
||||
CYGWIN* ) cygwin=true ;; #(
|
||||
Darwin* ) darwin=true ;; #(
|
||||
MSYS* | MINGW* ) msys=true ;; #(
|
||||
NONSTOP* ) nonstop=true ;;
|
||||
esac
|
||||
|
||||
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
|
||||
|
||||
|
||||
# Determine the Java command to use to start the JVM.
|
||||
if [ -n "$JAVA_HOME" ] ; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD=$JAVA_HOME/jre/sh/java
|
||||
else
|
||||
JAVACMD=$JAVA_HOME/bin/java
|
||||
fi
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
else
|
||||
JAVACMD=java
|
||||
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
|
||||
# Increase the maximum file descriptors if we can.
|
||||
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
||||
case $MAX_FD in #(
|
||||
max*)
|
||||
MAX_FD=$( ulimit -H -n ) ||
|
||||
warn "Could not query maximum file descriptor limit"
|
||||
esac
|
||||
case $MAX_FD in #(
|
||||
'' | soft) :;; #(
|
||||
*)
|
||||
ulimit -n "$MAX_FD" ||
|
||||
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
||||
esac
|
||||
fi
|
||||
|
||||
# Collect all arguments for the java command, stacking in reverse order:
|
||||
# * args from the command line
|
||||
# * the main class name
|
||||
# * -classpath
|
||||
# * -D...appname settings
|
||||
# * --module-path (only if needed)
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
|
||||
|
||||
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||
if "$cygwin" || "$msys" ; then
|
||||
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
|
||||
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
|
||||
|
||||
JAVACMD=$( cygpath --unix "$JAVACMD" )
|
||||
|
||||
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||
for arg do
|
||||
if
|
||||
case $arg in #(
|
||||
-*) false ;; # don't mess with options #(
|
||||
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
|
||||
[ -e "$t" ] ;; #(
|
||||
*) false ;;
|
||||
esac
|
||||
then
|
||||
arg=$( cygpath --path --ignore --mixed "$arg" )
|
||||
fi
|
||||
# Roll the args list around exactly as many times as the number of
|
||||
# args, so each arg winds up back in the position where it started, but
|
||||
# possibly modified.
|
||||
#
|
||||
# NB: a `for` loop captures its iteration list before it begins, so
|
||||
# changing the positional parameters here affects neither the number of
|
||||
# iterations, nor the values presented in `arg`.
|
||||
shift # remove old arg
|
||||
set -- "$@" "$arg" # push replacement arg
|
||||
done
|
||||
fi
|
||||
|
||||
# Collect all arguments for the java command;
|
||||
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
|
||||
# shell script including quotes and variable substitutions, so put them in
|
||||
# double quotes to make sure that they get re-expanded; and
|
||||
# * put everything else in single quotes, so that it's not re-expanded.
|
||||
|
||||
set -- \
|
||||
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||
-classpath "$CLASSPATH" \
|
||||
org.gradle.wrapper.GradleWrapperMain \
|
||||
"$@"
|
||||
|
||||
# Stop when "xargs" is not available.
|
||||
if ! command -v xargs >/dev/null 2>&1
|
||||
then
|
||||
die "xargs is not available"
|
||||
fi
|
||||
|
||||
# Use "xargs" to parse quoted args.
|
||||
#
|
||||
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
|
||||
#
|
||||
# In Bash we could simply go:
|
||||
#
|
||||
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
|
||||
# set -- "${ARGS[@]}" "$@"
|
||||
#
|
||||
# but POSIX shell has neither arrays nor command substitution, so instead we
|
||||
# post-process each arg (as a line of input to sed) to backslash-escape any
|
||||
# character that might be a shell metacharacter, then use eval to reverse
|
||||
# that process (while maintaining the separation between arguments), and wrap
|
||||
# the whole thing up as a single "set" statement.
|
||||
#
|
||||
# This will of course break if any of these variables contains a newline or
|
||||
# an unmatched quote.
|
||||
#
|
||||
|
||||
eval "set -- $(
|
||||
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
|
||||
xargs -n1 |
|
||||
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
|
||||
tr '\n' ' '
|
||||
)" '"$@"'
|
||||
|
||||
exec "$JAVACMD" "$@"
|
91
gradlew.bat
vendored
Normal file
91
gradlew.bat
vendored
Normal file
@ -0,0 +1,91 @@
|
||||
@rem
|
||||
@rem Copyright 2015 the original author or authors.
|
||||
@rem
|
||||
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
||||
@rem you may not use this file except in compliance with the License.
|
||||
@rem You may obtain a copy of the License at
|
||||
@rem
|
||||
@rem https://www.apache.org/licenses/LICENSE-2.0
|
||||
@rem
|
||||
@rem Unless required by applicable law or agreed to in writing, software
|
||||
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
||||
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
@rem See the License for the specific language governing permissions and
|
||||
@rem limitations under the License.
|
||||
@rem
|
||||
|
||||
@if "%DEBUG%"=="" @echo off
|
||||
@rem ##########################################################################
|
||||
@rem
|
||||
@rem Gradle startup script for Windows
|
||||
@rem
|
||||
@rem ##########################################################################
|
||||
|
||||
@rem Set local scope for the variables with windows NT shell
|
||||
if "%OS%"=="Windows_NT" setlocal
|
||||
|
||||
set DIRNAME=%~dp0
|
||||
if "%DIRNAME%"=="" set DIRNAME=.
|
||||
set APP_BASE_NAME=%~n0
|
||||
set APP_HOME=%DIRNAME%
|
||||
|
||||
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
|
||||
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
|
||||
|
||||
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
|
||||
|
||||
@rem Find java.exe
|
||||
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||
|
||||
set JAVA_EXE=java.exe
|
||||
%JAVA_EXE% -version >NUL 2>&1
|
||||
if %ERRORLEVEL% equ 0 goto execute
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
:findJavaFromJavaHome
|
||||
set JAVA_HOME=%JAVA_HOME:"=%
|
||||
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||
|
||||
if exist "%JAVA_EXE%" goto execute
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
:execute
|
||||
@rem Setup the command line
|
||||
|
||||
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
|
||||
|
||||
|
||||
@rem Execute Gradle
|
||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
|
||||
|
||||
:end
|
||||
@rem End local scope for the variables with windows NT shell
|
||||
if %ERRORLEVEL% equ 0 goto mainEnd
|
||||
|
||||
:fail
|
||||
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
||||
rem the _cmd.exe /c_ return code!
|
||||
set EXIT_CODE=%ERRORLEVEL%
|
||||
if %EXIT_CODE% equ 0 set EXIT_CODE=1
|
||||
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
|
||||
exit /b %EXIT_CODE%
|
||||
|
||||
:mainEnd
|
||||
if "%OS%"=="Windows_NT" endlocal
|
||||
|
||||
:omega
|
1
settings.gradle
Normal file
1
settings.gradle
Normal file
@ -0,0 +1 @@
|
||||
rootProject.name = 'sbapp'
|
16
src/main/java/ru/ulstu/is/sbapp/SbappApplication.java
Normal file
16
src/main/java/ru/ulstu/is/sbapp/SbappApplication.java
Normal file
@ -0,0 +1,16 @@
|
||||
package ru.ulstu.is.sbapp;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@SpringBootApplication
|
||||
@RestController
|
||||
public class SbappApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(SbappApplication.class, args);
|
||||
}
|
||||
}
|
@ -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,29 @@
|
||||
package ru.ulstu.is.sbapp.configuration;
|
||||
|
||||
import io.swagger.v3.oas.models.Components;
|
||||
import io.swagger.v3.oas.models.OpenAPI;
|
||||
import io.swagger.v3.oas.models.security.SecurityRequirement;
|
||||
import io.swagger.v3.oas.models.security.SecurityScheme;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import ru.ulstu.is.sbapp.configuration.jwt.JwtFilter;
|
||||
|
||||
|
||||
@Configuration
|
||||
public class OpenAPI30Configuration {
|
||||
public static final String API_PREFIX = "/api/1.0";
|
||||
|
||||
@Bean
|
||||
public OpenAPI customizeOpenAPI() {
|
||||
final String securitySchemeName = JwtFilter.TOKEN_BEGIN_STR;
|
||||
return new OpenAPI()
|
||||
.addSecurityItem(new SecurityRequirement()
|
||||
.addList(securitySchemeName))
|
||||
.components(new Components()
|
||||
.addSecuritySchemes(securitySchemeName, new SecurityScheme()
|
||||
.name(securitySchemeName)
|
||||
.type(SecurityScheme.Type.HTTP)
|
||||
.scheme("bearer")
|
||||
.bearerFormat("JWT")));
|
||||
}
|
||||
}
|
@ -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 passwordEncoder() {
|
||||
return new BCryptPasswordEncoder();
|
||||
}
|
||||
}
|
@ -0,0 +1,77 @@
|
||||
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.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.builders.WebSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
|
||||
import org.springframework.security.config.http.SessionCreationPolicy;
|
||||
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
|
||||
import ru.ulstu.is.sbapp.configuration.jwt.JwtFilter;
|
||||
import ru.ulstu.is.sbapp.socialNetwork.controller.MyUserController;
|
||||
import ru.ulstu.is.sbapp.socialNetwork.controller.UserController;
|
||||
import ru.ulstu.is.sbapp.socialNetwork.models.UserRole;
|
||||
import ru.ulstu.is.sbapp.socialNetwork.services.UserService;
|
||||
|
||||
@Configuration
|
||||
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
|
||||
private final Logger log = LoggerFactory.getLogger(SecurityConfiguration.class);
|
||||
|
||||
public static final String SPA_URL_MASK = "/{path:[^\\.]*}";
|
||||
|
||||
private final UserService userService;
|
||||
private final JwtFilter jwtFilter;
|
||||
|
||||
public SecurityConfiguration(UserService userService) {
|
||||
this.userService = userService;
|
||||
this.jwtFilter = new JwtFilter(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 {
|
||||
log.info("Creating security configuration");
|
||||
http.cors()
|
||||
.and()
|
||||
.csrf().disable()
|
||||
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
|
||||
.and()
|
||||
.authorizeRequests()
|
||||
.antMatchers("/", SPA_URL_MASK).permitAll()
|
||||
.antMatchers(HttpMethod.POST, UserController.URL_SIGNUP).permitAll()
|
||||
.antMatchers(HttpMethod.POST, UserController.URL_LOGIN).permitAll()
|
||||
.anyRequest()
|
||||
.authenticated()
|
||||
.and()
|
||||
.addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class)
|
||||
.anonymous();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void configure(AuthenticationManagerBuilder builder) throws Exception {
|
||||
builder.userDetailsService(userService);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void configure(WebSecurity web) {
|
||||
web
|
||||
.ignoring()
|
||||
.antMatchers(HttpMethod.OPTIONS, "/**")
|
||||
.antMatchers("/**/*.{js,html,css,png}")
|
||||
.antMatchers("/swagger-ui/index.html")
|
||||
.antMatchers("/webjars/**")
|
||||
.antMatchers("/swagger-resources/**")
|
||||
.antMatchers("/v3/api-docs/**");
|
||||
}
|
||||
}
|
@ -0,0 +1,40 @@
|
||||
package ru.ulstu.is.sbapp.configuration;
|
||||
|
||||
import org.springframework.boot.web.server.ErrorPage;
|
||||
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
|
||||
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.http.HttpStatus;
|
||||
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 {
|
||||
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");
|
||||
}
|
||||
|
||||
@Bean
|
||||
public WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> containerCustomizer() {
|
||||
return container -> container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/notFound"));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addCorsMappings(CorsRegistry registry) {
|
||||
registry.addMapping("/**").allowedMethods("*");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addResourceHandlers(ResourceHandlerRegistry registry) {
|
||||
registry.addResourceHandler("/static/css/**").addResourceLocations("/static/css/");
|
||||
}
|
||||
}
|
@ -0,0 +1,11 @@
|
||||
package ru.ulstu.is.sbapp.configuration.jwt;
|
||||
|
||||
public class JwtException extends RuntimeException {
|
||||
public JwtException(Throwable throwable) {
|
||||
super(throwable);
|
||||
}
|
||||
|
||||
public JwtException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
@ -0,0 +1,72 @@
|
||||
package ru.ulstu.is.sbapp.configuration.jwt;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.filter.GenericFilterBean;
|
||||
import ru.ulstu.is.sbapp.socialNetwork.services.UserService;
|
||||
|
||||
import javax.servlet.FilterChain;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.ServletRequest;
|
||||
import javax.servlet.ServletResponse;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
|
||||
public class JwtFilter extends GenericFilterBean {
|
||||
private static final String AUTHORIZATION = "Authorization";
|
||||
public static final String TOKEN_BEGIN_STR = "Bearer ";
|
||||
|
||||
private final UserService userService;
|
||||
|
||||
public JwtFilter(UserService userService) {
|
||||
this.userService = userService;
|
||||
}
|
||||
|
||||
private String getTokenFromRequest(HttpServletRequest request) {
|
||||
String bearer = request.getHeader(AUTHORIZATION);
|
||||
if (StringUtils.hasText(bearer) && bearer.startsWith(TOKEN_BEGIN_STR)) {
|
||||
return bearer.substring(TOKEN_BEGIN_STR.length());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private void raiseException(ServletResponse response, int status, String message) throws IOException {
|
||||
if (response instanceof final HttpServletResponse httpResponse) {
|
||||
httpResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
|
||||
httpResponse.setStatus(status);
|
||||
final byte[] body = new ObjectMapper().writeValueAsBytes(message);
|
||||
response.getOutputStream().write(body);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void doFilter(ServletRequest request,
|
||||
ServletResponse response,
|
||||
FilterChain chain) throws IOException, ServletException {
|
||||
if (request instanceof final HttpServletRequest httpRequest) {
|
||||
final String token = getTokenFromRequest(httpRequest);
|
||||
if (StringUtils.hasText(token)) {
|
||||
try {
|
||||
final UserDetails user = userService.loadUserByToken(token);
|
||||
final UsernamePasswordAuthenticationToken auth =
|
||||
new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
|
||||
SecurityContextHolder.getContext().setAuthentication(auth);
|
||||
} catch (JwtException e) {
|
||||
raiseException(response, HttpServletResponse.SC_UNAUTHORIZED, e.getMessage());
|
||||
return;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
raiseException(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
|
||||
String.format("Internal error: %s", e.getMessage()));
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
chain.doFilter(request, response);
|
||||
}
|
||||
}
|
@ -0,0 +1,27 @@
|
||||
package ru.ulstu.is.sbapp.configuration.jwt;
|
||||
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
@ConfigurationProperties(prefix = "jwt", ignoreInvalidFields = true)
|
||||
public class JwtProperties {
|
||||
private String devToken = "";
|
||||
private Boolean isDev = true;
|
||||
|
||||
public String getDevToken() {
|
||||
return devToken;
|
||||
}
|
||||
|
||||
public void setDevToken(String devToken) {
|
||||
this.devToken = devToken;
|
||||
}
|
||||
|
||||
public Boolean isDev() {
|
||||
return isDev;
|
||||
}
|
||||
|
||||
public void setDev(Boolean dev) {
|
||||
isDev = dev;
|
||||
}
|
||||
}
|
@ -0,0 +1,107 @@
|
||||
package ru.ulstu.is.sbapp.configuration.jwt;
|
||||
|
||||
import com.auth0.jwt.JWT;
|
||||
import com.auth0.jwt.algorithms.Algorithm;
|
||||
import com.auth0.jwt.exceptions.JWTVerificationException;
|
||||
import com.auth0.jwt.interfaces.DecodedJWT;
|
||||
import com.auth0.jwt.interfaces.JWTVerifier;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.time.LocalDate;
|
||||
import java.time.ZoneId;
|
||||
import java.util.Date;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
@Component
|
||||
public class JwtProvider {
|
||||
private final static Logger LOG = LoggerFactory.getLogger(JwtProvider.class);
|
||||
|
||||
private final static byte[] HEX_ARRAY = "0123456789ABCDEF".getBytes(StandardCharsets.US_ASCII);
|
||||
private final static String ISSUER = "auth0";
|
||||
|
||||
private final Algorithm algorithm;
|
||||
private final JWTVerifier verifier;
|
||||
|
||||
public JwtProvider(JwtProperties jwtProperties) {
|
||||
if (!jwtProperties.isDev()) {
|
||||
LOG.info("Generate new JWT key for prod");
|
||||
try {
|
||||
final MessageDigest salt = MessageDigest.getInstance("SHA-256");
|
||||
salt.update(UUID.randomUUID().toString().getBytes(StandardCharsets.UTF_8));
|
||||
LOG.info("Use generated JWT key for prod \n{}", bytesToHex(salt.digest()));
|
||||
algorithm = Algorithm.HMAC256(bytesToHex(salt.digest()));
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new JwtException(e);
|
||||
}
|
||||
} else {
|
||||
LOG.info("Use default JWT key for dev \n{}", jwtProperties.getDevToken());
|
||||
algorithm = Algorithm.HMAC256(jwtProperties.getDevToken());
|
||||
}
|
||||
verifier = JWT.require(algorithm)
|
||||
.withIssuer(ISSUER)
|
||||
.build();
|
||||
}
|
||||
|
||||
private static String bytesToHex(byte[] bytes) {
|
||||
byte[] hexChars = new byte[bytes.length * 2];
|
||||
for (int j = 0; j < bytes.length; j++) {
|
||||
int v = bytes[j] & 0xFF;
|
||||
hexChars[j * 2] = HEX_ARRAY[v >>> 4];
|
||||
hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];
|
||||
}
|
||||
return new String(hexChars, StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
public String generateToken(String login) {
|
||||
final Date issueDate = Date.from(LocalDate.now()
|
||||
.atStartOfDay(ZoneId.systemDefault())
|
||||
.toInstant());
|
||||
final Date expireDate = Date.from(LocalDate.now()
|
||||
.plusDays(15)
|
||||
.atStartOfDay(ZoneId.systemDefault())
|
||||
.toInstant());
|
||||
return JWT.create()
|
||||
.withIssuer(ISSUER)
|
||||
.withIssuedAt(issueDate)
|
||||
.withExpiresAt(expireDate)
|
||||
.withSubject(login)
|
||||
.sign(algorithm);
|
||||
}
|
||||
|
||||
private DecodedJWT validateToken(String token) {
|
||||
try {
|
||||
return verifier.verify(token);
|
||||
} catch (JWTVerificationException e) {
|
||||
throw new JwtException(String.format("Token verification error: %s", e.getMessage()));
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isTokenValid(String token) {
|
||||
if (!StringUtils.hasText(token)) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
validateToken(token);
|
||||
return true;
|
||||
} catch (JwtException e) {
|
||||
LOG.error(e.getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public Optional<String> getLoginFromToken(String token) {
|
||||
try {
|
||||
return Optional.ofNullable(validateToken(token).getSubject());
|
||||
} catch (JwtException e) {
|
||||
LOG.error(e.getMessage());
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
}
|
@ -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 MyUserController {
|
||||
private final MyUserService userService;
|
||||
|
||||
public MyUserController(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,58 @@
|
||||
package ru.ulstu.is.sbapp.socialNetwork.controller;
|
||||
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.security.access.annotation.Secured;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import ru.ulstu.is.sbapp.socialNetwork.dto.UserDto;
|
||||
import ru.ulstu.is.sbapp.socialNetwork.dto.UserInfoDTO;
|
||||
import ru.ulstu.is.sbapp.socialNetwork.dto.UsersPageDTO;
|
||||
import ru.ulstu.is.sbapp.socialNetwork.models.User;
|
||||
import ru.ulstu.is.sbapp.socialNetwork.models.UserRole;
|
||||
import ru.ulstu.is.sbapp.socialNetwork.services.UserService;
|
||||
|
||||
import javax.validation.Valid;
|
||||
import java.util.List;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
@RestController
|
||||
public class UserController {
|
||||
public static final String URL_LOGIN = "/jwt/login";
|
||||
public static final String URL_SIGNUP = "/jwt/signup";
|
||||
|
||||
private final UserService userService;
|
||||
|
||||
public UserController(UserService userService) {
|
||||
this.userService = userService;
|
||||
}
|
||||
|
||||
@GetMapping("/user")
|
||||
public String findUser(@RequestParam("token") String token) {
|
||||
UserDetails userDetails = userService.loadUserByToken(token);
|
||||
User user = userService.findByLogin(userDetails.getUsername());
|
||||
return user.getRole().toString();
|
||||
}
|
||||
@GetMapping("/users")
|
||||
@Secured({UserRole.AsString.ADMIN})
|
||||
public UsersPageDTO getUsers(@RequestParam(defaultValue = "1") int page,
|
||||
@RequestParam(defaultValue = "5") int size) {
|
||||
final Page<UserDto> users = userService.findAllPages(page, size)
|
||||
.map(UserDto::new);
|
||||
final int totalPages = users.getTotalPages();
|
||||
final List<Integer> pageNumbers = IntStream.rangeClosed(1, totalPages)
|
||||
.boxed()
|
||||
.toList();
|
||||
return new UsersPageDTO(users, pageNumbers, totalPages);
|
||||
}
|
||||
|
||||
|
||||
@PostMapping(URL_SIGNUP)
|
||||
public UserInfoDTO signup(@RequestBody @Valid UserDto userDto) {
|
||||
return userService.signupAndGetToken(userDto);
|
||||
}
|
||||
|
||||
@PostMapping(URL_LOGIN)
|
||||
public String login(@RequestBody @Valid UserDto userDto) {
|
||||
return userService.loginAndGetToken(userDto);
|
||||
}
|
||||
}
|
@ -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,38 @@
|
||||
package ru.ulstu.is.sbapp.socialNetwork.dto;
|
||||
|
||||
import ru.ulstu.is.sbapp.socialNetwork.models.User;
|
||||
import ru.ulstu.is.sbapp.socialNetwork.models.UserRole;
|
||||
|
||||
import javax.validation.constraints.NotEmpty;
|
||||
|
||||
public class UserDto {
|
||||
@NotEmpty
|
||||
private String login;
|
||||
@NotEmpty
|
||||
private String password;
|
||||
private UserRole role;
|
||||
private String passwordConfirm;
|
||||
|
||||
public UserDto(User user) {
|
||||
this.login = user.getLogin();
|
||||
this.password = user.getPassword();
|
||||
this.role = user.getRole();
|
||||
}
|
||||
|
||||
public UserDto() {}
|
||||
|
||||
public String getLogin() {
|
||||
return login;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
public String getPasswordConfirm() {
|
||||
return passwordConfirm;
|
||||
}
|
||||
|
||||
public UserRole getRole() {
|
||||
return role;
|
||||
}
|
||||
}
|
@ -0,0 +1,27 @@
|
||||
package ru.ulstu.is.sbapp.socialNetwork.dto;
|
||||
|
||||
|
||||
import ru.ulstu.is.sbapp.socialNetwork.models.UserRole;
|
||||
|
||||
public class UserInfoDTO {
|
||||
private final String token;
|
||||
private String login;
|
||||
private final UserRole role;
|
||||
public UserInfoDTO(String token, String login, UserRole role) {
|
||||
this.token = token;
|
||||
this.login = login;
|
||||
this.role = role;
|
||||
}
|
||||
|
||||
public String getToken() {
|
||||
return token;
|
||||
}
|
||||
|
||||
public UserRole getRole() {
|
||||
|
||||
return role;
|
||||
}
|
||||
public String getLogin() {
|
||||
return login;
|
||||
}
|
||||
}
|
@ -0,0 +1,29 @@
|
||||
package ru.ulstu.is.sbapp.socialNetwork.dto;
|
||||
|
||||
import org.springframework.data.domain.Page;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class UsersPageDTO {
|
||||
private Page<UserDto> users;
|
||||
private List<Integer> pageNumbers;
|
||||
private int totalPages;
|
||||
|
||||
public UsersPageDTO(Page<UserDto> users, List<Integer> pageNumbers, int totalPages) {
|
||||
this.users = users;
|
||||
this.pageNumbers = pageNumbers;
|
||||
this.totalPages = totalPages;
|
||||
}
|
||||
|
||||
public Page<UserDto> getUsers() {
|
||||
return users;
|
||||
}
|
||||
|
||||
public List<Integer> getPageNumbers() {
|
||||
return pageNumbers;
|
||||
}
|
||||
|
||||
public int getTotalPages() {
|
||||
return totalPages;
|
||||
}
|
||||
}
|
@ -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,7 @@
|
||||
package ru.ulstu.is.sbapp.socialNetwork.services;
|
||||
|
||||
public class UserExistsException extends RuntimeException {
|
||||
public UserExistsException(String login) {
|
||||
super(String.format("User '%s' already exists", login));
|
||||
}
|
||||
}
|
@ -0,0 +1,7 @@
|
||||
package ru.ulstu.is.sbapp.socialNetwork.services;
|
||||
|
||||
public class UserNotFoundException extends RuntimeException {
|
||||
public UserNotFoundException(String login) {
|
||||
super(String.format("User not found '%s'", login));
|
||||
}
|
||||
}
|
@ -0,0 +1,99 @@
|
||||
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.configuration.jwt.JwtException;
|
||||
import ru.ulstu.is.sbapp.configuration.jwt.JwtProvider;
|
||||
import ru.ulstu.is.sbapp.socialNetwork.dto.UserDto;
|
||||
import ru.ulstu.is.sbapp.socialNetwork.dto.UserInfoDTO;
|
||||
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;
|
||||
private final JwtProvider jwtProvider;
|
||||
|
||||
public UserService(UserRepository userRepository,
|
||||
PasswordEncoder passwordEncoder,
|
||||
ValidatorUtil validatorUtil,
|
||||
JwtProvider jwtProvider) {
|
||||
this.userRepository = userRepository;
|
||||
this.passwordEncoder = passwordEncoder;
|
||||
this.validatorUtil = validatorUtil;
|
||||
this.jwtProvider = jwtProvider;
|
||||
}
|
||||
|
||||
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 UserExistsException(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);
|
||||
}
|
||||
|
||||
public String loginAndGetToken(UserDto userDto) {
|
||||
final User user = findByLogin(userDto.getLogin());
|
||||
if (user == null) {
|
||||
throw new UserNotFoundException(userDto.getLogin());
|
||||
}
|
||||
if (!passwordEncoder.matches(userDto.getPassword(), user.getPassword())) {
|
||||
throw new UserNotFoundException(user.getLogin());
|
||||
}
|
||||
return jwtProvider.generateToken(user.getLogin());
|
||||
}
|
||||
|
||||
public UserDetails loadUserByToken(String token) throws UsernameNotFoundException {
|
||||
if (!jwtProvider.isTokenValid(token)) {
|
||||
throw new JwtException("Bad token");
|
||||
}
|
||||
final String userLogin = jwtProvider.getLoginFromToken(token)
|
||||
.orElseThrow(() -> new JwtException("Token is not contain Login"));
|
||||
return loadUserByUsername(userLogin);
|
||||
}
|
||||
|
||||
@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()));
|
||||
}
|
||||
|
||||
public UserInfoDTO signupAndGetToken(UserDto userDto) {
|
||||
final User user = createUser(userDto.getLogin(), userDto.getPassword(), userDto.getPasswordConfirm(), UserRole.USER);
|
||||
return new UserInfoDTO(jwtProvider.generateToken(user.getLogin()), user.getLogin(), UserRole.USER);
|
||||
}
|
||||
}
|
@ -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()));
|
||||
}
|
||||
}
|
||||
}
|
13
src/main/resources/application.properties
Normal file
13
src/main/resources/application.properties
Normal file
@ -0,0 +1,13 @@
|
||||
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
|
||||
jwt.dev-token=my-secret-jwt
|
||||
jwt.dev=true
|
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());
|
||||
|
||||
}
|
||||
}
|
78
src/test/java/ru/ulstu/is/sbapp/SbappApplicationTests.java
Normal file
78
src/test/java/ru/ulstu/is/sbapp/SbappApplicationTests.java
Normal file
@ -0,0 +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);
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user