Compare commits

..

9 Commits

46 changed files with 32812 additions and 2 deletions

38
.gitignore vendored Normal file
View 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/

View File

@ -1,6 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project version="4"> <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" /> <output url="file://$PROJECT_DIR$/out" />
</component> </component>
<component name="ProjectType">
<option name="id" value="jpab" />
</component>
</project> </project>

View File

@ -2,7 +2,9 @@
<project version="4"> <project version="4">
<component name="ProjectModuleManager"> <component name="ProjectModuleManager">
<modules> <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> </modules>
</component> </component>
</project> </project>

37
build.gradle Normal file
View File

@ -0,0 +1,37 @@
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.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

Binary file not shown.

30502
front/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

43
front/package.json Normal file
View 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"
]
}
}

View 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>
)
}

View 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>
)
}

View 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>
)
}

View 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>
)
}

View 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

Binary file not shown.

After

Width:  |  Height:  |  Size: 54 KiB

BIN
gradle/wrapper/gradle-wrapper.jar vendored Normal file

Binary file not shown.

View 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
View 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
View 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
View File

@ -0,0 +1 @@
rootProject.name = 'sbapp'

View 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);
}
}

View File

@ -0,0 +1,29 @@
package ru.ulstu.is.sbapp;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfiguration implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedMethods("*");
}
public static final String REST_API = "/api";
@Override
public void addViewControllers(ViewControllerRegistry registry) {
WebMvcConfigurer.super.addViewControllers(registry);
registry.addViewController("users");
registry.addViewController("contacts");
registry.addViewController("catalogs");
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/css/**").addResourceLocations("/static/css/");
}
}

View File

@ -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);
}
}

View File

@ -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);
}

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -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())));
}
}

View File

@ -0,0 +1,44 @@
package ru.ulstu.is.sbapp.socialNetwork.controller;
import org.springframework.web.bind.annotation.*;
import ru.ulstu.is.sbapp.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));
}
}

View File

@ -0,0 +1,50 @@
package ru.ulstu.is.sbapp.socialNetwork.controller;
import org.springframework.web.bind.annotation.*;
import ru.ulstu.is.sbapp.WebConfiguration;
import ru.ulstu.is.sbapp.socialNetwork.dto.MusicDTO;
import ru.ulstu.is.sbapp.socialNetwork.models.Music;
import ru.ulstu.is.sbapp.socialNetwork.services.MusicService;
import org.springframework.web.bind.annotation.*;
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));
}
}

View File

@ -0,0 +1,68 @@
package ru.ulstu.is.sbapp.socialNetwork.controller;
import org.springframework.web.bind.annotation.*;
import ru.ulstu.is.sbapp.WebConfiguration;
import ru.ulstu.is.sbapp.socialNetwork.dto.UserDTO;
import ru.ulstu.is.sbapp.socialNetwork.models.UserModel;
import ru.ulstu.is.sbapp.socialNetwork.services.UserService;
import javax.validation.Valid;
import java.util.List;
@RestController
@RequestMapping(WebConfiguration.REST_API + "/users")
public class UserController {
private final UserService userService;
public UserController(UserService userService){
this.userService = userService;
}
@GetMapping("/{id}")
public UserDTO getUser(@PathVariable Long id) {
return new UserDTO(userService.findUser(id));
}
@GetMapping("")
public List<UserDTO> getUsers() {
return userService.findAllUsers().stream().map(UserDTO::new).toList();
}
@PostMapping("")
public UserDTO createUser(@RequestBody @Valid UserDTO user) {
UserModel result = userService.addUser(user.getName(), user.getCity());
userService.updateCommunities(result.getId(), user.getCommunity());
return new UserDTO(userService.updateMusics(result.getId(), user.getMusic()));
}
@PatchMapping("/{id}")
public UserDTO updateUser(@PathVariable Long id,
@RequestBody @Valid UserDTO user) {
UserModel result = userService.updateUser(id, user.getName());
userService.updateCommunities(result.getId(), user.getCommunity());
return new UserDTO(userService.updateMusics(result.getId(), user.getMusic()));
}
@PatchMapping("/add_music/{id}")
public UserDTO addMusic(@PathVariable Long id, @RequestParam Long music_id) {
return new UserDTO(userService.addMusic(id, music_id));
}
@PatchMapping("/add_community/{id}")
public UserDTO addCommunity(@PathVariable Long id, @RequestParam Long community_id) {
return new UserDTO(userService.addCommunity(id, community_id));
}
@GetMapping("/search")
public List<UserDTO> searchUsers(@RequestParam("city") String city) {
List<UserModel> users = userService.findUserByCity(city);
return users.stream().map(UserDTO::new).toList();
}
@DeleteMapping("/{id}")
public UserDTO deleteUser(@PathVariable Long id) {
return new UserDTO(userService.deleteUser(id));
}
}

View File

@ -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 + '\'' +
'}';
}
}

View File

@ -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 + '\'' +
'}';
}
}

View File

@ -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 UserDTO {
private Long id;
private String name;
private String city;
public UserDTO(){}
public UserDTO(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 UserDTO(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 + '\'' +
'}';
}
}

View File

@ -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 + '\'' +
'}';
}
}

View File

@ -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 + '\'' +
'}';
}
}

View File

@ -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 + '\'' +
'}';
}
}

View File

@ -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);
}

View File

@ -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);
}

View File

@ -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 UserRepository extends JpaRepository<UserModel, Long> {
List<UserModel> findByCity(String city);
}

View File

@ -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();
}
}

View File

@ -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();
}
}

View File

@ -0,0 +1,212 @@
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.UserRepository;
import javax.persistence.EntityNotFoundException;
import javax.persistence.Query;
import java.util.List;
import java.util.Optional;
@Service
public class UserService {
private UserRepository repo;
private CommunityService communityService;
private MusicService musicService;
public UserService(UserRepository 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();
}
}

View File

@ -0,0 +1,11 @@
spring.main.banner-mode=off
#server.port=8080
spring.datasource.url=jdbc:h2:file:./data
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto=update
spring.h2.console.enabled=true
spring.h2.console.settings.trace=false
spring.h2.console.settings.web-allow-others=false

View File

@ -0,0 +1,95 @@
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.UserService;
import javax.persistence.EntityNotFoundException;
import java.util.List;
@SpringBootTest
public class JpaCommunityTest {
private static final Logger log = LoggerFactory.getLogger(JpaUserTest.class);
@Autowired
UserService 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());
}
}

View 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.UserService;
import javax.persistence.EntityNotFoundException;
import java.util.List;
@SpringBootTest
public class JpaMusicTest {
private static final Logger log = LoggerFactory.getLogger(JpaUserTest.class);
@Autowired
UserService 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()));
}
}

View 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.UserService;
import javax.persistence.EntityNotFoundException;
import java.util.List;
@SpringBootTest
public class JpaUserTest {
private static final Logger log = LoggerFactory.getLogger(JpaUserTest.class);
@Autowired
UserService 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());
}
}

View 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);
}
}