Compare commits

...

No commits in common. "main" and "LabWork04" have entirely different histories.

39 changed files with 19501 additions and 24 deletions

56
.gitignore vendored
View File

@ -1,26 +1,38 @@
# ---> Java
# Compiled class file
*.class
HELP.md
.gradle
build/
!gradle/wrapper/gradle-wrapper.jar
!**/src/main/**/build/
!**/src/test/**/build/
lab4-vue-front/node_modules
# Log file
*.log
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
bin/
!**/src/main/**/bin/
!**/src/test/**/bin/
# BlueJ files
*.ctxt
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
out/
!**/src/main/**/out/
!**/src/test/**/out/
# Mobile Tools for Java (J2ME)
.mtj.tmp/
# Package Files #
*.jar
*.war
*.nar
*.ear
*.zip
*.tar.gz
*.rar
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
replay_pid*
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
### VS Code ###
.vscode/

View File

@ -1,2 +0,0 @@
# Minhasapov_IP_LabWork1

27
build.gradle Normal file
View File

@ -0,0 +1,27 @@
plugins {
id 'java'
id 'org.springframework.boot' version '3.0.2'
id 'io.spring.dependency-management' version '1.1.0'
}
group = 'ru.ulstu.is'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '17'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'com.h2database:h2:2.1.210'
implementation group: 'org.springdoc', name: 'springdoc-openapi-ui', version: '1.6.5'
implementation 'org.hibernate.validator:hibernate-validator'
implementation 'org.springdoc:springdoc-openapi-ui:1.6.5'
}
tasks.named('test') {
useJUnitPlatform()
}

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

19
lab4-vue-front/README.md Normal file
View File

@ -0,0 +1,19 @@
# lab4-vue-front
## Project setup
```
npm install
```
### Compiles and hot-reloads for development
```
npm run serve
```
### Compiles and minifies for production
```
npm run build
```
### Customize configuration
See [Configuration Reference](https://cli.vuejs.org/config/).

View File

@ -0,0 +1,5 @@
module.exports = {
presets: [
'@vue/cli-plugin-babel/preset'
]
}

View File

@ -0,0 +1,19 @@
{
"compilerOptions": {
"target": "es5",
"module": "esnext",
"baseUrl": "./",
"moduleResolution": "node",
"paths": {
"@/*": [
"src/*"
]
},
"lib": [
"esnext",
"dom",
"dom.iterable",
"scripthost"
]
}
}

17576
lab4-vue-front/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,29 @@
{
"name": "lab4_vue_front",
"version": "0.1.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build"
},
"dependencies": {
"@popperjs/core": "^2.11.7",
"axios": "^1.3.4",
"core-js": "^3.8.3",
"vue": "^3.2.13",
"vue-router": "^4.1.6",
"vuex": "^4.0.0"
},
"devDependencies": {
"@vue/cli-plugin-babel": "~5.0.0",
"@vue/cli-plugin-router": "~5.0.0",
"@vue/cli-plugin-vuex": "~5.0.0",
"@vue/cli-service": "~5.0.0"
},
"browserslist": [
"> 1%",
"last 2 versions",
"not dead",
"not ie 11"
]
}

View File

@ -0,0 +1,15 @@
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<link rel="stylesheet" href="https://unpkg.com/chota@latest">
<title>LabWork04 - Social Network</title>
</head>
<body>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
<div id="app"></div>
</body>
</html>

View File

@ -0,0 +1,48 @@
<template>
<div>
<p class='text-center m-3 h3'>LabWork04 - Social Network</p>
</div>
<div class="nav row">
<div class="nav-left col-4">
<router-link to="/customers" class="text-decoration-none m-3">Профили</router-link>
<router-link to="/posts" class="text-decoration-none m-3">Посты</router-link>
<select class="form-select mt-4" style="font-size: 16px; max-height: 35px; max-width: 180px;" v-model="currentCustomerId">
<option value="-1" selected class="button dark outline" :on-click="updateCurrentCustomer()">Не выбран</option>
<option v-for="customer in customers" v-bind:value="customer['id']" class="button dark outline" :on-click="updateCurrentCustomer()">{{ customer['username'] }}</option>
</select>
</div>
</div>
<router-view></router-view>
</template>
<script>
import axios from 'axios'
export default {
data() {
return {
currentCustomerId: -1,
customers: []
}
},
methods: {
async updateCurrentCustomer() {
history.replaceState(this.currentCustomerId, "");
}
},
async beforeMount() {
setInterval(async () => {
const response = await axios.get('http://localhost:8080/customer');
this.customers = [];
response.data.forEach(element => {
this.customers.push(element);
console.log(element);
});
}, 500)
},
}
</script>
<style lang="">
</style>

View File

@ -0,0 +1,154 @@
<template>
<div class="ms-5">
<p class='h4 m-3'>Пользователи</p>
<button type='button' class="btn btn-primary ms-3 mb-3" data-bs-toggle="modal" data-bs-target="#customerCreate">
Добавить нового пользователя
</button>
<p class='h4 ms-3'>Список</p>
<div class="row">
<div class="col-5">
<div v-for="customer in customers" class="row card is-left mb-3">
<div class="row is-left">
<div class="row is-left h3">{{ customer['username'] }}</div>
</div>
<p class="row is-left"></p>
<div class="row" v-if="!(customer['posts'].length == 0)">
<p class="h4">Посты:</p>
<div class="col">
<div v-for="post in customer['posts']" class="row is-left card mb-3">
<div class="row is-left h4">{{ post['title'] }}</div>
<div class="row is-left h5">{{ post['content'] }}</div>
</div>
</div>
</div>
<div class="row is-left" v-if="!(customer['comments'].length == 0)">
<p class="h4">Комментарии:</p>
<div class="col">
<div v-for="comment in customer['comments']" class="row is-left card mb-3">
<div class="row is-left h5">"{{ comment['content'] }}" - к посту '{{ comment['postTitle'] }}' от пользователя {{ comment['postAuthor'] }}</div>
</div>
</div>
</div>
<div class="row" v-if="customer['id'] == currentCustomerId">
<button v-on:click="deleteUser(customer['id'])" class="col button dark outline">Удалить</button>
<button v-on:click="selectedCustomer = customer; usernameModal=customer['username'];passwordModal=customer['password']" class="col button primary outline" data-bs-toggle="modal" data-bs-target="#customerEdit">Редактировать</button>
</div>
</div>
</div>
</div>
</div>
<!-- Modal -->
<div class="modal fade" id="customerCreate" tabindex="-1" role="dialog" aria-labelledby="customerCreateLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="customerCreateLabel">Создать пользователя</h5>
</div>
<div class="modal-body text-center">
<p>Имя пользователя</p>
<textarea v-model='usernameModal' id="usernameText" cols="30" rows="1"></textarea>
<p>Пароль</p>
<textarea v-model='passwordModal' id="passwordText" cols="30" rows="1"></textarea>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Отмена</button>
<button type="button" class="btn btn-primary" v-on:click='createUser'>Создать</button>
</div>
</div>
</div>
</div>
<!-- Modal -->
<div class="modal fade" id="customerEdit" tabindex="-1" role="dialog" aria-labelledby="customerEditLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="customerEditLabel">Изменение пользователя</h5>
</div>
<div class="modal-body text-center">
<p>Имя пользователя</p>
<textarea v-model='usernameModal' id="usernameText" cols="30" rows="1"></textarea>
<p>Пароль</p>
<textarea v-model='passwordModal' id="passwordText" cols="30" rows="1"></textarea>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Отмена</button>
<button type="button" class="btn btn-primary" v-on:click='editUser'>Применить</button>
</div>
</div>
</div>
</div>
</template>
<script>
import axios from 'axios'
export default {
data() {
return {
customers: [],
usernameModal: '',
passwordModal: '',
selectedCustomer: {},
currentCustomerId: -1
}
},
methods: {
async createUser(){
const response = await axios.post('http://localhost:8080/customer?username=' + this.usernameModal + '&password=' + this.passwordModal);
this.refreshList();
},
async deleteUser(id) {
const response = await axios.delete('http://localhost:8080/customer/' + id);
this.refreshList();
},
async editUser() {
const response = await axios.put('http://localhost:8080/customer/' + this.selectedCustomer['id'] + '?username=' + this.usernameModal + '&password=' + this.passwordModal);
this.refreshList();
},
async refreshList() {
this.customers = [];
if (this.$route.params.id === "") {
const response = await axios.get('http://localhost:8080/customer');
response.data.forEach(element => {
this.customers.push(element);
console.log(element);
});
} else {
const response = await axios.get('http://localhost:8080/customer/' + this.$route.params.id);
this.customers.push(response.data)
}
},
},
async mounted() {
this.currentCustomerId = history.state;
setInterval(async () => this.currentCustomerId = history.state, 50)
if (this.$route.params.id === "") {
const response = await axios.get('http://localhost:8080/customer');
response.data.forEach(element => {
this.customers.push(element);
console.log(element);
});
} else {
const response = await axios.get('http://localhost:8080/customer/' + this.$route.params.id);
this.customers.push(response.data)
}
},
async beforeRouteUpdate(to, from) {
this.$route.params.id = to.params.id;
this.refreshList();
},
}
</script>
<style lang="">
</style>

View File

@ -0,0 +1,275 @@
<template>
<div class="ms-5">
<div class="col-7">
<div class="row">
<input type="text" v-bind:id="'searchString'" class="col-4"/>
<button type="button" v-on:click="getSearchResult()" class="button col-2 secondary outline">Поиск</button>
<button type="button" v-on:click="searchMode = -1;" class="button col-2 secondary outline">Отмена</button>
</div>
</div>
<div v-if="!(searchMode == -1)">
<div v-if="!(searchResults.length == 0)" class="row">
<div class="col-5">
<div class="row mb-5 card" v-for="result in searchResults">
<div class="col">
<div v-if="result['title'] == null">
<div class="row is-left mt-2">
<span class="h3">Комментарий</span>
<!-- <p class="text-primary h2">Пользователь: {{ result['customerName'] }}</p> -->
<span class="h3">Контент: {{ result['content'] }}</span>
</div>
</div>
<div v-else>
<div class="row is-left mt-2">
<span class="h3">Пост</span>
<!-- <p class="text-primary h2">Пользователь: {{ result['customerName'] }}</p> -->
<span class="h3">Оглавление: {{ result['title'] }}</span>
<span class="h3">Контент: {{ result['content'] }}</span>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div v-if="searchMode == -1">
<p class='h3 m-3'>Посты</p>
<div class="row" v-if="currentCustomerId != -1">
<div class="col-7">
<div class="row is-left">
<p class="col-2 is-left mb-2">Заголовок:</p>
<input type="text" class="col-5" v-model="titleModal"/>
</div>
<div class="row is-left">
<p class="col-2 is-left mb-2">Текст:</p>
<textarea type="textarea" class="col-5" v-model="postContentModal"/>
</div>
<div class="row is-left">
<button type='button' class="button btn-primary col-7" v-on:click='createPost'>
Опубликовать
</button>
</div>
</div>
</div>
<div v-if="!(posts.length == 0)" class="row">
<div class="col-5">
<div class="row mb-5 card" v-for="post in posts">
<div class="col">
<div class="row is-left my-3">
<p class="h2"><router-link v-bind:to="'/customers/' + post['customerId']" class="text-primary">{{ post['customerName'] }}</router-link></p>
</div>
<div class="row text-left">
<span class="h2">{{ post['title'] }}</span>
<span class="h3">{{ post['content'] }}</span>
</div>
<div class="row">
<div v-if="!(post['comments'].length == 0)">
<p class="row h3 is-left my-3">Комментарии:</p>
<div class="row text-left mb-4 card" v-for="comment in post['comments']">
<div class="row is-left">
<span class="h2"><router-link v-bind:to="'/customers/' + post['customerId']" class="text-primary">{{ post['customerName'] }}</router-link></span>
<span class="h3">{{ comment['content'] }}</span>
</div>
<div v-if="selectedCustomerContainsComment(comment) == true" class="row mt-3">
<button v-on:click="selectedCommentId = comment['id']; selectedPostTitle = post['title']" class="button primary outline col" data-bs-toggle="modal" data-bs-target="#commentEdit">Изменить</button>
<button v-on:click="deleteComment(comment['id'])" class="button error col">Удалить</button>
</div>
</div>
</div>
<div class="row" v-if="currentCustomerId != -1">
<input type="text" v-bind:id="'post-comment-' + post['id']" class="col-7"/>
<button type="button" v-on:click="selectedPostId = post['id']; selectedPostTitle = post['title']; createComment()" class="button col-5 secondary outline">Комментировать</button>
</div>
</div>
<div class="row" v-if="post['customerId'] == currentCustomerId">
<button type="button" v-on:click="deletePost(post['id'])" class="col button dark outline">Удалить пост</button>
<button type="button" v-on:click="selectedPostId = post['id']" class="col button primary outline" data-bs-toggle="modal" data-bs-target="#postEdit">Изменить пост</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Modal -->
<div class="modal fade" id="postEdit" tabindex="-1" role="dialog" aria-labelledby="postEditLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="postEditLabel">Редактировать пост</h5>
</div>
<div class="modal-body text-center">
<p>{{ currentCustomer['username'] }}</p>
<p>Заголовок</p>
<textarea v-model='titleModal' id="editModalTitle" cols="30" rows="1"></textarea>
<p>Содержание</p>
<textarea v-model='postContentModal' id="editModalPostContent" cols="30" rows="1"></textarea>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Закрыть</button>
<button type="button" class="btn btn-primary" v-on:click='editPost'>Изменить</button>
</div>
</div>
</div>
</div>
<!-- Modal -->
<div class="modal fade" id="commentEdit" tabindex="-1" role="dialog" aria-labelledby="commentEditLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="commentEditLabel">Изменить комментарий</h5>
</div>
<div class="modal-body text-center">
<p>Под именем:</p>
<p>{{ currentCustomer['username'] }}</p>
<p>К посту:</p>
<p>{{ selectedPostTitle }}</p>
<p>Комментарий</p>
<textarea v-model='contentModal' id="editModalText" cols="30" rows="1"></textarea>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Закрыть</button>
<button type="button" class="btn btn-primary" v-on:click='editComment'>Изменить</button>
</div>
</div>
</div>
</div>
</template>
<script>
import axios from 'axios'
export default {
data() {
return {
searchResults: [],
customers: [],
selectedCustomerId: 0,
currentCustomer: {},
posts: [],
selectedPostId: 0,
selectedPostTitle: '',
contentModal: '',
titleModal: '',
postContentModal: '',
selectedCommentId: 0,
currentCustomerId: -1,
searchMode: -1,
}
},
methods: {
async getSearchResult(){
const content = document.getElementById("searchString").value
if (content != ''){
this.searchMode = 0;
this.searchResults = [];
const responseSearch = await axios.post('http://localhost:8080/search?searchStr=' + content);
responseSearch.data.forEach(element => {
this.searchResults.push(element);
console.log(element);
});
}
else{
this.searchMode = -1;
this.refreshList();
}
},
selectedCustomerContainsComment(comment) {
var customer = this.customers.find(element => element['id'] == this.currentCustomerId);
console.log(customer);
if (customer == null) return false;
var flag = false;
customer['comments'].forEach(commentIn => {
if (commentIn['id'] == comment['id']) {
flag = true;
}
});
return flag;
},
async createComment() {
const content = document.getElementById("post-comment-" + this.selectedPostId).value
await axios.post('http://localhost:8080/comment?text=' + content + '&ownerId=' + this.currentCustomerId + '&postId=' + this.selectedPostId);
document.getElementById("post-comment-" + this.selectedPostId).value = ''
this.refreshList();
},
async deleteComment(commentId) {
await axios.delete('http://localhost:8080/comment/' + commentId);
this.refreshList();
},
async editComment(){
await axios.put('http://localhost:8080/comment/' + this.selectedCommentId + '?text=' + this.contentModal);
this.refreshList();
},
async createPost() {
const response = await axios.post('http://localhost:8080/post?title=' + this.titleModal + '&content=' + this.postContentModal + '&authorId=' + this.currentCustomerId);
this.titleModal = ''
this.postContentModal = ''
this.refreshList();
},
async deletePost(postId) {
const response = await axios.delete('http://localhost:8080/post/' + postId);
this.refreshList();
},
async editPost(){
const response = await axios.put('http://localhost:8080/post/' + this.selectedPostId + '?title=' + this.titleModal + '&content=' + this.postContentModal);
this.refreshList();
},
async refreshList(){
this.customers = [];
this.posts = [];
const responseCustomer = await axios.get('http://localhost:8080/customer');
responseCustomer.data.forEach(element => {
this.customers.push(element);
console.log(element);
});
const responsePost = await axios.get('http://localhost:8080/post');
responsePost.data.forEach(element => {
this.posts.splice(0, 0, element);
console.log(element);
});
}
},
async beforeMount() {
this.currentCustomerId = history.state;
setInterval(async () => this.currentCustomerId = history.state, 50)
const responseCustomer = await axios.get('http://localhost:8080/customer');
responseCustomer.data.forEach(element => {
this.customers.push(element);
if (element['id'] == this.currentCustomerId) {
this.currentCustomer = element;
}
console.log(element);
});
const responsePost = await axios.get('http://localhost:8080/post');
responsePost.data.forEach(element => {
this.posts.splice(0, 0, element);
console.log(element);
});
}
}
</script>
<style lang="">
</style>

View File

@ -0,0 +1,29 @@
import {createApp} from 'vue'
import App from './App'
import { createRouter, createWebHistory } from "vue-router"
import Customers from './components/Customers'
import Posts from './components/Posts'
const routes = [
{
path: '/customers/:id?',
name: "Customers",
component: Customers,
props: true
},
{
path: '/posts',
name: "Posts",
component: Posts,
props: true
}
]
const router = createRouter({
routes,
history: createWebHistory()
})
createApp(App).use(router).mount('#app')

View File

@ -0,0 +1,4 @@
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
transpileDependencies: true
})

1
settings.gradle Normal file
View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -0,0 +1,34 @@
package ru.ulstu.is.labwork.Lab4.controller;
import org.springframework.web.bind.annotation.*;
import ru.ulstu.is.labwork.Lab4.DTO.CommentDto;
import ru.ulstu.is.labwork.Lab4.DTO.PostDto;
import ru.ulstu.is.labwork.Lab4.services.CommentService;
import ru.ulstu.is.labwork.Lab4.services.PostService;
import java.util.ArrayList;
import java.util.List;
@RestController
@RequestMapping("/search")
public class SearchController {
private final CommentService commentService;
private final PostService postService;
public SearchController(PostService postService, CommentService commentService){
this.commentService = commentService;
this.postService = postService;
}
@PostMapping
public List<Object> getResult(@RequestParam("searchStr") String searchStr) {
List<Object> result = new ArrayList<>();
result.addAll(commentService.findFilteredComments(searchStr).stream()
.map(CommentDto::new)
.toList());
result.addAll(postService.findFilteredPosts(searchStr).stream()
.map(PostDto::new)
.toList());
return result;
}
}

View File

@ -0,0 +1,67 @@
package ru.ulstu.is.labwork.Lab4.model;
import jakarta.persistence.*;
import java.util.Objects;
@Entity
public class Comment {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column
private String content;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name="customer_fk")
private Customer customer;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name="post_fk")
private Post post;
public Comment() {
}
public Comment(Customer customer, Post post, String content) {
this.customer = customer;
this.post = post;
this.content = content;
}
public Long getId() {
return id;
}
public Post getPost() {
return post;
}
public Customer getCustomer() {
return customer;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Comment comment = (Comment) o;
return Objects.equals(id, comment.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
}

View File

@ -0,0 +1,72 @@
package ru.ulstu.is.labwork.Lab4.model;
import jakarta.persistence.*;
import java.util.*;
@Entity
public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column
private String username;
@Column
private String password;
@OneToMany(fetch = FetchType.EAGER, mappedBy = "customer", cascade = CascadeType.ALL)
private List<Comment> comments;
@OneToMany(fetch = FetchType.EAGER, mappedBy = "customer", cascade = CascadeType.ALL)
private List<Post> posts;
public Customer() {
}
public Customer(String username, String password) {
this.username = username;
this.password = password;
this.comments = new ArrayList<>();
this.posts = new ArrayList<>();
}
public Long getId() {
return id;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public List<Comment> getComments() {
return comments;
}
public List<Post> getPosts() {
return posts;
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Customer customer = (Customer) obj;
return Objects.equals(id, customer.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
}

View File

@ -0,0 +1,79 @@
package ru.ulstu.is.labwork.Lab4.model;
import jakarta.persistence.*;
import java.util.ArrayList;
import java.util.List;
@Entity
public class Post {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column
private String title;
@Column
private String content;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "customer_fk")
private Customer customer;
@OneToMany(fetch = FetchType.EAGER, mappedBy = "post", cascade = CascadeType.ALL)
private List<Comment> comments;
public Post() {
}
public Post(Customer customer, String title, String content) {
this.customer = customer;
this.title = title;
this.content = content;
this.comments = new ArrayList<>();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Post post = (Post) o;
return id.equals(post.id);
}
@Override
public int hashCode() {
return id.hashCode();
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public List<Comment> getComments() {
return comments;
}
public Customer getCustomer() {
return customer;
}
public Long getId() {
return id;
}
}

View File

@ -0,0 +1,10 @@
package ru.ulstu.is.labwork.Lab4.repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import ru.ulstu.is.labwork.Lab4.model.Comment;
import java.util.List;
public interface CommentRepository extends JpaRepository<Comment, Long> {
List<Comment> findByContentLikeIgnoreCase(String text);
}

View File

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

View File

@ -0,0 +1,11 @@
package ru.ulstu.is.labwork.Lab4.repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import ru.ulstu.is.labwork.Lab4.model.Post;
import java.util.List;
public interface PostRepository extends JpaRepository<Post, Long> {
List<Post> findByContentLikeIgnoreCase(String text);
}

View File

@ -0,0 +1,79 @@
package ru.ulstu.is.labwork.Lab4.services;
import jakarta.persistence.EntityNotFoundException;
import jakarta.transaction.Transactional;
import ru.ulstu.is.labwork.Lab4.model.Comment;
import ru.ulstu.is.labwork.Lab4.model.Customer;
import ru.ulstu.is.labwork.Lab4.model.Post;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import ru.ulstu.is.labwork.Lab4.repositories.CommentRepository;
import java.util.List;
import java.util.Optional;
@Service
public class CommentService {
private final CommentRepository commentRepository;
public CommentService(CommentRepository commentRepository) {
this.commentRepository = commentRepository;
}
@Transactional
public List<Comment> findFilteredComments(String filter) {
return commentRepository.findByContentLikeIgnoreCase("%" + filter + "%");
}
@Transactional
public Comment findComment(Long id) {
final Optional<Comment> comment = commentRepository.findById(id);
return comment.orElseThrow(EntityNotFoundException::new);
}
@Transactional
public List<Comment> findAllComments() {
return commentRepository.findAll();
}
@Transactional
public Comment addComment(Customer customer, Post post, String content) {
if (customer == null || post == null) {
throw new IllegalArgumentException("Invalid customer or post");
}
if (!StringUtils.hasText(content)) {
throw new IllegalArgumentException("Invalid comment's content");
}
final Comment comment = new Comment(customer, post, content);
customer.getComments().add(comment);
post.getComments().add(comment);
return commentRepository.save(comment);
}
@Transactional
public Comment updateComment(Long id, String content) {
if (!StringUtils.hasText(content)) {
throw new IllegalArgumentException("Comment's content is empty");
}
final Comment currentComment = findComment(id);
currentComment.setContent(content);
return commentRepository.save(currentComment);
}
@Transactional
public Comment deleteComment(Long id) {
final Comment currentComment = findComment(id);
commentRepository.delete(currentComment);
currentComment.getPost().getComments().remove(currentComment);
currentComment.getCustomer().getComments().remove(currentComment);
return currentComment;
}
@Transactional
public void deleteAllComments() {
commentRepository.deleteAll();
}
}

View File

@ -0,0 +1,62 @@
package ru.ulstu.is.labwork.Lab4.services;
import jakarta.persistence.EntityNotFoundException;
import jakarta.transaction.Transactional;
import ru.ulstu.is.labwork.Lab4.model.Customer;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import ru.ulstu.is.labwork.Lab4.repositories.CustomerRepository;
import java.util.List;
import java.util.Optional;
@Service
public class CustomerService {
private final CustomerRepository customerRepository;
public CustomerService(CustomerRepository customerRepository) {
this.customerRepository = customerRepository;
}
@Transactional
public Customer findCustomer(Long id) {
final Optional<Customer> customer = customerRepository.findById(id);
return customer.orElseThrow(EntityNotFoundException::new);
}
@Transactional
public List<Customer> findAllCustomers() {
return customerRepository.findAll();
}
@Transactional
public Customer addCustomer(String username, String password) {
if (!StringUtils.hasText(username) || !StringUtils.hasText(password)) {
throw new IllegalArgumentException("Customer's username or password is empty");
}
Customer customer = new Customer(username, password);
return customerRepository.save(customer);
}
@Transactional
public Customer updateCustomer(Long id, String username, String password) {
if (!StringUtils.hasText(username) || !StringUtils.hasText(password)) {
throw new IllegalArgumentException("Customer's username or password is empty");
}
Customer customer = findCustomer(id);
customer.setUsername(username);
customer.setPassword(password);
return customerRepository.save(customer);
}
@Transactional
public Customer deleteCustomer(Long id) {
Customer customer = findCustomer(id);
customerRepository.delete(customer);
return customer;
}
@Transactional
public void deleteAllCustomers() {
customerRepository.deleteAll();
}
}

View File

@ -0,0 +1,75 @@
package ru.ulstu.is.labwork.Lab4.services;
import jakarta.persistence.EntityNotFoundException;
import jakarta.transaction.Transactional;
import ru.ulstu.is.labwork.Lab4.model.Comment;
import ru.ulstu.is.labwork.Lab4.model.Customer;
import ru.ulstu.is.labwork.Lab4.model.Post;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import ru.ulstu.is.labwork.Lab4.repositories.CommentRepository;
import ru.ulstu.is.labwork.Lab4.repositories.PostRepository;
import java.util.List;
import java.util.Optional;
@Service
public class PostService {
private final PostRepository postRepository;
public PostService(PostRepository postRepository) {
this.postRepository = postRepository;
}
@Transactional
public List<Post> findFilteredPosts(String filter) {
return postRepository.findByContentLikeIgnoreCase("%" + filter + "%");
}
@Transactional
public Post findPost(Long id) {
final Optional<Post> post = postRepository.findById(id);
return post.orElseThrow(EntityNotFoundException::new);
}
@Transactional
public List<Post> findAllPosts() {
return postRepository.findAll();
}
@Transactional
public Post addPost(Customer customer, String title, String content) {
if (customer == null) {
throw new IllegalArgumentException("Invalid customer");
}
if (!StringUtils.hasText(title) | !StringUtils.hasText(content)) {
throw new IllegalArgumentException("Invalid post's content or title");
}
Post post = new Post(customer, title, content);
customer.getPosts().add(post);
return postRepository.save(post);
}
@Transactional
public Post updatePost(Long id, String title, String content) {
if (!StringUtils.hasText(content) | !StringUtils.hasText(title)) {
throw new IllegalArgumentException("Post's content or title is empty");
}
Post post = findPost(id);
post.setTitle(title);
post.setContent(content);
return postRepository.save(post);
}
@Transactional
public Post deletePost(Long id) {
Post post = findPost(id);
post.getCustomer().getPosts().remove(post);
postRepository.delete(post);
return post;
}
@Transactional
public void deleteAllPosts() {
postRepository.deleteAll();
}
}

View File

@ -0,0 +1,13 @@
package ru.ulstu.is.labwork;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class LabworkApplication {
public static void main(String[] args) {
SpringApplication.run(LabworkApplication.class, args);
}
}

View File

@ -0,0 +1,13 @@
package ru.ulstu.is.labwork;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfiguration implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedMethods("*");
}
}

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