ALL
This commit is contained in:
parent
52e76173ea
commit
d3150467f2
1
Lab 2.1
Submodule
1
Lab 2.1
Submodule
@ -0,0 +1 @@
|
||||
Subproject commit d6b549408acb6551f0edb675a13048a887b7d90c
|
37
Lab 2.2/.gitignore
vendored
Normal file
37
Lab 2.2/.gitignore
vendored
Normal file
@ -0,0 +1,37 @@
|
||||
HELP.md
|
||||
.gradle
|
||||
build/
|
||||
!gradle/wrapper/gradle-wrapper.jar
|
||||
!**/src/main/**/build/
|
||||
!**/src/test/**/build/
|
||||
|
||||
### 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/
|
29
Lab 2.2/build.gradle
Normal file
29
Lab 2.2/build.gradle
Normal file
@ -0,0 +1,29 @@
|
||||
plugins {
|
||||
id 'java'
|
||||
id 'org.springframework.boot' version '3.2.3'
|
||||
id 'io.spring.dependency-management' version '1.1.4'
|
||||
}
|
||||
|
||||
group = 'com.example'
|
||||
version = '0.0.1-SNAPSHOT'
|
||||
|
||||
java {
|
||||
sourceCompatibility = '17'
|
||||
}
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation 'org.springframework.boot:spring-boot-starter-web'
|
||||
implementation 'org.springframework.boot:spring-boot-starter-validation'
|
||||
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.3.0'
|
||||
implementation 'org.modelmapper:modelmapper:3.2.0'
|
||||
|
||||
testImplementation 'org.springframework.boot:spring-boot-starter-test'
|
||||
}
|
||||
|
||||
tasks.named('test') {
|
||||
useJUnitPlatform()
|
||||
}
|
BIN
Lab 2.2/gradle/wrapper/gradle-wrapper.jar
vendored
Normal file
BIN
Lab 2.2/gradle/wrapper/gradle-wrapper.jar
vendored
Normal file
Binary file not shown.
7
Lab 2.2/gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
7
Lab 2.2/gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
@ -0,0 +1,7 @@
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip
|
||||
networkTimeout=10000
|
||||
validateDistributionUrl=true
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
249
Lab 2.2/gradlew
vendored
Normal file
249
Lab 2.2/gradlew
vendored
Normal file
@ -0,0 +1,249 @@
|
||||
#!/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/HEAD/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
|
||||
|
||||
# This is normally unused
|
||||
# shellcheck disable=SC2034
|
||||
APP_BASE_NAME=${0##*/}
|
||||
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
|
||||
APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit
|
||||
|
||||
# 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
|
||||
if ! command -v java >/dev/null 2>&1
|
||||
then
|
||||
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
|
||||
fi
|
||||
|
||||
# Increase the maximum file descriptors if we can.
|
||||
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
||||
case $MAX_FD in #(
|
||||
max*)
|
||||
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC2039,SC3045
|
||||
MAX_FD=$( ulimit -H -n ) ||
|
||||
warn "Could not query maximum file descriptor limit"
|
||||
esac
|
||||
case $MAX_FD in #(
|
||||
'' | soft) :;; #(
|
||||
*)
|
||||
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC2039,SC3045
|
||||
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
|
||||
|
||||
|
||||
# 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"'
|
||||
|
||||
# Collect all arguments for the java command:
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
|
||||
# and any embedded shellness will be escaped.
|
||||
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
|
||||
# treated as '${Hostname}' itself on the command line.
|
||||
|
||||
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" "$@"
|
92
Lab 2.2/gradlew.bat
vendored
Normal file
92
Lab 2.2/gradlew.bat
vendored
Normal file
@ -0,0 +1,92 @@
|
||||
@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=.
|
||||
@rem This is normally unused
|
||||
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
Lab 2.2/settings.gradle
Normal file
1
Lab 2.2/settings.gradle
Normal file
@ -0,0 +1 @@
|
||||
rootProject.name = 'demo'
|
54
Lab 2.2/src/main/java/com/example/demo/DemoApplication.java
Normal file
54
Lab 2.2/src/main/java/com/example/demo/DemoApplication.java
Normal file
@ -0,0 +1,54 @@
|
||||
package com.example.demo;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.Date;
|
||||
import java.text.SimpleDateFormat;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.boot.CommandLineRunner;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
import com.example.demo.news.model.NewsEntity;
|
||||
import com.example.demo.news.service.NewsService;
|
||||
import com.example.demo.types.model.TypeEntity;
|
||||
import com.example.demo.types.service.TypeService;
|
||||
import com.example.demo.users.model.UserEntity;
|
||||
import com.example.demo.users.service.UserService;
|
||||
|
||||
@SpringBootApplication
|
||||
public class DemoApplication implements CommandLineRunner {
|
||||
private final Logger log = LoggerFactory.getLogger(DemoApplication.class);
|
||||
|
||||
private final TypeService typeService;
|
||||
private final UserService userService;
|
||||
private final NewsService itemService;
|
||||
|
||||
public DemoApplication(TypeService typeNews, UserService userService, NewsService itemNews) {
|
||||
|
||||
this.typeService = typeNews;
|
||||
this.userService = userService;
|
||||
this.itemService = itemNews;
|
||||
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(DemoApplication.class, args);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run(String... args) throws Exception {
|
||||
if (args.length > 0 && Objects.equals("--populate", args[0])) {
|
||||
log.info("Create default types values");
|
||||
final var type1 = typeService.create(new TypeEntity(null, "По поводу отчислений"));
|
||||
final var user1 = userService.create(new UserEntity(null, "user1", "123", "admin"));
|
||||
log.info("Create default items values");
|
||||
|
||||
String dateString = "25.03.2024";
|
||||
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
|
||||
Date parsedDate = (java.util.Date) sdf.parse(dateString);
|
||||
itemService.create(new NewsEntity(null, type1, user1, "rgre", "dggd", (java.util.Date) parsedDate));
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,8 @@
|
||||
package com.example.demo.core.configuration;
|
||||
|
||||
public class Constants {
|
||||
public static final String API_URL = "/api/1.0";
|
||||
|
||||
private Constants() {
|
||||
}
|
||||
}
|
@ -0,0 +1,13 @@
|
||||
package com.example.demo.core.configuration;
|
||||
|
||||
import org.modelmapper.ModelMapper;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
public class MapperConfiguration {
|
||||
@Bean
|
||||
ModelMapper modelMapper() {
|
||||
return new ModelMapper();
|
||||
}
|
||||
}
|
@ -0,0 +1,15 @@
|
||||
package com.example.demo.core.configuration;
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.lang.NonNull;
|
||||
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(@NonNull CorsRegistry registry) {
|
||||
registry.addMapping("/**")
|
||||
.allowedMethods("GET", "POST", "PUT", "DELETE");
|
||||
}
|
||||
}
|
@ -0,0 +1,7 @@
|
||||
package com.example.demo.core.error;
|
||||
|
||||
public class NotFoundException extends RuntimeException {
|
||||
public NotFoundException(Long id) {
|
||||
super(String.format("Entity with id [%s] is not found or not exists", id));
|
||||
}
|
||||
}
|
@ -0,0 +1,20 @@
|
||||
package com.example.demo.core.model;
|
||||
|
||||
public abstract class BaseEntity {
|
||||
protected Long id;
|
||||
|
||||
protected BaseEntity() {
|
||||
}
|
||||
|
||||
protected BaseEntity(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
}
|
@ -0,0 +1,17 @@
|
||||
package com.example.demo.core.repository;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface CommonRepository<E, T> {
|
||||
List<E> getAll();
|
||||
|
||||
E get(T id);
|
||||
|
||||
E create(E entity);
|
||||
|
||||
E update(E entity);
|
||||
|
||||
E delete(E entity);
|
||||
|
||||
void deleteAll();
|
||||
}
|
@ -0,0 +1,57 @@
|
||||
package com.example.demo.core.repository;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.TreeMap;
|
||||
|
||||
import com.example.demo.core.model.BaseEntity;
|
||||
|
||||
public abstract class MapRepository<E extends BaseEntity> implements CommonRepository<E, Long> {
|
||||
private final Map<Long, E> entities = new TreeMap<>();
|
||||
private Long lastId = 0L;
|
||||
|
||||
protected MapRepository() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<E> getAll() {
|
||||
return entities.values().stream().toList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public E get(Long id) {
|
||||
return entities.get(id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public E create(E entity) {
|
||||
lastId++;
|
||||
entity.setId(lastId);
|
||||
entities.put(lastId, entity);
|
||||
return entity;
|
||||
}
|
||||
|
||||
@Override
|
||||
public E update(E entity) {
|
||||
if (get(entity.getId()) == null) {
|
||||
return null;
|
||||
}
|
||||
entities.put(entity.getId(), entity);
|
||||
return entity;
|
||||
}
|
||||
|
||||
@Override
|
||||
public E delete(E entity) {
|
||||
if (get(entity.getId()) == null) {
|
||||
return null;
|
||||
}
|
||||
entities.remove(entity.getId());
|
||||
return entity;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deleteAll() {
|
||||
lastId = 0L;
|
||||
entities.clear();
|
||||
}
|
||||
}
|
@ -0,0 +1,75 @@
|
||||
package com.example.demo.news.api;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.modelmapper.ModelMapper;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import com.example.demo.core.configuration.Constants;
|
||||
import com.example.demo.news.model.NewsEntity;
|
||||
import com.example.demo.news.service.NewsService;
|
||||
import com.example.demo.types.service.TypeService;
|
||||
import com.example.demo.users.service.UserService;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
|
||||
@RestController
|
||||
@RequestMapping(Constants.API_URL + "/news")
|
||||
public class NewsController {
|
||||
private final NewsService newsService;
|
||||
private final TypeService typeService;
|
||||
private final UserService userService;
|
||||
private final ModelMapper modelMapper;
|
||||
|
||||
public NewsController(NewsService newsService, TypeService typeService, UserService userService,
|
||||
ModelMapper modelMapper) {
|
||||
this.newsService = newsService;
|
||||
this.typeService = typeService;
|
||||
this.userService = userService;
|
||||
this.modelMapper = modelMapper;
|
||||
}
|
||||
|
||||
private NewsDto toDto(NewsEntity entity) {
|
||||
return modelMapper.map(entity, NewsDto.class);
|
||||
}
|
||||
|
||||
private NewsEntity toEntity(NewsDto dto) {
|
||||
final NewsEntity entity = modelMapper.map(dto, NewsEntity.class);
|
||||
entity.setType(typeService.get(dto.getTypeId()));
|
||||
entity.setHandle(userService.get(dto.getUserId()));
|
||||
return entity;
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public List<NewsDto> getAll(@RequestParam(name = "typeId", defaultValue = "1") Long typeId) {
|
||||
return newsService.getAll(typeId).stream().map(this::toDto).toList();
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public NewsDto get(@PathVariable(name = "id") Long id) {
|
||||
return toDto(newsService.get(id));
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public NewsDto create(@RequestBody @Valid NewsDto dto) {
|
||||
return toDto(newsService.create(toEntity(dto)));
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
public NewsDto update(@PathVariable(name = "id") Long id, @RequestBody NewsDto dto) {
|
||||
return toDto(newsService.update(id, toEntity(dto)));
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
public NewsDto delete(@PathVariable(name = "id") Long id) {
|
||||
return toDto(newsService.delete(id));
|
||||
}
|
||||
}
|
69
Lab 2.2/src/main/java/com/example/demo/news/api/NewsDto.java
Normal file
69
Lab 2.2/src/main/java/com/example/demo/news/api/NewsDto.java
Normal file
@ -0,0 +1,69 @@
|
||||
package com.example.demo.news.api;
|
||||
|
||||
import java.sql.Date;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
|
||||
public class NewsDto {
|
||||
private Long id;
|
||||
@NotNull
|
||||
private Long typeId;
|
||||
@NotNull
|
||||
private Long userId;
|
||||
@NotNull
|
||||
private String title;
|
||||
@NotNull
|
||||
private String text;
|
||||
@NotNull
|
||||
private Date date;
|
||||
|
||||
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public Long getTypeId() {
|
||||
return typeId;
|
||||
}
|
||||
|
||||
public void setTypeId(Long typeId) {
|
||||
this.typeId = typeId;
|
||||
}
|
||||
|
||||
public Long getUserId() {
|
||||
return userId;
|
||||
}
|
||||
|
||||
public void setUserId(Long userId) {
|
||||
this.userId = userId;
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
|
||||
public void setTitle(String title) {
|
||||
this.title = title;
|
||||
}
|
||||
|
||||
public String getText() {
|
||||
return text;
|
||||
}
|
||||
|
||||
public void setText(String text) {
|
||||
this.text = text;
|
||||
}
|
||||
|
||||
public Date getDate() {
|
||||
return date;
|
||||
}
|
||||
|
||||
public void setDate(Date date) {
|
||||
this.date = date;
|
||||
}
|
||||
}
|
@ -0,0 +1,90 @@
|
||||
package com.example.demo.news.model;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.Objects;
|
||||
|
||||
import com.example.demo.core.model.BaseEntity;
|
||||
import com.example.demo.types.model.TypeEntity;
|
||||
import com.example.demo.users.model.UserEntity;
|
||||
|
||||
public class NewsEntity extends BaseEntity {
|
||||
private TypeEntity type;
|
||||
private UserEntity handle;
|
||||
private String title;
|
||||
private String text;
|
||||
private Date date;
|
||||
|
||||
public NewsEntity() {
|
||||
super();
|
||||
}
|
||||
|
||||
public NewsEntity(Long id, TypeEntity type, UserEntity handle, String title, String text, Date date) {
|
||||
super(id);
|
||||
this.type = type;
|
||||
this.handle = handle;
|
||||
this.title = title;
|
||||
this.text = text;
|
||||
this.date = date;
|
||||
}
|
||||
|
||||
public TypeEntity getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public void setType(TypeEntity type) {
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
public UserEntity getHandle() {
|
||||
return handle;
|
||||
}
|
||||
|
||||
public void setHandle(UserEntity handle) {
|
||||
this.handle = handle;
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
|
||||
public void setTitle(String title) {
|
||||
this.title = title;
|
||||
}
|
||||
|
||||
public String getText() {
|
||||
return text;
|
||||
}
|
||||
|
||||
public void setText(String text) {
|
||||
this.text = text;
|
||||
}
|
||||
|
||||
public Date getDate() {
|
||||
return date;
|
||||
}
|
||||
|
||||
public void setDate(Date date) {
|
||||
this.date = date;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(id, type, title, text, date);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null || getClass() != obj.getClass())
|
||||
return false;
|
||||
final NewsEntity other = (NewsEntity) obj;
|
||||
return Objects.equals(other.getId(), id)
|
||||
&& Objects.equals(other.getType(), type)
|
||||
&& Objects.equals(other.getHandle(), handle)
|
||||
&& Objects.equals(other.getTitle(), title)
|
||||
|
||||
&& Objects.equals(other.getText(), text)
|
||||
&& Objects.equals(other.getDate(), date);
|
||||
}
|
||||
}
|
@ -0,0 +1,10 @@
|
||||
package com.example.demo.news.repository;
|
||||
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import com.example.demo.core.repository.MapRepository;
|
||||
import com.example.demo.news.model.NewsEntity;
|
||||
|
||||
@Repository
|
||||
public class NewsRepository extends MapRepository<NewsEntity> {
|
||||
}
|
@ -0,0 +1,53 @@
|
||||
package com.example.demo.news.service;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import com.example.demo.core.error.NotFoundException;
|
||||
import com.example.demo.news.model.NewsEntity;
|
||||
import com.example.demo.news.repository.NewsRepository;
|
||||
|
||||
@Service
|
||||
public class NewsService {
|
||||
private final NewsRepository repository;
|
||||
|
||||
public NewsService(NewsRepository repository) {
|
||||
this.repository = repository;
|
||||
}
|
||||
|
||||
public List<NewsEntity> getAll(Long typeId) {
|
||||
if (Objects.equals(typeId, 0L)) {
|
||||
return repository.getAll();
|
||||
}
|
||||
return repository.getAll().stream()
|
||||
.filter(item -> item.getType().getId().equals(typeId))
|
||||
.toList();
|
||||
}
|
||||
|
||||
public NewsEntity get(Long id) {
|
||||
return Optional.ofNullable(repository.get(id))
|
||||
.orElseThrow(() -> new NotFoundException(id));
|
||||
}
|
||||
|
||||
public NewsEntity create(NewsEntity entity) {
|
||||
return repository.create(entity);
|
||||
}
|
||||
|
||||
public NewsEntity update(Long id, NewsEntity entity) {
|
||||
final NewsEntity existsEntity = get(id);
|
||||
existsEntity.setType(entity.getType());
|
||||
existsEntity.setHandle(entity.getHandle());
|
||||
existsEntity.setTitle(entity.getTitle());
|
||||
existsEntity.setText(entity.getText());
|
||||
existsEntity.setDate(entity.getDate());
|
||||
return repository.update(existsEntity);
|
||||
}
|
||||
|
||||
public NewsEntity delete(Long id) {
|
||||
final NewsEntity existsEntity = get(id);
|
||||
return repository.delete(existsEntity);
|
||||
}
|
||||
}
|
@ -0,0 +1,77 @@
|
||||
package com.example.demo.reviews.api;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.modelmapper.ModelMapper;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import com.example.demo.core.configuration.Constants;
|
||||
import com.example.demo.reviews.model.ReviewEntity;
|
||||
import com.example.demo.reviews.service.ReviewService;
|
||||
import com.example.demo.users.service.UserService;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
|
||||
@RestController
|
||||
@RequestMapping(Constants.API_URL + "/review")
|
||||
public class ReviewController {
|
||||
private final ReviewService reviewService;
|
||||
private final UserService userService;
|
||||
|
||||
private final ModelMapper modelMapper;
|
||||
|
||||
public ReviewController(ReviewService reviewService, UserService userService,
|
||||
ModelMapper modelMapper) {
|
||||
this.reviewService = reviewService;
|
||||
this.userService = userService;
|
||||
this.modelMapper = modelMapper;
|
||||
}
|
||||
|
||||
private ReviewDto toDto(ReviewEntity entity) {
|
||||
return modelMapper.map(entity, ReviewDto.class);
|
||||
}
|
||||
|
||||
private ReviewEntity toEntity(ReviewDto dto) {
|
||||
final ReviewEntity entity = modelMapper.map(dto, ReviewEntity.class);
|
||||
entity.setUser(userService.get(dto.getUserId()));
|
||||
return entity;
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public List<ReviewDto> getAll(@RequestParam(name = "userId", defaultValue = "0") Long userId) {
|
||||
return reviewService.getAll(userId).stream().map(this::toDto).toList();
|
||||
}
|
||||
|
||||
@GetMapping("/news/{newsId}")
|
||||
public List<ReviewDto> getAllFor(@PathVariable(name = "newsId") Long newsId) {
|
||||
return reviewService.getAllForNews(newsId).stream().map(this::toDto).toList();
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public ReviewDto get(@PathVariable(name = "id") Long id) {
|
||||
return toDto(reviewService.get(id));
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public ReviewDto create(@RequestBody @Valid ReviewDto dto) {
|
||||
return toDto(reviewService.create(toEntity(dto)));
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
public ReviewDto update(@PathVariable(name = "id") Long id, @RequestBody ReviewDto dto) {
|
||||
return toDto(reviewService.update(id, toEntity(dto)));
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
public ReviewDto delete(@PathVariable(name = "id") Long id) {
|
||||
return toDto(reviewService.delete(id));
|
||||
}
|
||||
}
|
@ -0,0 +1,58 @@
|
||||
package com.example.demo.reviews.api;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import java.util.Date;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
|
||||
public class ReviewDto {
|
||||
private Long id;
|
||||
|
||||
private Long userId;
|
||||
|
||||
private Long newsId;
|
||||
@NotNull
|
||||
private Date date;
|
||||
@NotNull
|
||||
private String text;
|
||||
|
||||
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public Long getNewsId() {
|
||||
return newsId;
|
||||
}
|
||||
|
||||
public void setNewsId(Long newsId) {
|
||||
this.userId = newsId;
|
||||
}
|
||||
|
||||
public Long getUserId() {
|
||||
return userId;
|
||||
}
|
||||
|
||||
public void setUserId(Long userId) {
|
||||
this.userId = userId;
|
||||
}
|
||||
|
||||
public Date getDate() {
|
||||
return date;
|
||||
}
|
||||
|
||||
public void setDate(Date date) {
|
||||
this.date = date;
|
||||
}
|
||||
|
||||
public String getText() {
|
||||
return text;
|
||||
}
|
||||
|
||||
public void setText(String text) {
|
||||
this.text = text;
|
||||
}
|
||||
}
|
@ -0,0 +1,78 @@
|
||||
package com.example.demo.reviews.model;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.Date;
|
||||
|
||||
import com.example.demo.core.model.BaseEntity;
|
||||
import com.example.demo.users.model.UserEntity;
|
||||
import com.example.demo.news.model.NewsEntity;
|
||||
|
||||
public class ReviewEntity extends BaseEntity {
|
||||
private UserEntity user;
|
||||
private NewsEntity news;
|
||||
private Date date;
|
||||
private String text;
|
||||
|
||||
public ReviewEntity() {
|
||||
super();
|
||||
}
|
||||
|
||||
public ReviewEntity(Long id, UserEntity user, NewsEntity news, Date date, String text) {
|
||||
super(id);
|
||||
this.user = user;
|
||||
this.news = news;
|
||||
this.date = date;
|
||||
this.text = text;
|
||||
}
|
||||
|
||||
public UserEntity getUser() {
|
||||
return user;
|
||||
}
|
||||
|
||||
public void setUser(UserEntity user) {
|
||||
this.user = user;
|
||||
}
|
||||
|
||||
public NewsEntity getNews() {
|
||||
return news;
|
||||
}
|
||||
|
||||
public void setNews(NewsEntity news) {
|
||||
this.news = news;
|
||||
}
|
||||
|
||||
public Date getDate() {
|
||||
return date;
|
||||
}
|
||||
|
||||
public void setDate(Date date) {
|
||||
this.date = date;
|
||||
}
|
||||
|
||||
public String getText() {
|
||||
return text;
|
||||
}
|
||||
|
||||
public void setText(String text) {
|
||||
this.text = text;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(id, user, news, date, text);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null || getClass() != obj.getClass())
|
||||
return false;
|
||||
final ReviewEntity other = (ReviewEntity) obj;
|
||||
return Objects.equals(other.getId(), id)
|
||||
&& Objects.equals(other.getUser(), user)
|
||||
&& Objects.equals(other.getNews(), news)
|
||||
&& Objects.equals(other.getDate(), date)
|
||||
&& Objects.equals(other.getText(), text);
|
||||
}
|
||||
}
|
@ -0,0 +1,10 @@
|
||||
package com.example.demo.reviews.repository;
|
||||
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import com.example.demo.core.repository.MapRepository;
|
||||
import com.example.demo.reviews.model.ReviewEntity;
|
||||
|
||||
@Repository
|
||||
public class ReviewRepository extends MapRepository<ReviewEntity> {
|
||||
}
|
@ -0,0 +1,61 @@
|
||||
package com.example.demo.reviews.service;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import com.example.demo.core.error.NotFoundException;
|
||||
import com.example.demo.reviews.model.ReviewEntity;
|
||||
import com.example.demo.reviews.repository.ReviewRepository;
|
||||
|
||||
@Service
|
||||
public class ReviewService {
|
||||
private final ReviewRepository repository;
|
||||
|
||||
public ReviewService(ReviewRepository repository) {
|
||||
this.repository = repository;
|
||||
}
|
||||
|
||||
public List<ReviewEntity> getAll(Long userId) {
|
||||
if (Objects.equals(userId, 0L)) {
|
||||
return repository.getAll();
|
||||
}
|
||||
return repository.getAll().stream()
|
||||
.filter(review -> review.getUser().getId().equals(userId))
|
||||
.toList();
|
||||
}
|
||||
|
||||
public List<ReviewEntity> getAllForNews(Long newsId) {
|
||||
if (Objects.equals(newsId, 0L)) {
|
||||
return repository.getAll();
|
||||
}
|
||||
return repository.getAll().stream()
|
||||
.filter(review -> review.getUser().getId().equals(newsId))
|
||||
.toList();
|
||||
}
|
||||
|
||||
public ReviewEntity get(Long id) {
|
||||
return Optional.ofNullable(repository.get(id))
|
||||
.orElseThrow(() -> new NotFoundException(id));
|
||||
}
|
||||
|
||||
public ReviewEntity create(ReviewEntity entity) {
|
||||
return repository.create(entity);
|
||||
}
|
||||
|
||||
public ReviewEntity update(Long id, ReviewEntity entity) {
|
||||
final ReviewEntity existsEntity = get(id);
|
||||
existsEntity.setUser(entity.getUser());
|
||||
existsEntity.setNews(entity.getNews());
|
||||
existsEntity.setDate(entity.getDate());
|
||||
existsEntity.setText(entity.getText());
|
||||
return repository.update(existsEntity);
|
||||
}
|
||||
|
||||
public ReviewEntity delete(Long id) {
|
||||
final ReviewEntity existsEntity = get(id);
|
||||
return repository.delete(existsEntity);
|
||||
}
|
||||
}
|
@ -0,0 +1,23 @@
|
||||
package com.example.demo.speaker.api;
|
||||
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import com.example.demo.speaker.service.SpeakerNews;
|
||||
|
||||
@RestController
|
||||
public class SpeakerController {
|
||||
private final SpeakerNews speakerService;
|
||||
|
||||
public SpeakerController(SpeakerNews speakerService) {
|
||||
this.speakerService = speakerService;
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public String hello(
|
||||
@RequestParam(value = "name", defaultValue = "Мир") String name,
|
||||
@RequestParam(value = "lang", defaultValue = "ru") String lang) {
|
||||
return speakerService.say(name, lang);
|
||||
}
|
||||
}
|
@ -0,0 +1,27 @@
|
||||
package com.example.demo.speaker.configuration;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import com.example.demo.speaker.domain.Speaker;
|
||||
import com.example.demo.speaker.domain.SpeakerEng;
|
||||
import com.example.demo.speaker.domain.SpeakerRus;
|
||||
|
||||
@Configuration
|
||||
public class SpeakerConfiguration {
|
||||
private final Logger log = LoggerFactory.getLogger(SpeakerConfiguration.class);
|
||||
|
||||
@Bean(value = "ru", initMethod = "init", destroyMethod = "destroy")
|
||||
public SpeakerRus createRusSpeaker() {
|
||||
log.info("Call createRusSpeaker()");
|
||||
return new SpeakerRus();
|
||||
}
|
||||
|
||||
@Bean(value = "en")
|
||||
public Speaker createEngSpeaker() {
|
||||
log.info("Call createEngSpeaker()");
|
||||
return new SpeakerEng();
|
||||
}
|
||||
}
|
@ -0,0 +1,5 @@
|
||||
package com.example.demo.speaker.domain;
|
||||
|
||||
public interface Speaker {
|
||||
String say();
|
||||
}
|
@ -0,0 +1,28 @@
|
||||
package com.example.demo.speaker.domain;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import jakarta.annotation.PostConstruct;
|
||||
import jakarta.annotation.PreDestroy;
|
||||
|
||||
@Component(value = "de")
|
||||
public class SpeakerDeu implements Speaker {
|
||||
private final Logger log = LoggerFactory.getLogger(SpeakerDeu.class);
|
||||
|
||||
@Override
|
||||
public String say() {
|
||||
return "Hallo";
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
public void init() {
|
||||
log.info("SpeakerDeu.init()");
|
||||
}
|
||||
|
||||
@PreDestroy
|
||||
public void destroy() {
|
||||
log.info("SpeakerDeu.destroy()");
|
||||
}
|
||||
}
|
@ -0,0 +1,26 @@
|
||||
package com.example.demo.speaker.domain;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.DisposableBean;
|
||||
import org.springframework.beans.factory.InitializingBean;
|
||||
|
||||
public class SpeakerEng implements Speaker, InitializingBean, DisposableBean {
|
||||
private final Logger log = LoggerFactory.getLogger(SpeakerEng.class);
|
||||
|
||||
@Override
|
||||
public String say() {
|
||||
return "Hello";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterPropertiesSet() {
|
||||
log.info("SpeakerEng.afterPropertiesSet()");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void destroy() {
|
||||
log.info("SpeakerEng.destroy()");
|
||||
|
||||
}
|
||||
}
|
@ -0,0 +1,21 @@
|
||||
package com.example.demo.speaker.domain;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class SpeakerRus implements Speaker {
|
||||
private final Logger log = LoggerFactory.getLogger(SpeakerRus.class);
|
||||
|
||||
@Override
|
||||
public String say() {
|
||||
return "Привет";
|
||||
}
|
||||
|
||||
public void init() {
|
||||
log.info("SpeakerRus.init()");
|
||||
}
|
||||
|
||||
public void destroy() {
|
||||
log.info("SpeakerRus.destroy()");
|
||||
}
|
||||
}
|
@ -0,0 +1,20 @@
|
||||
package com.example.demo.speaker.service;
|
||||
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import com.example.demo.speaker.domain.Speaker;
|
||||
|
||||
@Service
|
||||
public class SpeakerNews {
|
||||
private final ApplicationContext applicationContext;
|
||||
|
||||
public SpeakerNews(ApplicationContext applicationContext) {
|
||||
this.applicationContext = applicationContext;
|
||||
}
|
||||
|
||||
public String say(String name, String lang) {
|
||||
final Speaker speaker = (Speaker) applicationContext.getBean(lang);
|
||||
return String.format("%s, %s!", speaker.say(), name);
|
||||
}
|
||||
}
|
@ -0,0 +1,64 @@
|
||||
package com.example.demo.types.api;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.modelmapper.ModelMapper;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import com.example.demo.core.configuration.Constants;
|
||||
import com.example.demo.types.model.TypeEntity;
|
||||
import com.example.demo.types.service.TypeService;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
|
||||
@RestController
|
||||
@RequestMapping(Constants.API_URL + "/type")
|
||||
public class TypeController {
|
||||
private final TypeService typeService;
|
||||
private final ModelMapper modelMapper;
|
||||
|
||||
public TypeController(TypeService typeService, ModelMapper modelMapper) {
|
||||
this.typeService = typeService;
|
||||
this.modelMapper = modelMapper;
|
||||
}
|
||||
|
||||
private TypeDto toDto(TypeEntity entity) {
|
||||
return modelMapper.map(entity, TypeDto.class);
|
||||
}
|
||||
|
||||
private TypeEntity toEntity(TypeDto dto) {
|
||||
return modelMapper.map(dto, TypeEntity.class);
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public List<TypeDto> getAll() {
|
||||
return typeService.getAll().stream().map(this::toDto).toList();
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public TypeDto get(@PathVariable(name = "id") Long id) {
|
||||
return toDto(typeService.get(id));
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public TypeDto create(@RequestBody @Valid TypeDto dto) {
|
||||
return toDto(typeService.create(toEntity(dto)));
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
public TypeDto update(@PathVariable(name = "id") Long id, @RequestBody TypeDto dto) {
|
||||
return toDto(typeService.update(id, toEntity(dto)));
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
public TypeDto delete(@PathVariable(name = "id") Long id) {
|
||||
return toDto(typeService.delete(id));
|
||||
}
|
||||
}
|
@ -0,0 +1,28 @@
|
||||
package com.example.demo.types.api;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
|
||||
public class TypeDto {
|
||||
private Long id;
|
||||
@NotBlank
|
||||
private String name;
|
||||
|
||||
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
}
|
@ -0,0 +1,43 @@
|
||||
package com.example.demo.types.model;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
import com.example.demo.core.model.BaseEntity;
|
||||
|
||||
public class TypeEntity extends BaseEntity {
|
||||
private String name;
|
||||
|
||||
public TypeEntity() {
|
||||
super();
|
||||
}
|
||||
|
||||
public TypeEntity(Long id, String name) {
|
||||
super(id);
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(id, name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null || getClass() != obj.getClass())
|
||||
return false;
|
||||
final TypeEntity other = (TypeEntity) obj;
|
||||
return Objects.equals(other.getId(), id)
|
||||
&& Objects.equals(other.getName(), name);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,10 @@
|
||||
package com.example.demo.types.repository;
|
||||
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import com.example.demo.core.repository.MapRepository;
|
||||
import com.example.demo.types.model.TypeEntity;
|
||||
|
||||
@Repository
|
||||
public class TypeRepository extends MapRepository<TypeEntity> {
|
||||
}
|
@ -0,0 +1,43 @@
|
||||
package com.example.demo.types.service;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import com.example.demo.core.error.NotFoundException;
|
||||
import com.example.demo.types.model.TypeEntity;
|
||||
import com.example.demo.types.repository.TypeRepository;
|
||||
|
||||
@Service
|
||||
public class TypeService {
|
||||
private final TypeRepository repository;
|
||||
|
||||
public TypeService(TypeRepository repository) {
|
||||
this.repository = repository;
|
||||
}
|
||||
|
||||
public List<TypeEntity> getAll() {
|
||||
return repository.getAll();
|
||||
}
|
||||
|
||||
public TypeEntity get(Long id) {
|
||||
return Optional.ofNullable(repository.get(id))
|
||||
.orElseThrow(() -> new NotFoundException(id));
|
||||
}
|
||||
|
||||
public TypeEntity create(TypeEntity entity) {
|
||||
return repository.create(entity);
|
||||
}
|
||||
|
||||
public TypeEntity update(Long id, TypeEntity entity) {
|
||||
final TypeEntity existsEntity = get(id);
|
||||
existsEntity.setName(entity.getName());
|
||||
return repository.update(existsEntity);
|
||||
}
|
||||
|
||||
public TypeEntity delete(Long id) {
|
||||
final TypeEntity existsEntity = get(id);
|
||||
return repository.delete(existsEntity);
|
||||
}
|
||||
}
|
@ -0,0 +1,64 @@
|
||||
package com.example.demo.users.api;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.modelmapper.ModelMapper;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import com.example.demo.core.configuration.Constants;
|
||||
import com.example.demo.users.model.UserEntity;
|
||||
import com.example.demo.users.service.UserService;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
|
||||
@RestController
|
||||
@RequestMapping(Constants.API_URL + "/user")
|
||||
public class UserController {
|
||||
private final UserService userService;
|
||||
private final ModelMapper modelMapper;
|
||||
|
||||
public UserController(UserService userService, ModelMapper modelMapper) {
|
||||
this.userService = userService;
|
||||
this.modelMapper = modelMapper;
|
||||
}
|
||||
|
||||
private UserDto toDto(UserEntity entity) {
|
||||
return modelMapper.map(entity, UserDto.class);
|
||||
}
|
||||
|
||||
private UserEntity toEntity(UserDto dto) {
|
||||
return modelMapper.map(dto, UserEntity.class);
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public List<UserDto> getAll() {
|
||||
return userService.getAll().stream().map(this::toDto).toList();
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public UserDto get(@PathVariable(name = "id") Long id) {
|
||||
return toDto(userService.get(id));
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public UserDto create(@RequestBody @Valid UserDto dto) {
|
||||
return toDto(userService.create(toEntity(dto)));
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
public UserDto update(@PathVariable(name = "id") Long id, @RequestBody UserDto dto) {
|
||||
return toDto(userService.update(id, toEntity(dto)));
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
public UserDto delete(@PathVariable(name = "id") Long id) {
|
||||
return toDto(userService.delete(id));
|
||||
}
|
||||
}
|
@ -0,0 +1,51 @@
|
||||
package com.example.demo.users.api;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
|
||||
public class UserDto {
|
||||
private Long id;
|
||||
@NotNull
|
||||
|
||||
private String handle;
|
||||
@NotNull
|
||||
|
||||
private String password;
|
||||
@NotNull
|
||||
|
||||
private String status;
|
||||
|
||||
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getHandle() {
|
||||
return handle;
|
||||
}
|
||||
|
||||
public void setHandle(String handle) {
|
||||
this.handle = handle;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
public String getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public void setStatus(String status) {
|
||||
this.status = status;
|
||||
}
|
||||
}
|
@ -0,0 +1,65 @@
|
||||
package com.example.demo.users.model;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
import com.example.demo.core.model.BaseEntity;
|
||||
|
||||
public class UserEntity extends BaseEntity {
|
||||
|
||||
private String handle;
|
||||
private String password;
|
||||
private String status;
|
||||
|
||||
public UserEntity() {
|
||||
super();
|
||||
}
|
||||
|
||||
public UserEntity(Long id, String handle, String password, String status) {
|
||||
super(id);
|
||||
this.handle = handle;
|
||||
this.password = password;
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
public String getHandle() {
|
||||
return handle;
|
||||
}
|
||||
|
||||
public void setHandle(String handle) {
|
||||
this.handle = handle;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
public String getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public void setStatus(String status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(id, handle, password, status);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null || getClass() != obj.getClass())
|
||||
return false;
|
||||
final UserEntity other = (UserEntity) obj;
|
||||
return Objects.equals(other.getId(), id)
|
||||
&& Objects.equals(other.getHandle(), handle)
|
||||
&& Objects.equals(other.getPassword(), password)
|
||||
&& Objects.equals(other.getStatus(), status);
|
||||
}
|
||||
}
|
@ -0,0 +1,10 @@
|
||||
package com.example.demo.users.repository;
|
||||
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import com.example.demo.core.repository.MapRepository;
|
||||
import com.example.demo.users.model.UserEntity;
|
||||
|
||||
@Repository
|
||||
public class UserRepository extends MapRepository<UserEntity> {
|
||||
}
|
@ -0,0 +1,45 @@
|
||||
package com.example.demo.users.service;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import com.example.demo.core.error.NotFoundException;
|
||||
import com.example.demo.users.model.UserEntity;
|
||||
import com.example.demo.users.repository.UserRepository;
|
||||
|
||||
@Service
|
||||
public class UserService {
|
||||
private final UserRepository repository;
|
||||
|
||||
public UserService(UserRepository repository) {
|
||||
this.repository = repository;
|
||||
}
|
||||
|
||||
public List<UserEntity> getAll() {
|
||||
return repository.getAll();
|
||||
}
|
||||
|
||||
public UserEntity get(Long id) {
|
||||
return Optional.ofNullable(repository.get(id))
|
||||
.orElseThrow(() -> new NotFoundException(id));
|
||||
}
|
||||
|
||||
public UserEntity create(UserEntity entity) {
|
||||
return repository.create(entity);
|
||||
}
|
||||
|
||||
public UserEntity update(Long id, UserEntity entity) {
|
||||
final UserEntity existsEntity = get(id);
|
||||
existsEntity.setHandle(entity.getHandle());
|
||||
existsEntity.setPassword(entity.getPassword());
|
||||
existsEntity.setStatus(entity.getStatus());
|
||||
return repository.update(existsEntity);
|
||||
}
|
||||
|
||||
public UserEntity delete(Long id) {
|
||||
final UserEntity existsEntity = get(id);
|
||||
return repository.delete(existsEntity);
|
||||
}
|
||||
}
|
1
Lab 2.2/src/main/resources/application.properties
Normal file
1
Lab 2.2/src/main/resources/application.properties
Normal file
@ -0,0 +1 @@
|
||||
server.port = 8090
|
90
Lab 2.2/src/test/java/com/example/demo/NewsServiceTests.java
Normal file
90
Lab 2.2/src/test/java/com/example/demo/NewsServiceTests.java
Normal file
@ -0,0 +1,90 @@
|
||||
package com.example.demo;
|
||||
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
|
||||
import org.junit.jupiter.api.Order;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestMethodOrder;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
import com.example.demo.core.error.NotFoundException;
|
||||
import java.util.Date;
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import com.example.demo.news.model.NewsEntity;
|
||||
import com.example.demo.types.model.TypeEntity;
|
||||
import com.example.demo.news.service.NewsService;
|
||||
import com.example.demo.types.service.TypeService;
|
||||
import com.example.demo.users.model.UserEntity;
|
||||
import com.example.demo.users.service.UserService;
|
||||
|
||||
@SpringBootTest
|
||||
@TestMethodOrder(OrderAnnotation.class)
|
||||
class NewsServiceTests {
|
||||
@Autowired
|
||||
private NewsService newsService;
|
||||
@Autowired
|
||||
private TypeService typeNews;
|
||||
@Autowired
|
||||
private UserService userService;
|
||||
|
||||
@Test
|
||||
void getTest() {
|
||||
Assertions.assertThrows(NotFoundException.class, () -> newsService.get(0L));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(1)
|
||||
void createTest() throws ParseException {
|
||||
final TypeEntity type = typeNews.create(new TypeEntity(null, "specialType"));
|
||||
final UserEntity handle = userService.create(new UserEntity(null, "specialuser", "12", "admin"));
|
||||
String dateString = "25.03.2024";
|
||||
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
|
||||
Date parsedDate = (java.util.Date) sdf.parse(dateString);
|
||||
newsService.create(new NewsEntity(null, type, handle, "dfd", "dhfj", (java.util.Date) parsedDate));
|
||||
newsService.create(new NewsEntity(null, type, handle, "dfdfd", "dhfdfj", (java.util.Date) parsedDate));
|
||||
final NewsEntity last = newsService
|
||||
.create(new NewsEntity(null, type, handle, "что-то нормальное", "dhfdfj", (java.util.Date) parsedDate));
|
||||
Assertions.assertEquals(4, newsService.getAll(0L).size());
|
||||
Assertions.assertEquals(last, newsService.get(4L));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(2)
|
||||
void updateTest() throws ParseException {
|
||||
String dateString = "29.03.2024";
|
||||
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
|
||||
Date parsedDate = (java.util.Date) sdf.parse(dateString);
|
||||
final TypeEntity type = typeNews.create(new TypeEntity(null, "specialType2"));
|
||||
final UserEntity handle = userService.create(new UserEntity(null, "specialuser2", "12", "admin"));
|
||||
|
||||
final NewsEntity entity = newsService.get(3L);
|
||||
final String oldTitle = entity.getTitle();
|
||||
final NewsEntity newEntity = newsService.update(3L,
|
||||
new NewsEntity(null, type,
|
||||
handle, "что-то нормальное,но другое", "dhfdfj",
|
||||
(java.util.Date) parsedDate));
|
||||
Assertions.assertEquals(4, newsService.getAll(0L).size());
|
||||
Assertions.assertEquals(newEntity, newsService.get(3L));
|
||||
Assertions.assertEquals("что-то нормальное,но другое", newEntity.getTitle());
|
||||
Assertions.assertNotEquals(oldTitle, newEntity.getTitle());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(3)
|
||||
void deleteTest() throws ParseException {
|
||||
newsService.delete(1L);
|
||||
Assertions.assertEquals(3, newsService.getAll(0L).size());
|
||||
String dateString = "28.03.2024";
|
||||
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
|
||||
Date parsedDate = (java.util.Date) sdf.parse(dateString);
|
||||
final TypeEntity type = typeNews.create(new TypeEntity(null, "specialType3"));
|
||||
final UserEntity handle = userService.create(new UserEntity(null, "specialuser3", "12", "admin"));
|
||||
final NewsEntity newEntity = newsService
|
||||
.create(new NewsEntity(null, type, handle, "dfdfd", "dhfdfj", (java.util.Date) parsedDate));
|
||||
|
||||
Assertions.assertEquals(7, typeNews.getAll().size());
|
||||
Assertions.assertEquals(5L, newEntity.getId());
|
||||
}
|
||||
}
|
100
Lab 2.2/src/test/java/com/example/demo/ReviewServiceTests.java
Normal file
100
Lab 2.2/src/test/java/com/example/demo/ReviewServiceTests.java
Normal file
@ -0,0 +1,100 @@
|
||||
package com.example.demo;
|
||||
|
||||
import java.util.Calendar;
|
||||
import java.util.GregorianCalendar;
|
||||
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
|
||||
import org.junit.jupiter.api.Order;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestMethodOrder;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
import com.example.demo.core.error.NotFoundException;
|
||||
import com.example.demo.reviews.model.ReviewEntity;
|
||||
import com.example.demo.reviews.service.ReviewService;
|
||||
import java.text.ParseException;
|
||||
import com.example.demo.users.model.UserEntity;
|
||||
import com.example.demo.users.service.UserService;
|
||||
import com.example.demo.news.service.NewsService;
|
||||
import com.example.demo.news.model.NewsEntity;
|
||||
import com.example.demo.types.service.TypeService;
|
||||
import com.example.demo.types.model.TypeEntity;
|
||||
|
||||
@SpringBootTest
|
||||
@TestMethodOrder(OrderAnnotation.class)
|
||||
class ReviewServiceTests {
|
||||
@Autowired
|
||||
private ReviewService reviewService;
|
||||
@Autowired
|
||||
private UserService userService;
|
||||
@Autowired
|
||||
private TypeService typeService;
|
||||
@Autowired
|
||||
private NewsService newsService;
|
||||
|
||||
private Calendar calendar = new GregorianCalendar(2017, 2, 25);
|
||||
|
||||
@Test
|
||||
void getTest() {
|
||||
Assertions.assertThrows(NotFoundException.class, () -> reviewService.get(0L));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(1)
|
||||
void createTest() throws ParseException {
|
||||
final TypeEntity type = typeService.create(new TypeEntity(null, "specialType"));
|
||||
final UserEntity handle = userService.create(new UserEntity(null, "specialuser", "12", "admin"));
|
||||
|
||||
final NewsEntity newsSpecial = newsService
|
||||
.create(new NewsEntity(null, type, handle, "dfd", "dhfj", calendar.getTime()));
|
||||
|
||||
reviewService.create(new ReviewEntity(null, handle, newsSpecial, calendar.getTime(), "все было супер"));
|
||||
reviewService.create(new ReviewEntity(null, handle, newsSpecial, calendar.getTime(), "all is ok"));
|
||||
final ReviewEntity last = reviewService
|
||||
.create(new ReviewEntity(null, handle, newsSpecial, calendar.getTime(), "fantastic"));
|
||||
|
||||
Assertions.assertEquals(3, reviewService.getAll(0L).size());
|
||||
Assertions.assertEquals(3, reviewService.getAllForNews(0L).size());
|
||||
Assertions.assertEquals(last, reviewService.get(3L));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(2)
|
||||
void updateTest() {
|
||||
final UserEntity userSpecial1 = userService
|
||||
.create(new UserEntity(null, "userSpecial1", "111", "student"));
|
||||
final String test = "TEST";
|
||||
final ReviewEntity entity = reviewService.get(3L);
|
||||
final String oldText = entity.getText();
|
||||
final var News = entity.getNews();
|
||||
final ReviewEntity newEntity = reviewService.update(3L,
|
||||
new ReviewEntity(null, userSpecial1, News, calendar.getTime(), test));
|
||||
Assertions.assertEquals(3, reviewService.getAll(0L).size());
|
||||
Assertions.assertEquals(3, reviewService.getAllForNews(0L).size());
|
||||
Assertions.assertEquals(newEntity, reviewService.get(3L));
|
||||
Assertions.assertEquals(test, newEntity.getText());
|
||||
Assertions.assertNotEquals(oldText, newEntity.getText());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(3)
|
||||
void deleteTest() {
|
||||
final ReviewEntity entity = reviewService.get(3L);
|
||||
final UserEntity userSpecial2 = userService
|
||||
.create(new UserEntity(null, "userSpecial2", "userspecial@gmail.com", "userSpecial2"));
|
||||
|
||||
reviewService.delete(3L);
|
||||
Assertions.assertEquals(2, reviewService.getAll(0L).size());
|
||||
Assertions.assertEquals(2, reviewService.getAllForNews(0L).size());
|
||||
final ReviewEntity last = reviewService.get(2L);
|
||||
Assertions.assertEquals(2L, last.getId());
|
||||
final var News = entity.getNews();
|
||||
final ReviewEntity newEntity = reviewService.update(2L,
|
||||
new ReviewEntity(null, userSpecial2, News, calendar.getTime(), "nice"));
|
||||
Assertions.assertEquals(2, reviewService.getAll(0L).size());
|
||||
Assertions.assertEquals(2, reviewService.getAllForNews(0L).size());
|
||||
Assertions.assertEquals(2L, newEntity.getId());
|
||||
}
|
||||
}
|
38
Lab 2.2/src/test/java/com/example/demo/SpeakerNewsTests.java
Normal file
38
Lab 2.2/src/test/java/com/example/demo/SpeakerNewsTests.java
Normal file
@ -0,0 +1,38 @@
|
||||
package com.example.demo;
|
||||
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
import com.example.demo.speaker.service.SpeakerNews;
|
||||
|
||||
@SpringBootTest
|
||||
class SpeakerNewsTests {
|
||||
@Autowired
|
||||
SpeakerNews speakerNews;
|
||||
|
||||
@Test
|
||||
void testSpeakerRus() {
|
||||
final String res = speakerNews.say("Мир", "ru");
|
||||
Assertions.assertEquals("Привет, Мир!", res);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSpeakerEng() {
|
||||
final String res = speakerNews.say("World", "en");
|
||||
Assertions.assertEquals("Hello, World!", res);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSpeakerDeu() {
|
||||
final String res = speakerNews.say("Welt", "de");
|
||||
Assertions.assertEquals("Hallo, Welt!", res);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSpeakerErrorWired() {
|
||||
Assertions.assertThrows(NoSuchBeanDefinitionException.class, () -> speakerNews.say("Мир", "rus"));
|
||||
}
|
||||
}
|
60
Lab 2.2/src/test/java/com/example/demo/TypeNewsTests.java
Normal file
60
Lab 2.2/src/test/java/com/example/demo/TypeNewsTests.java
Normal file
@ -0,0 +1,60 @@
|
||||
package com.example.demo;
|
||||
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
|
||||
import org.junit.jupiter.api.Order;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestMethodOrder;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
import com.example.demo.core.error.NotFoundException;
|
||||
import com.example.demo.types.model.TypeEntity;
|
||||
import com.example.demo.types.service.TypeService;
|
||||
|
||||
@SpringBootTest
|
||||
@TestMethodOrder(OrderAnnotation.class)
|
||||
class TypeNewsTests {
|
||||
@Autowired
|
||||
private TypeService typeService;
|
||||
|
||||
@Test
|
||||
void getTest() {
|
||||
Assertions.assertThrows(NotFoundException.class, () -> typeService.get(0L));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(1)
|
||||
void createTest() {
|
||||
typeService.create(new TypeEntity(null, "Название 1"));
|
||||
typeService.create(new TypeEntity(null, "Название 2"));
|
||||
final TypeEntity last = typeService.create(new TypeEntity(null, "Название 3"));
|
||||
Assertions.assertEquals(5, typeService.getAll().size());
|
||||
Assertions.assertEquals(last, typeService.get(5L));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(2)
|
||||
void updateTest() {
|
||||
final String test = "TEST";
|
||||
final TypeEntity entity = typeService.get(3L);
|
||||
final String oldName = entity.getName();
|
||||
final TypeEntity newEntity = typeService.update(3L, new TypeEntity(1L, test));
|
||||
Assertions.assertEquals(4, typeService.getAll().size());
|
||||
Assertions.assertEquals(newEntity, typeService.get(3L));
|
||||
Assertions.assertEquals(test, newEntity.getName());
|
||||
Assertions.assertNotEquals(oldName, newEntity.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(3)
|
||||
void deleteTest() {
|
||||
typeService.delete(3L);
|
||||
final TypeEntity last = typeService.get(2L);
|
||||
Assertions.assertEquals(2L, last.getId());
|
||||
|
||||
final TypeEntity newEntity = typeService.create(new TypeEntity(null, "Другое имя"));
|
||||
Assertions.assertEquals(4, typeService.getAll().size());
|
||||
Assertions.assertEquals(5L, newEntity.getId());
|
||||
}
|
||||
}
|
61
Lab 2.2/src/test/java/com/example/demo/UserServiceTests.java
Normal file
61
Lab 2.2/src/test/java/com/example/demo/UserServiceTests.java
Normal file
@ -0,0 +1,61 @@
|
||||
package com.example.demo;
|
||||
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
|
||||
import org.junit.jupiter.api.Order;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestMethodOrder;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
import com.example.demo.core.error.NotFoundException;
|
||||
import com.example.demo.users.model.UserEntity;
|
||||
import com.example.demo.users.service.UserService;
|
||||
|
||||
@SpringBootTest
|
||||
@TestMethodOrder(OrderAnnotation.class)
|
||||
class UserServiceTests {
|
||||
@Autowired
|
||||
private UserService userService;
|
||||
|
||||
@Test
|
||||
void getTest() {
|
||||
Assertions.assertThrows(NotFoundException.class, () -> userService.get(0L));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(1)
|
||||
void createTest() {
|
||||
userService.create(new UserEntity(null, "user1", "123", "admin"));
|
||||
userService.create(new UserEntity(null, "user2", "1", "student"));
|
||||
final UserEntity last = userService.create(new UserEntity(null, "user3", "1", "student"));
|
||||
Assertions.assertEquals(3, userService.getAll().size());
|
||||
Assertions.assertEquals(last, userService.get(3L));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(2)
|
||||
void updateTest() {
|
||||
final String test = "TEST";
|
||||
final UserEntity entity = userService.get(3L);
|
||||
final String oldHandle = entity.getHandle();
|
||||
final UserEntity newEntity = userService.update(3L, new UserEntity(1L, test, "user3@gmail.com", "user3"));
|
||||
Assertions.assertEquals(3, userService.getAll().size());
|
||||
Assertions.assertEquals(newEntity, userService.get(3L));
|
||||
Assertions.assertEquals(test, newEntity.getHandle());
|
||||
Assertions.assertNotEquals(oldHandle, newEntity.getHandle());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(3)
|
||||
void deleteTest() {
|
||||
userService.delete(3L);
|
||||
Assertions.assertEquals(2, userService.getAll().size());
|
||||
final UserEntity last = userService.get(2L);
|
||||
Assertions.assertEquals(2L, last.getId());
|
||||
|
||||
final UserEntity newEntity = userService.create(new UserEntity(null, "user3", "1", "student"));
|
||||
Assertions.assertEquals(3, userService.getAll().size());
|
||||
Assertions.assertEquals(4L, newEntity.getId());
|
||||
}
|
||||
}
|
14
Lektsia6-src_2/.vscode/launch.json
vendored
Normal file
14
Lektsia6-src_2/.vscode/launch.json
vendored
Normal file
@ -0,0 +1,14 @@
|
||||
{
|
||||
"configurations": [
|
||||
{
|
||||
"type": "java",
|
||||
"name": "Spring Boot-DemoApplication<Лекция6-src>",
|
||||
"request": "launch",
|
||||
"cwd": "${workspaceFolder}",
|
||||
"mainClass": "com.example.demo.DemoApplication",
|
||||
"projectName": "Лекция6-src",
|
||||
"args": "",
|
||||
"envFile": "${workspaceFolder}/.env"
|
||||
}
|
||||
]
|
||||
}
|
24
Lektsia6-src_2/Lektsia6-src_1/.vscode/launch.json
vendored
Normal file
24
Lektsia6-src_2/Lektsia6-src_1/.vscode/launch.json
vendored
Normal file
@ -0,0 +1,24 @@
|
||||
{
|
||||
"configurations": [
|
||||
{
|
||||
"type": "java",
|
||||
"name": "Spring Boot-DemoApplication<Лекция6-src>",
|
||||
"request": "launch",
|
||||
"cwd": "${workspaceFolder}",
|
||||
"mainClass": "com.example.demo.DemoApplication",
|
||||
"projectName": "Лекция6-src",
|
||||
"args": "",
|
||||
"envFile": "${workspaceFolder}/.env"
|
||||
},
|
||||
{
|
||||
"type": "java",
|
||||
"name": "Spring Boot-DemoApplication<demo>",
|
||||
"request": "launch",
|
||||
"cwd": "${workspaceFolder}",
|
||||
"mainClass": "com.example.demo.DemoApplication",
|
||||
"projectName": "demo",
|
||||
"args": "",
|
||||
"envFile": "${workspaceFolder}/.env"
|
||||
}
|
||||
]
|
||||
}
|
3
Lektsia6-src_2/Lektsia6-src_1/.vscode/settings.json
vendored
Normal file
3
Lektsia6-src_2/Lektsia6-src_1/.vscode/settings.json
vendored
Normal file
@ -0,0 +1,3 @@
|
||||
{
|
||||
"java.configuration.updateBuildConfiguration": "interactive"
|
||||
}
|
BIN
Lektsia6-src_2/Lektsia6-src_1/data.mv.db
Normal file
BIN
Lektsia6-src_2/Lektsia6-src_1/data.mv.db
Normal file
Binary file not shown.
36
Lektsia6-src_2/Lektsia6-src_1/Лекция6-src/.gitignore
vendored
Normal file
36
Lektsia6-src_2/Lektsia6-src_1/Лекция6-src/.gitignore
vendored
Normal file
@ -0,0 +1,36 @@
|
||||
HELP.md
|
||||
.gradle
|
||||
build/
|
||||
!gradle/wrapper/gradle-wrapper.jar
|
||||
!**/src/main/**/build/
|
||||
!**/src/test/**/build/
|
||||
|
||||
### 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/
|
||||
|
||||
data.*.db
|
14
Lektsia6-src_2/Lektsia6-src_1/Лекция6-src/.vscode/launch.json
vendored
Normal file
14
Lektsia6-src_2/Lektsia6-src_1/Лекция6-src/.vscode/launch.json
vendored
Normal file
@ -0,0 +1,14 @@
|
||||
{
|
||||
"configurations": [
|
||||
{
|
||||
"type": "java",
|
||||
"name": "Spring Boot-DemoApplication<Лекция6-src>",
|
||||
"request": "launch",
|
||||
"cwd": "${workspaceFolder}",
|
||||
"mainClass": "com.example.demo.DemoApplication",
|
||||
"projectName": "Лекция6-src",
|
||||
"args": "",
|
||||
"envFile": "${workspaceFolder}/.env"
|
||||
}
|
||||
]
|
||||
}
|
52
Lektsia6-src_2/Lektsia6-src_1/Лекция6-src/build.gradle
Normal file
52
Lektsia6-src_2/Lektsia6-src_1/Лекция6-src/build.gradle
Normal file
@ -0,0 +1,52 @@
|
||||
plugins {
|
||||
id 'java'
|
||||
id 'org.springframework.boot' version '3.2.4'
|
||||
id 'io.spring.dependency-management' version '1.1.4'
|
||||
}
|
||||
|
||||
group = 'com.example'
|
||||
version = '0.0.1-SNAPSHOT'
|
||||
|
||||
defaultTasks 'bootRun'
|
||||
|
||||
jar {
|
||||
enabled = false
|
||||
}
|
||||
|
||||
bootJar {
|
||||
archiveFileName = String.format('%s-%s.jar', rootProject.name, version)
|
||||
}
|
||||
|
||||
assert System.properties['java.specification.version'] == '17' || '21'
|
||||
java {
|
||||
sourceCompatibility = '17'
|
||||
}
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation 'org.springframework.boot:spring-boot-starter-web'
|
||||
implementation 'org.springframework.boot:spring-boot-starter-validation'
|
||||
implementation 'org.modelmapper:modelmapper:3.2.0'
|
||||
|
||||
|
||||
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
|
||||
implementation 'com.h2database:h2:2.2.224'
|
||||
|
||||
implementation 'org.springframework.boot:spring-boot-devtools'
|
||||
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
|
||||
implementation 'nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect:3.3.0'
|
||||
runtimeOnly 'org.webjars.npm:bootstrap:5.3.3'
|
||||
runtimeOnly 'org.webjars.npm:bootstrap-icons:1.11.3'
|
||||
|
||||
implementation 'org.springframework.boot:spring-boot-starter-security'
|
||||
implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity6'
|
||||
|
||||
testImplementation 'org.springframework.boot:spring-boot-starter-test'
|
||||
}
|
||||
|
||||
tasks.named('test') {
|
||||
useJUnitPlatform()
|
||||
}
|
BIN
Lektsia6-src_2/Lektsia6-src_1/Лекция6-src/gradle/wrapper/gradle-wrapper.jar
vendored
Normal file
BIN
Lektsia6-src_2/Lektsia6-src_1/Лекция6-src/gradle/wrapper/gradle-wrapper.jar
vendored
Normal file
Binary file not shown.
7
Lektsia6-src_2/Lektsia6-src_1/Лекция6-src/gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
7
Lektsia6-src_2/Lektsia6-src_1/Лекция6-src/gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
@ -0,0 +1,7 @@
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip
|
||||
networkTimeout=10000
|
||||
validateDistributionUrl=true
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
249
Lektsia6-src_2/Lektsia6-src_1/Лекция6-src/gradlew
vendored
Normal file
249
Lektsia6-src_2/Lektsia6-src_1/Лекция6-src/gradlew
vendored
Normal file
@ -0,0 +1,249 @@
|
||||
#!/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/HEAD/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
|
||||
|
||||
# This is normally unused
|
||||
# shellcheck disable=SC2034
|
||||
APP_BASE_NAME=${0##*/}
|
||||
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
|
||||
APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit
|
||||
|
||||
# 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
|
||||
if ! command -v java >/dev/null 2>&1
|
||||
then
|
||||
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
|
||||
fi
|
||||
|
||||
# Increase the maximum file descriptors if we can.
|
||||
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
||||
case $MAX_FD in #(
|
||||
max*)
|
||||
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC2039,SC3045
|
||||
MAX_FD=$( ulimit -H -n ) ||
|
||||
warn "Could not query maximum file descriptor limit"
|
||||
esac
|
||||
case $MAX_FD in #(
|
||||
'' | soft) :;; #(
|
||||
*)
|
||||
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC2039,SC3045
|
||||
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
|
||||
|
||||
|
||||
# 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"'
|
||||
|
||||
# Collect all arguments for the java command:
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
|
||||
# and any embedded shellness will be escaped.
|
||||
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
|
||||
# treated as '${Hostname}' itself on the command line.
|
||||
|
||||
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" "$@"
|
92
Lektsia6-src_2/Lektsia6-src_1/Лекция6-src/gradlew.bat
vendored
Normal file
92
Lektsia6-src_2/Lektsia6-src_1/Лекция6-src/gradlew.bat
vendored
Normal file
@ -0,0 +1,92 @@
|
||||
@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=.
|
||||
@rem This is normally unused
|
||||
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
|
15
Lektsia6-src_2/Lektsia6-src_1/Лекция6-src/readme.md
Normal file
15
Lektsia6-src_2/Lektsia6-src_1/Лекция6-src/readme.md
Normal file
@ -0,0 +1,15 @@
|
||||
H2 Console: \
|
||||
http://localhost:8080/h2-console
|
||||
|
||||
JDBC URL: jdbc:h2:file:./data \
|
||||
User Name: sa \
|
||||
Password: password
|
||||
|
||||
Почитать:
|
||||
|
||||
- Spring Boot CRUD Application with Thymeleaf https://www.baeldung.com/spring-boot-crud-thymeleaf
|
||||
- Thymeleaf Layout Dialect https://ultraq.github.io/thymeleaf-layout-dialect/
|
||||
- Tutorial: Using Thymeleaf https://www.thymeleaf.org/doc/tutorials/3.1/usingthymeleaf.html#introducing-thymeleaf
|
||||
- Working with Cookies in Spring MVC using @CookieValue Annotation https://www.geeksforgeeks.org/working-with-cookies-in-spring-mvc-using-cookievalue-annotation/
|
||||
- Session Attributes in Spring MVC https://www.baeldung.com/spring-mvc-session-attributes
|
||||
- LazyInitializationException – What it is and the best way to fix it https://thorben-janssen.com/lazyinitializationexception/
|
@ -0,0 +1 @@
|
||||
rootProject.name = 'demo'
|
@ -0,0 +1,75 @@
|
||||
package com.example.demo;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
import java.util.GregorianCalendar;
|
||||
import java.util.List;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.boot.CommandLineRunner;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
import com.example.demo.core.configuration.Constants;
|
||||
import com.example.demo.news.model.NewsEntity;
|
||||
import com.example.demo.news.service.NewsService;
|
||||
import com.example.demo.types.model.TypeEntity;
|
||||
import com.example.demo.types.service.TypeService;
|
||||
import com.example.demo.users.model.UserEntity;
|
||||
import com.example.demo.users.model.UserRole;
|
||||
import com.example.demo.users.service.UserService;
|
||||
|
||||
@SpringBootApplication
|
||||
public class DemoApplication implements CommandLineRunner {
|
||||
private final Logger log = LoggerFactory.getLogger(DemoApplication.class);
|
||||
|
||||
private final TypeService typeService;
|
||||
private final UserService userService;
|
||||
private final NewsService newsService;
|
||||
|
||||
public DemoApplication(TypeService typeService, UserService userService, NewsService newsService) {
|
||||
this.typeService = typeService;
|
||||
this.userService = userService;
|
||||
this.newsService = newsService;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(DemoApplication.class, args);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run(String... args) throws Exception {
|
||||
// if (args.length > 0 && "--populate".equals(args[0])) {
|
||||
log.info("Create default types values");
|
||||
log.info("Create default user values");
|
||||
final var admin = new UserEntity("admin", "admin");
|
||||
admin.setRole(UserRole.ADMIN);
|
||||
userService.create(admin);
|
||||
|
||||
final var user1 = userService.create(new UserEntity("user1", Constants.DEFAULT_PASSWORD));
|
||||
|
||||
IntStream.range(2, 8)
|
||||
.forEach(value -> userService.create(
|
||||
new UserEntity("user".concat(String.valueOf(value)), Constants.DEFAULT_PASSWORD)));
|
||||
final TypeEntity type1 = typeService.create(new TypeEntity("По поводу отчислений"));
|
||||
final TypeEntity type2 = typeService.create(new TypeEntity("По другому поводу"));
|
||||
log.info("Create default items values");
|
||||
Calendar calendar = new GregorianCalendar(2024, 4, 15);
|
||||
Calendar calendar2 = new GregorianCalendar(2024, 4, 20);
|
||||
final List<NewsEntity> news = List.of(
|
||||
new NewsEntity(type1, "Заголовок", "чипи чипи", calendar.getTime()),
|
||||
new NewsEntity(type1, "Другой заголовок", "чипи чапа", calendar.getTime()),
|
||||
new NewsEntity(type2, "Заголовок2", "чипи чипи", calendar.getTime()));
|
||||
news.forEach(newsEntity -> newsService.create(admin.getId(), newsEntity));
|
||||
|
||||
final List<NewsEntity> news2 = List.of(
|
||||
new NewsEntity(type1, "Заголовок3", "чипи чипи", calendar2.getTime()),
|
||||
new NewsEntity(type2, "Заголовок 222", "чипи чипи", calendar2.getTime())
|
||||
);
|
||||
news2.forEach(newsEntity -> newsService.create(admin.getId(), newsEntity));
|
||||
}
|
||||
}
|
||||
|
@ -0,0 +1,56 @@
|
||||
package com.example.demo.allReviews.api;
|
||||
|
||||
import org.modelmapper.ModelMapper;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
|
||||
import com.example.demo.core.api.PageAttributesMapper;
|
||||
import com.example.demo.core.configuration.Constants;
|
||||
import com.example.demo.news.service.NewsService;
|
||||
import com.example.demo.reviews.api.ReviewDto;
|
||||
import com.example.demo.reviews.model.ReviewEntity;
|
||||
import com.example.demo.reviews.service.ReviewService;
|
||||
import com.example.demo.users.service.UserService;
|
||||
|
||||
@Controller
|
||||
@RequestMapping(AllReviewsController.URL)
|
||||
public class AllReviewsController {
|
||||
public static final String URL = "/all-reviews";
|
||||
private static final String VIEW = "all-reviews";
|
||||
private static final String PAGE_ATTRIBUTE = "page";
|
||||
|
||||
private final ReviewService reviewService;
|
||||
private final NewsService newsService;
|
||||
private final ModelMapper modelMapper;
|
||||
|
||||
public AllReviewsController(ReviewService reviewService, ModelMapper modelMapper, NewsService newsService) {
|
||||
this.reviewService = reviewService;
|
||||
this.modelMapper = modelMapper;
|
||||
this.newsService = newsService;
|
||||
}
|
||||
|
||||
private ExpandedReviewDto toDto(ReviewEntity entity) {
|
||||
ExpandedReviewDto dto = modelMapper.map(entity, ExpandedReviewDto.class);
|
||||
dto.setUserName(entity.getUser().getLogin());
|
||||
dto.setNewsName(entity.getNews().getTitle());
|
||||
return dto;
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public String getAll(
|
||||
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
|
||||
Model model,
|
||||
@RequestParam(name = "newsId", defaultValue = "0") Long newsId
|
||||
) {
|
||||
model.addAttribute(PAGE_ATTRIBUTE, page);
|
||||
model.addAttribute("news", newsService.getAll());
|
||||
model.addAttribute("newsId", newsId);
|
||||
model.addAllAttributes(PageAttributesMapper.toAttributes(
|
||||
reviewService.getAllForNews(newsId, page, Constants.DEFUALT_PAGE_SIZE),
|
||||
this::toDto));
|
||||
return VIEW;
|
||||
}
|
||||
}
|
@ -0,0 +1,15 @@
|
||||
package com.example.demo.allReviews.api;
|
||||
|
||||
import com.example.demo.reviews.api.ReviewDto;
|
||||
|
||||
public class ExpandedReviewDto extends ReviewDto {
|
||||
private String userName;
|
||||
|
||||
public void setUserName(String name) {
|
||||
this.userName = name;
|
||||
}
|
||||
|
||||
public String getUserName() {
|
||||
return userName;
|
||||
}
|
||||
}
|
@ -0,0 +1,20 @@
|
||||
package com.example.demo.core.api;
|
||||
|
||||
import org.springframework.web.bind.annotation.ControllerAdvice;
|
||||
import org.springframework.web.bind.annotation.ModelAttribute;
|
||||
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpSession;
|
||||
|
||||
@ControllerAdvice
|
||||
public class GlobalController {
|
||||
|
||||
|
||||
@ModelAttribute("servletPath")
|
||||
String getRequestServletPath(HttpServletRequest request) {
|
||||
return request.getServletPath();
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -0,0 +1,18 @@
|
||||
package com.example.demo.core.api;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.function.Function;
|
||||
|
||||
import org.springframework.data.domain.Page;
|
||||
|
||||
public class PageAttributesMapper {
|
||||
private PageAttributesMapper() {
|
||||
}
|
||||
|
||||
public static <E, D> Map<String, Object> toAttributes(Page<E> page, Function<E, D> mapper) {
|
||||
return Map.of(
|
||||
"items", page.getContent().stream().map(mapper::apply).toList(),
|
||||
"currentPage", page.getNumber(),
|
||||
"totalPages", page.getTotalPages());
|
||||
}
|
||||
}
|
@ -0,0 +1,19 @@
|
||||
package com.example.demo.core.configuration;
|
||||
|
||||
public class Constants {
|
||||
public static final String SEQUENCE_NAME = "hibernate_sequence";
|
||||
|
||||
public static final int DEFUALT_PAGE_SIZE = 5;
|
||||
|
||||
public static final String REDIRECT_VIEW = "redirect:";
|
||||
|
||||
public static final String ADMIN_PREFIX = "/admin";
|
||||
|
||||
public static final String LOGIN_URL = "/login";
|
||||
public static final String LOGOUT_URL = "/logout";
|
||||
|
||||
public static final String DEFAULT_PASSWORD = "123456";
|
||||
|
||||
private Constants() {
|
||||
}
|
||||
}
|
@ -0,0 +1,23 @@
|
||||
package com.example.demo.core.configuration;
|
||||
|
||||
import org.modelmapper.ModelMapper;
|
||||
import org.modelmapper.PropertyMap;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import com.example.demo.core.model.BaseEntity;
|
||||
|
||||
@Configuration
|
||||
public class MapperConfiguration {
|
||||
@Bean
|
||||
ModelMapper modelMapper() {
|
||||
final ModelMapper mapper = new ModelMapper();
|
||||
mapper.addMappings(new PropertyMap<Object, BaseEntity>() {
|
||||
@Override
|
||||
protected void configure() {
|
||||
skip(destination.getId());
|
||||
}
|
||||
});
|
||||
return mapper;
|
||||
}
|
||||
}
|
@ -0,0 +1,14 @@
|
||||
package com.example.demo.core.configuration;
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
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 addViewControllers(ViewControllerRegistry registry) {
|
||||
registry.addViewController("/login").setViewName("login");
|
||||
registry.addRedirectViewController("/", "/");
|
||||
}
|
||||
}
|
@ -0,0 +1,53 @@
|
||||
package com.example.demo.core.error;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.core.annotation.AnnotationUtils;
|
||||
import org.springframework.web.bind.annotation.ControllerAdvice;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
import org.springframework.web.servlet.ModelAndView;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
|
||||
@ControllerAdvice
|
||||
public class AdviceController {
|
||||
private final Logger log = LoggerFactory.getLogger(AdviceController.class);
|
||||
|
||||
private static Throwable getRootCause(Throwable throwable) {
|
||||
Throwable rootCause = throwable;
|
||||
while (rootCause.getCause() != null && rootCause.getCause() != rootCause) {
|
||||
rootCause = rootCause.getCause();
|
||||
}
|
||||
return rootCause;
|
||||
}
|
||||
|
||||
private static Map<String, Object> getAttributes(HttpServletRequest request, Throwable throwable) {
|
||||
final Throwable rootCause = getRootCause(throwable);
|
||||
final StackTraceElement firstError = rootCause.getStackTrace()[0];
|
||||
return Map.of(
|
||||
"message", rootCause.getMessage(),
|
||||
"url", request.getRequestURL(),
|
||||
"exception", rootCause.getClass().getName(),
|
||||
"file", firstError.getFileName(),
|
||||
"method", firstError.getMethodName(),
|
||||
"line", firstError.getLineNumber());
|
||||
}
|
||||
|
||||
@ExceptionHandler(value = Exception.class)
|
||||
public ModelAndView defaultErrorloginr(HttpServletRequest request, Throwable throwable) throws Throwable {
|
||||
if (AnnotationUtils.findAnnotation(throwable.getClass(),
|
||||
ResponseStatus.class) != null) {
|
||||
throw throwable;
|
||||
}
|
||||
|
||||
log.error("{}", throwable.getMessage());
|
||||
throwable.printStackTrace();
|
||||
final ModelAndView model = new ModelAndView();
|
||||
model.addAllObjects(getAttributes(request, throwable));
|
||||
model.setViewName("error");
|
||||
return model;
|
||||
}
|
||||
}
|
@ -0,0 +1,7 @@
|
||||
package com.example.demo.core.error;
|
||||
|
||||
public class NotFoundException extends RuntimeException {
|
||||
public <T> NotFoundException(Class<T> clazz, Long id) {
|
||||
super(String.format("%s with id [%s] is not found or not exists", clazz.getSimpleName(), id));
|
||||
}
|
||||
}
|
@ -0,0 +1,28 @@
|
||||
package com.example.demo.core.model;
|
||||
|
||||
import com.example.demo.core.configuration.Constants;
|
||||
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.MappedSuperclass;
|
||||
import jakarta.persistence.SequenceGenerator;
|
||||
|
||||
@MappedSuperclass
|
||||
public abstract class BaseEntity {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = Constants.SEQUENCE_NAME)
|
||||
@SequenceGenerator(name = Constants.SEQUENCE_NAME, sequenceName = Constants.SEQUENCE_NAME, allocationSize = 1)
|
||||
protected Long id;
|
||||
|
||||
protected BaseEntity() {
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
}
|
@ -0,0 +1,112 @@
|
||||
package com.example.demo.core.security;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
|
||||
import org.springframework.security.config.Customizer;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
|
||||
import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer.FrameOptionsConfig;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.security.web.SecurityFilterChain;
|
||||
|
||||
import com.example.demo.core.configuration.Constants;
|
||||
import com.example.demo.users.api.UserSignupController;
|
||||
import com.example.demo.users.model.UserRole;
|
||||
|
||||
@Configuration
|
||||
@EnableWebSecurity
|
||||
public class SecurityConfiguration {
|
||||
@Bean
|
||||
SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
|
||||
httpSecurity.headers(headers -> headers.frameOptions(FrameOptionsConfig::sameOrigin));
|
||||
httpSecurity.csrf(AbstractHttpConfigurer::disable);
|
||||
httpSecurity.cors(Customizer.withDefaults());
|
||||
// доступ к этим файлам получает любой пользователь
|
||||
httpSecurity.authorizeHttpRequests(requests -> requests
|
||||
.requestMatchers("/css/**", "/img/**", "/webjars/**", "/*.svg")
|
||||
.permitAll());
|
||||
// все данные операции доступны только админу, иначе 403 ошибка. к этим адресам
|
||||
// мы не сможем получить доступ ни по какому тппу запросов
|
||||
httpSecurity.authorizeHttpRequests(requests -> requests
|
||||
.requestMatchers(Constants.ADMIN_PREFIX + "/**").hasRole(UserRole.ADMIN.name())
|
||||
.requestMatchers("/h2-console/**").hasRole(UserRole.ADMIN.name())
|
||||
|
||||
|
||||
.requestMatchers("/").permitAll()
|
||||
// доступ к регистрации пользователя доступен только анонимным пользователям
|
||||
.requestMatchers(UserSignupController.URL).anonymous()
|
||||
// доступ ко входу пользователя доступен только анонимным пользователям
|
||||
.requestMatchers(Constants.LOGIN_URL).anonymous()
|
||||
// для получения доступа ко всем остальным адресам необходимо чтобы пользователь
|
||||
// вошел в систему( был не анонименым)
|
||||
.anyRequest().authenticated());
|
||||
// хотим использовать аутентификацию через нашу форму
|
||||
httpSecurity.formLogin(formLogin -> formLogin
|
||||
.loginPage(Constants.LOGIN_URL));
|
||||
// функция запоминания пароля
|
||||
httpSecurity.rememberMe(rememberMe -> rememberMe.key("uniqueAndSecret"));
|
||||
// удаляем куки выходе из приложения
|
||||
httpSecurity.logout(logout -> logout
|
||||
.deleteCookies("JSESSIONID"));
|
||||
|
||||
return httpSecurity.build();
|
||||
}
|
||||
// возвращает провайдер аутентификации, который работает через хранилище
|
||||
// dao- data access Object
|
||||
@Bean
|
||||
DaoAuthenticationProvider authenticationProvider(UserDetailsService userDetailsService) {
|
||||
// создаем провайдер для работы с хранилищем
|
||||
final DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
|
||||
// в качестве хранилища будет использоваться uds
|
||||
authProvider.setUserDetailsService(userDetailsService);
|
||||
// в качестве энкодера паролей используется доп бин
|
||||
authProvider.setPasswordEncoder(passwordEncoder());
|
||||
return authProvider;
|
||||
}
|
||||
// доп бин для энкодера. если без него, то пароль не кодируется.
|
||||
// эта штука преобразует пароль из 60 символов в 16-ричном формате
|
||||
@Bean
|
||||
PasswordEncoder passwordEncoder() {
|
||||
return new BCryptPasswordEncoder();
|
||||
}
|
||||
}
|
||||
// если мы хотим делать авторизацию через аннотации мы вешаем на этот класс
|
||||
// аннотацию enableGlobalMethodsecurity, в
|
||||
// котором можем определять какие аннотации будут работать
|
||||
// securedEnable - включает использование аннотации secured(можно вешать на
|
||||
// отдельные методы. чтобы указывать какие роли нужно иметь, чтобы получить
|
||||
// доступ на конкретный метод)
|
||||
// @EnableGlobalMethodSecurity(
|
||||
// securedEnabled=true,
|
||||
// jsr250Enabled=true,
|
||||
// prePostEnabled=true)
|
||||
|
||||
// securedEnabled–включает использование аннотации @Secured;
|
||||
// jsr250Enabled–включает использование аннотации @RolesAllowed;
|
||||
// prePostEnabled–включает использование аннотаций @PreAuthorise,
|
||||
// @PostAuthorise, @PreFilter, @PostFilter.
|
||||
|
||||
// Через аннотации:
|
||||
// • @PreAuthorise – выполняет выражение
|
||||
// на языке
|
||||
// SEL для
|
||||
// контроля доступа
|
||||
// перед выполнением метода;•
|
||||
// @PostAuthorise – выполняет выражение
|
||||
// на языке
|
||||
// SEL для
|
||||
// контроля доступа
|
||||
// после
|
||||
// выполнением
|
||||
|
||||
// метода (доступ к результату);
|
||||
// • @PreFilter – использует выражение SEL для фильтрации перед выполнением;
|
||||
// • @PostFilter – использует выражение SEL для фильтрации после выполнения;
|
||||
// • @Secured – определяет список ролей пользователей, которые могут
|
||||
// использовать
|
||||
// метод/методы класса;
|
||||
// • @RolesAllowed – аналогично @Secured (реализовано в рамках JSR 250)
|
@ -0,0 +1,64 @@
|
||||
package com.example.demo.core.security;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.Set;
|
||||
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
|
||||
import com.example.demo.users.model.UserEntity;
|
||||
|
||||
public class UserPrincipal implements UserDetails {
|
||||
private final long id;
|
||||
private final String username;
|
||||
private final String password;
|
||||
private final Set<? extends GrantedAuthority> roles;
|
||||
private final boolean active;
|
||||
|
||||
public UserPrincipal(UserEntity user) {
|
||||
this.id = user.getId();
|
||||
this.username = user.getLogin();
|
||||
this.password = user.getPassword();
|
||||
this.roles = Set.of(user.getRole());
|
||||
this.active = true;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<? extends GrantedAuthority> getAuthorities() {
|
||||
return roles;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isEnabled() {
|
||||
return active;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isAccountNonExpired() {
|
||||
return isEnabled();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isAccountNonLocked() {
|
||||
return isEnabled();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isCredentialsNonExpired() {
|
||||
return isEnabled();
|
||||
}
|
||||
}
|
@ -0,0 +1,93 @@
|
||||
package com.example.demo.index.api;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.Calendar;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.modelmapper.ModelMapper;
|
||||
import org.springframework.security.core.annotation.AuthenticationPrincipal;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
|
||||
import com.example.demo.core.api.PageAttributesMapper;
|
||||
import com.example.demo.core.configuration.Constants;
|
||||
import com.example.demo.core.security.UserPrincipal;
|
||||
import com.example.demo.news.api.NewsDto;
|
||||
import com.example.demo.news.model.NewsEntity;
|
||||
import com.example.demo.news.service.NewsService;
|
||||
import com.example.demo.types.service.TypeService;
|
||||
import com.example.demo.users.service.UserService;
|
||||
|
||||
@Controller
|
||||
public class IndexController {
|
||||
public static final String PRODUCTS_VIEW = "index";
|
||||
public static final String PAGE_ATTRIBUTE = "page";
|
||||
|
||||
private NewsService newsService;
|
||||
private UserService userService;
|
||||
private TypeService typeService;
|
||||
private final ModelMapper modelMapper;
|
||||
|
||||
public IndexController(NewsService newsService, TypeService typeService, UserService userService, ModelMapper modelMapper) {
|
||||
this.newsService = newsService;
|
||||
this.userService = userService;
|
||||
this.modelMapper = modelMapper;
|
||||
this.typeService = typeService;
|
||||
}
|
||||
|
||||
private NewsDto toDto(NewsEntity entity) {
|
||||
NewsDto dto = modelMapper.map(entity, NewsDto.class);
|
||||
dto.setUserName(entity.getUser().getLogin());
|
||||
return dto;
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public String getAll(
|
||||
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
|
||||
@RequestParam(name = "typeId", defaultValue = "0") Long typeId,
|
||||
@RequestParam(name = "userId", defaultValue = "0") Long userId,
|
||||
@RequestParam(name = "startDate", defaultValue = "") String startDateString,
|
||||
@RequestParam(name = "endDate", defaultValue = "") String endDateString,
|
||||
@AuthenticationPrincipal UserPrincipal principal,
|
||||
Model model) {
|
||||
final Map<String, Object> attributes = PageAttributesMapper.toAttributes(
|
||||
newsService.getAllWithReviewsCount(page, Constants.DEFUALT_PAGE_SIZE), item -> toDto(item));
|
||||
model.addAllAttributes(attributes);
|
||||
model.addAttribute(PAGE_ATTRIBUTE, page);
|
||||
|
||||
model.addAttribute("startDate", startDateString);
|
||||
model.addAttribute("endDate", endDateString);
|
||||
model.addAttribute("userId", userId);
|
||||
model.addAttribute("typeId", typeId);
|
||||
model.addAttribute("users", userService.getAllAdmins());
|
||||
model.addAttribute("types", typeService.getAll());
|
||||
|
||||
Calendar startDate = Calendar.getInstance(), endDate = Calendar.getInstance();
|
||||
|
||||
if (startDateString.equals("")) {
|
||||
startDate.setTimeInMillis(0);
|
||||
} else {
|
||||
LocalDate localDate = LocalDate.parse(startDateString, DateTimeFormatter.ISO_DATE);
|
||||
startDate.clear();
|
||||
startDate.set(localDate.getYear(), localDate.getMonthValue() - 1, localDate.getDayOfMonth());
|
||||
}
|
||||
|
||||
if (endDateString.equals("")) {
|
||||
endDate = Calendar.getInstance();
|
||||
} else {
|
||||
LocalDate localDate = LocalDate.parse(endDateString, DateTimeFormatter.ISO_DATE);
|
||||
endDate.clear();
|
||||
endDate.set(localDate.getYear(), localDate.getMonthValue() - 1, localDate.getDayOfMonth());
|
||||
}
|
||||
|
||||
model.addAllAttributes(PageAttributesMapper.toAttributes(
|
||||
newsService.getAllWithReviewsCount(userId, typeId, startDate, endDate, page, Constants.DEFUALT_PAGE_SIZE),
|
||||
this::toDto));
|
||||
|
||||
return PRODUCTS_VIEW;
|
||||
}
|
||||
}
|
@ -0,0 +1,144 @@
|
||||
package com.example.demo.news.api;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.modelmapper.ModelMapper;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.validation.BindingResult;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.ModelAttribute;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.SessionAttribute;
|
||||
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
|
||||
|
||||
import com.example.demo.core.api.PageAttributesMapper;
|
||||
import com.example.demo.core.configuration.Constants;
|
||||
import com.example.demo.core.security.UserPrincipal;
|
||||
import com.example.demo.news.model.NewsEntity;
|
||||
import com.example.demo.news.service.NewsService;
|
||||
import com.example.demo.types.model.TypeEntity;
|
||||
import com.example.demo.types.service.TypeService;
|
||||
import com.example.demo.users.model.UserEntity;
|
||||
import com.example.demo.users.service.UserService;
|
||||
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.annotation.AuthenticationPrincipal;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
|
||||
@Controller
|
||||
@RequestMapping(NewsController.URL)
|
||||
public class NewsController {
|
||||
public static final String URL = Constants.ADMIN_PREFIX + "/news";
|
||||
private static final String PAGE_ATTRIBUTE = "page";
|
||||
private static final String NEWS_VIEW = "news";
|
||||
private static final String NEWS_EDIT_VIEW = "news-edit";
|
||||
private static final String NEWS_ATTRIBUTE = "news";
|
||||
|
||||
private final TypeService typeService;
|
||||
private final NewsService newsService;
|
||||
private final ModelMapper modelMapper;
|
||||
|
||||
public NewsController(TypeService typeService, NewsService newsService,
|
||||
ModelMapper modelMapper) {
|
||||
this.typeService = typeService;
|
||||
this.newsService = newsService;
|
||||
this.modelMapper = modelMapper;
|
||||
}
|
||||
|
||||
private NewsDto toDto(NewsEntity entity) {
|
||||
NewsDto dto = modelMapper.map(entity, NewsDto.class);
|
||||
return dto;
|
||||
}
|
||||
|
||||
private NewsEntity toEntity(NewsDto dto) {
|
||||
NewsEntity entity = modelMapper.map(dto, NewsEntity.class);
|
||||
entity.setType(typeService.get(dto.getTypeId()));
|
||||
return entity;
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public String getAll(
|
||||
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
|
||||
@AuthenticationPrincipal UserPrincipal userPrincipal,
|
||||
Model model) {
|
||||
final Map<String, Object> attributes = PageAttributesMapper.toAttributes(
|
||||
newsService.getAll(userPrincipal.getId(), page, Constants.DEFUALT_PAGE_SIZE), this::toDto);
|
||||
model.addAllAttributes(attributes);
|
||||
model.addAttribute(PAGE_ATTRIBUTE, page);
|
||||
return NEWS_VIEW;
|
||||
}
|
||||
|
||||
@GetMapping("/edit/")
|
||||
public String create(Model model) {
|
||||
List<TypeEntity> types = typeService.getAll();
|
||||
model.addAttribute("types", types);
|
||||
model.addAttribute(NEWS_ATTRIBUTE, new NewsDto());
|
||||
return NEWS_EDIT_VIEW;
|
||||
}
|
||||
|
||||
@PostMapping("/edit/")
|
||||
public String create(
|
||||
@AuthenticationPrincipal UserPrincipal principal,
|
||||
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
|
||||
@ModelAttribute(name = NEWS_ATTRIBUTE) @Valid NewsDto news,
|
||||
BindingResult bindingResult,
|
||||
Model model,
|
||||
RedirectAttributes redirectAttributes) {
|
||||
if (bindingResult.hasErrors()) {
|
||||
model.addAttribute(PAGE_ATTRIBUTE, page);
|
||||
return NEWS_EDIT_VIEW;
|
||||
}
|
||||
redirectAttributes.addAttribute(PAGE_ATTRIBUTE, page);
|
||||
news.setDate(new Date()); // Установка текущей даты
|
||||
newsService.create(principal.getId(), toEntity(news)); // Использование ID текущего пользователя
|
||||
return Constants.REDIRECT_VIEW + URL;
|
||||
}
|
||||
|
||||
@GetMapping("/edit/{id}")
|
||||
public String update(
|
||||
@PathVariable(name = "id") Long id,
|
||||
Model model) {
|
||||
if (id <= 0) {
|
||||
throw new IllegalArgumentException();
|
||||
}
|
||||
model.addAttribute("types", typeService.getAll());
|
||||
|
||||
model.addAttribute(NEWS_ATTRIBUTE, toDto(newsService.getNews(id)));
|
||||
return NEWS_EDIT_VIEW;
|
||||
}
|
||||
|
||||
@PostMapping("/edit/{id}")
|
||||
public String update(
|
||||
@PathVariable(name = "id") Long id,
|
||||
@ModelAttribute(name = NEWS_ATTRIBUTE) @Valid NewsDto news,
|
||||
BindingResult bindingResult,
|
||||
Model model) {
|
||||
if (bindingResult.hasErrors()) {
|
||||
return NEWS_EDIT_VIEW;
|
||||
}
|
||||
if (id <= 0) {
|
||||
throw new IllegalArgumentException();
|
||||
}
|
||||
|
||||
news.setDate(new Date());
|
||||
newsService.update(id, toEntity(news));
|
||||
typeService.getAll();
|
||||
return Constants.REDIRECT_VIEW + URL;
|
||||
}
|
||||
|
||||
@PostMapping("/delete/{id}")
|
||||
public String delete(
|
||||
@PathVariable(name = "id") Long id) {
|
||||
newsService.delete(id);
|
||||
return Constants.REDIRECT_VIEW + URL;
|
||||
}
|
||||
}
|
@ -0,0 +1,99 @@
|
||||
package com.example.demo.news.api;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
|
||||
public class NewsDto {
|
||||
private Long id;
|
||||
|
||||
@NotNull
|
||||
private Long typeId;
|
||||
|
||||
private String typeName;
|
||||
// @NotNull
|
||||
private Long userId;
|
||||
@NotNull
|
||||
private String title;
|
||||
@NotNull
|
||||
private String text;
|
||||
// @NotNull
|
||||
private Date date;
|
||||
|
||||
private String userName;
|
||||
private Long reviewsCount;
|
||||
|
||||
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getTypeName() {
|
||||
return typeName;
|
||||
}
|
||||
|
||||
public void setTypeName(String typeName) {
|
||||
this.typeName = typeName;
|
||||
}
|
||||
|
||||
public Long getReviewsCount() {
|
||||
return reviewsCount;
|
||||
}
|
||||
|
||||
public void setReviewsCount(Long count) {
|
||||
this.reviewsCount = count;
|
||||
}
|
||||
|
||||
public String getUserName() {
|
||||
return userName;
|
||||
}
|
||||
|
||||
public void setUserName(String name) {
|
||||
this.userName = name;
|
||||
}
|
||||
|
||||
public Long getUserId() {
|
||||
return userId;
|
||||
}
|
||||
|
||||
public void setUserId(Long userId) {
|
||||
this.userId = userId;
|
||||
}
|
||||
|
||||
public Long getTypeId() {
|
||||
return typeId;
|
||||
}
|
||||
|
||||
public void setTypeId(Long id) {
|
||||
this.typeId = id;
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
|
||||
public void setTitle(String title) {
|
||||
this.title = title;
|
||||
}
|
||||
|
||||
public String getText() {
|
||||
return text;
|
||||
}
|
||||
|
||||
public void setText(String text) {
|
||||
this.text = text;
|
||||
}
|
||||
|
||||
public Date getDate() {
|
||||
return date;
|
||||
}
|
||||
|
||||
public void setDate(Date date) {
|
||||
this.date = date;
|
||||
}
|
||||
}
|
@ -0,0 +1,31 @@
|
||||
package com.example.demo.news.api;
|
||||
|
||||
public class NewsGroupedDto {
|
||||
private String typeName;
|
||||
private String title;
|
||||
private String text;
|
||||
|
||||
public String getTypeName() {
|
||||
return typeName;
|
||||
}
|
||||
|
||||
public void setTypeName(String typeName) {
|
||||
this.typeName = typeName;
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
|
||||
public void setTitle(String title) {
|
||||
this.title = title;
|
||||
}
|
||||
|
||||
public String getText() {
|
||||
return text;
|
||||
}
|
||||
|
||||
public void setText(String text) {
|
||||
this.text = text;
|
||||
}
|
||||
}
|
@ -0,0 +1,26 @@
|
||||
package com.example.demo.news.model;
|
||||
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
import com.example.demo.types.model.TypeEntity;
|
||||
import com.example.demo.users.model.UserEntity;
|
||||
|
||||
public class ExtendedNewsEntity extends NewsEntity {
|
||||
private Long reviewsCount;
|
||||
|
||||
public ExtendedNewsEntity(Long id, TypeEntity type, UserEntity user, String title, String text, Date date,
|
||||
Long reviewsCount) {
|
||||
super(type, user, title, text, date);
|
||||
this.reviewsCount = reviewsCount;
|
||||
this.setId(id);
|
||||
}
|
||||
|
||||
public void setReviewsCount(Long count) {
|
||||
this.reviewsCount = count;
|
||||
}
|
||||
|
||||
public Long getReviewsCount() {
|
||||
return reviewsCount;
|
||||
}
|
||||
}
|
@ -0,0 +1,124 @@
|
||||
package com.example.demo.news.model;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.Objects;
|
||||
|
||||
import com.example.demo.core.model.BaseEntity;
|
||||
import com.example.demo.reviews.model.ReviewEntity;
|
||||
import com.example.demo.types.model.TypeEntity;
|
||||
import com.example.demo.users.model.UserEntity;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.JoinColumn;
|
||||
import jakarta.persistence.ManyToOne;
|
||||
import jakarta.persistence.Table;
|
||||
|
||||
@Entity
|
||||
@Table(name = "news")
|
||||
public class NewsEntity extends BaseEntity {
|
||||
@ManyToOne
|
||||
@JoinColumn(name = "typeId", nullable = false)
|
||||
private TypeEntity type;
|
||||
|
||||
@ManyToOne
|
||||
@JoinColumn(name = "userId")
|
||||
private UserEntity user;
|
||||
|
||||
@Column(nullable = false)
|
||||
private String title;
|
||||
|
||||
@Column(nullable = false)
|
||||
private String text;
|
||||
|
||||
@Column(nullable = false)
|
||||
private Date date;
|
||||
|
||||
public NewsEntity() {
|
||||
}
|
||||
|
||||
public NewsEntity(TypeEntity type, String title, String text, Date date) {
|
||||
this.type = type;
|
||||
this.title = title;
|
||||
this.text = text;
|
||||
this.date = date;
|
||||
}
|
||||
|
||||
public NewsEntity(TypeEntity type, UserEntity user, String title, String text, Date date) {
|
||||
this.type = type;
|
||||
this.user = user;
|
||||
this.title = title;
|
||||
this.text = text;
|
||||
this.date = date;
|
||||
}
|
||||
|
||||
public TypeEntity getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public void setType(TypeEntity type) {
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
public UserEntity getUser() {
|
||||
return user;
|
||||
}
|
||||
|
||||
public void setUser(UserEntity user) {
|
||||
if (user == null) {
|
||||
return; // Защита от NullPointerException
|
||||
}
|
||||
|
||||
if (this.user != null && this.user.equals(user)) {
|
||||
return; // Проверка на дублирование связи
|
||||
}
|
||||
|
||||
this.user = user;
|
||||
user.addNews(this); // Добавляем обратную связь
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
|
||||
public void setTitle(String title) {
|
||||
this.title = title;
|
||||
}
|
||||
|
||||
public String getText() {
|
||||
return text;
|
||||
}
|
||||
|
||||
public void setText(String text) {
|
||||
this.text = text;
|
||||
}
|
||||
|
||||
public Date getDate() {
|
||||
return date;
|
||||
}
|
||||
|
||||
public void setDate(Date date) {
|
||||
this.date = date;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(super.hashCode(), type, user, title, text, date);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null || getClass() != obj.getClass())
|
||||
return false;
|
||||
if (!super.equals(obj))
|
||||
return false;
|
||||
final NewsEntity other = (NewsEntity) obj;
|
||||
return Objects.equals(this.type, other.type)
|
||||
&& Objects.equals(this.user, other.user)
|
||||
&& Objects.equals(this.title, other.title)
|
||||
&& Objects.equals(this.text, other.text)
|
||||
&& Objects.equals(this.date, other.date);
|
||||
}
|
||||
}
|
@ -0,0 +1,65 @@
|
||||
package com.example.demo.news.repository;
|
||||
|
||||
import java.util.Calendar;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.CrudRepository;
|
||||
import org.springframework.data.repository.PagingAndSortingRepository;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
|
||||
import com.example.demo.news.model.ExtendedNewsEntity;
|
||||
import com.example.demo.news.model.NewsEntity;
|
||||
|
||||
public interface NewsRepository extends CrudRepository<NewsEntity, Long>,
|
||||
PagingAndSortingRepository<NewsEntity, Long> {
|
||||
|
||||
Optional<NewsEntity> findOneByUserIdAndId(long userId, long newsId);
|
||||
|
||||
List<NewsEntity> findByUserId(long userId);
|
||||
|
||||
Optional<NewsEntity> findById(long newsId);
|
||||
|
||||
List<NewsEntity> findByUserIdAndTypeId(long userId, long typeId);
|
||||
|
||||
@Query("select n from UserEntity u join u.news n where u.id = ?1 and n.date >= ?2 and n.date <= ?3")
|
||||
List<NewsEntity> getNewsByUserIdForLastMonth(long userId, Calendar start, Calendar finish);
|
||||
|
||||
@Query("select o from UserEntity u join u.news o where o.date >= ?1 and o.date <= ?2")
|
||||
Page<NewsEntity> getNewsForLastMonth(Calendar start, Calendar finish, Pageable pageable);
|
||||
|
||||
Page<NewsEntity> findByUserId(long userId, Pageable pageable);
|
||||
|
||||
Page<NewsEntity> findByTypeId(long typeId, Pageable pageable);
|
||||
|
||||
Page<NewsEntity> findByUserIdAndTypeId(long userId, long typeId, Pageable pageable);
|
||||
|
||||
@Query("SELECT new com.example.demo.news.model.ExtendedNewsEntity(n.id, n.type, n.user, n.title, n.text, n.date, COUNT(r.id)) "
|
||||
+
|
||||
"FROM NewsEntity n " +
|
||||
"LEFT JOIN ReviewEntity r ON r.news.id = n.id " +
|
||||
"GROUP BY n.id, n.type, n.user, n.title, n.text, n.date")
|
||||
Page<ExtendedNewsEntity> findAllNewsWithReviewCount(Pageable pageable);
|
||||
|
||||
// !!!
|
||||
|
||||
@Query("SELECT new com.example.demo.news.model.ExtendedNewsEntity(n.id, n.type, n.user, n.title, n.text, n.date, COUNT(r.id)) "
|
||||
+
|
||||
"FROM NewsEntity n " +
|
||||
"LEFT JOIN ReviewEntity r ON r.news.id = n.id " +
|
||||
"WHERE (:userId = 0L OR n.user.id = :userId) " +
|
||||
"AND (:typeId = 0L OR n.type.id = :typeId) " +
|
||||
"AND n.date BETWEEN :startDate AND :endDate " +
|
||||
"GROUP BY n.id, n.type, n.user, n.title, n.text, n.date")
|
||||
Page<ExtendedNewsEntity> findNewsWithReviewsCount(@Param("userId") long userId,
|
||||
@Param("typeId") long typeId,
|
||||
@Param("startDate") Calendar startDate,
|
||||
@Param("endDate") Calendar endDate,
|
||||
Pageable pageable);
|
||||
|
||||
Optional<NewsEntity> findByTitleIgnoreCase(String title);
|
||||
|
||||
}
|
@ -0,0 +1,181 @@
|
||||
package com.example.demo.news.service;
|
||||
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.stream.StreamSupport;
|
||||
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import com.example.demo.core.error.NotFoundException;
|
||||
import com.example.demo.news.model.ExtendedNewsEntity;
|
||||
import com.example.demo.news.model.NewsEntity;
|
||||
import com.example.demo.news.repository.NewsRepository;
|
||||
import com.example.demo.reviews.model.ReviewEntity;
|
||||
import com.example.demo.users.model.UserEntity;
|
||||
import com.example.demo.users.service.UserService;
|
||||
|
||||
import groovyjarjarantlr4.v4.parse.ANTLRParser.elementOption_return;
|
||||
|
||||
@Service
|
||||
public class NewsService {
|
||||
private final NewsRepository repository;
|
||||
private final UserService userService;
|
||||
|
||||
public NewsService(NewsRepository repository, UserService userService) {
|
||||
this.repository = repository;
|
||||
this.userService = userService;
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<NewsEntity> getAll(long userId, Long typeId) {
|
||||
userService.get(userId);
|
||||
if (typeId == null || typeId <= 0L) {
|
||||
return repository.findByUserId(userId);
|
||||
} else {
|
||||
return repository.findByUserIdAndTypeId(userId, typeId);
|
||||
}
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<NewsEntity> getAll() {
|
||||
return StreamSupport
|
||||
.stream(repository.findAll().spliterator(), false)
|
||||
.toList();
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public Page<ExtendedNewsEntity> getAllWithReviewsCount(int page, int size) {
|
||||
final Pageable pageable = PageRequest.of(page, size);
|
||||
return repository.findAllNewsWithReviewCount(pageable);
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public Page<NewsEntity> getAll(int page, int size) {
|
||||
final Pageable pageable = PageRequest.of(page, size);
|
||||
return repository.findAll(pageable);
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public Page<NewsEntity> getAll(long userId, int page, int size) {
|
||||
final Pageable pageable = PageRequest.of(page, size);
|
||||
userService.get(userId);
|
||||
return repository.findByUserId(userId, pageable);
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public NewsEntity get(long userId, long id) {
|
||||
userService.get(userId);
|
||||
return repository.findOneByUserIdAndId(userId, id)
|
||||
.orElseThrow(() -> new NotFoundException(NewsEntity.class, id));
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public NewsEntity get(long id) {
|
||||
return repository.findById(id)
|
||||
.orElseThrow(() -> new NotFoundException(NewsEntity.class, id));
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public NewsEntity getNews(long id) {
|
||||
return repository.findById(id)
|
||||
.orElseThrow(() -> new NotFoundException(NewsEntity.class, id));
|
||||
}
|
||||
private void checkTitle(String title) {
|
||||
if (repository.findByTitleIgnoreCase(title).isPresent()) {
|
||||
throw new IllegalArgumentException(String.format("News with title %s is already exists", title));
|
||||
}
|
||||
}
|
||||
@Transactional
|
||||
public NewsEntity create(long userId, NewsEntity entity) {
|
||||
if (entity == null) {
|
||||
throw new IllegalArgumentException("Entity is null");
|
||||
}
|
||||
checkTitle(entity.getTitle());
|
||||
UserEntity existsUser = userService.get(userId);
|
||||
entity.setUser(existsUser);
|
||||
return repository.save(entity);
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public Page<NewsEntity> getAll(long userId, Long typeId, int page, int size) {
|
||||
final Pageable pageable = PageRequest.of(page, size);
|
||||
|
||||
if (Objects.equals(userId, 0L) && Objects.equals(typeId, 0L)) {
|
||||
return repository.findAll(pageable);
|
||||
}
|
||||
|
||||
if (Objects.equals(userId, 0L)) {
|
||||
return repository.findByTypeId(typeId, pageable);
|
||||
}
|
||||
|
||||
if (Objects.equals(typeId, 0L)) {
|
||||
return repository.findByUserId(userId, pageable);
|
||||
}
|
||||
|
||||
return repository.findByUserIdAndTypeId(userId, typeId, pageable);
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public Page<NewsEntity> getNewsByMonth(Calendar startDate, Calendar finishDate, int page,
|
||||
int size) {
|
||||
final Pageable pageable = PageRequest.of(page, size, Sort.by("id"));
|
||||
|
||||
return repository.getNewsForLastMonth(startDate, finishDate, pageable);
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public Page<ExtendedNewsEntity> getAllWithReviewsCount(Long userId, Long typeId, Calendar startDate,
|
||||
Calendar endDate, int page, int size) {
|
||||
Pageable pageable = PageRequest.of(page, size, Sort.by("id"));
|
||||
return repository.findNewsWithReviewsCount(userId, typeId, startDate, endDate, pageable);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public NewsEntity update(long userId, Long id, NewsEntity entity) {
|
||||
userService.get(userId);
|
||||
NewsEntity existsEntity = get(userId, id);
|
||||
existsEntity.setTitle(entity.getTitle());
|
||||
existsEntity.setText(entity.getText());
|
||||
existsEntity.setDate(entity.getDate());
|
||||
existsEntity.setType(entity.getType());
|
||||
return repository.save(existsEntity);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public NewsEntity update(Long id, NewsEntity entity) {
|
||||
NewsEntity existsEntity = get(id);
|
||||
existsEntity.setTitle(entity.getTitle());
|
||||
existsEntity.setText(entity.getText());
|
||||
existsEntity.setDate(entity.getDate());
|
||||
existsEntity.setType(entity.getType());
|
||||
return repository.save(existsEntity);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public NewsEntity delete(long userId, Long id) {
|
||||
userService.get(userId);
|
||||
NewsEntity existsEntity = get(userId, id);
|
||||
repository.delete(existsEntity);
|
||||
return existsEntity;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public NewsEntity delete(Long id) {
|
||||
NewsEntity existsEntity = get(id);
|
||||
repository.delete(existsEntity);
|
||||
return existsEntity;
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<NewsEntity> getNewsByUserIdForLastMonth(long userId, Calendar start, Calendar finish) {
|
||||
userService.get(userId);
|
||||
return repository.getNewsByUserIdForLastMonth(userId, start, finish);
|
||||
}
|
||||
}
|
@ -0,0 +1,149 @@
|
||||
package com.example.demo.reviews.api;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.Map;
|
||||
|
||||
import org.springframework.security.core.annotation.AuthenticationPrincipal;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.modelmapper.ModelMapper;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.ModelAttribute;
|
||||
import org.springframework.validation.BindingResult;
|
||||
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
|
||||
|
||||
import com.example.demo.core.api.PageAttributesMapper;
|
||||
import com.example.demo.core.configuration.Constants;
|
||||
import com.example.demo.core.security.UserPrincipal;
|
||||
import com.example.demo.news.service.NewsService;
|
||||
import com.example.demo.reviews.model.ReviewEntity;
|
||||
import com.example.demo.reviews.service.ReviewService;
|
||||
import com.example.demo.users.service.UserService;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
|
||||
@Controller
|
||||
@RequestMapping(ReviewController.URL)
|
||||
public class ReviewController {
|
||||
public static final String URL = "/reviews";
|
||||
private static final String REVIEW_VIEW = "reviews";
|
||||
private static final String PAGE_ATTRIBUTE = "page";
|
||||
private static final String REVIEW_ATTRIBUTE = "review";
|
||||
private static final String REVIEW_EDIT_VIEW = "review-edit";
|
||||
|
||||
private final ReviewService reviewService;
|
||||
private final UserService userService;
|
||||
private final NewsService newsService;
|
||||
private final ModelMapper modelMapper;
|
||||
|
||||
public ReviewController(ReviewService reviewService, NewsService newsService, UserService userService, ModelMapper modelMapper) {
|
||||
this.reviewService = reviewService;
|
||||
this.userService = userService;
|
||||
this.modelMapper = modelMapper;
|
||||
this.newsService = newsService;
|
||||
}
|
||||
|
||||
private ReviewDto toDto(ReviewEntity entity) {
|
||||
ReviewDto dto = modelMapper.map(entity, ReviewDto.class);
|
||||
dto.setNewsName(entity.getNews().getTitle());
|
||||
return dto;
|
||||
}
|
||||
|
||||
private ReviewEntity toEntity(ReviewDto dto) {
|
||||
final ReviewEntity entity = modelMapper.map(dto, ReviewEntity.class);
|
||||
entity.setNews(newsService.get(dto.getNewsId()));
|
||||
return entity;
|
||||
}
|
||||
@GetMapping
|
||||
public String getAll(
|
||||
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
|
||||
@AuthenticationPrincipal UserPrincipal principal,
|
||||
Model model) {
|
||||
final Map<String, Object> attributes = PageAttributesMapper.toAttributes(
|
||||
reviewService.getAll(principal.getId(), page, Constants.DEFUALT_PAGE_SIZE), this::toDto);
|
||||
model.addAllAttributes(attributes);
|
||||
model.addAttribute(PAGE_ATTRIBUTE, page);
|
||||
return REVIEW_VIEW;
|
||||
}
|
||||
|
||||
@GetMapping("/news/{id}")
|
||||
public String getAllForNews(
|
||||
@PathVariable(name = "id") Long id,
|
||||
@PathVariable(name = "news") Long newsId,
|
||||
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
|
||||
Model model) {
|
||||
final Map<String, Object> attributes = PageAttributesMapper.toAttributes(
|
||||
reviewService.getAllForNews(newsId,page, Constants.DEFUALT_PAGE_SIZE), this::toDto);
|
||||
model.addAllAttributes(attributes);
|
||||
model.addAttribute(PAGE_ATTRIBUTE, page);
|
||||
return REVIEW_VIEW;
|
||||
}
|
||||
|
||||
@GetMapping("/edit/")
|
||||
public String create(
|
||||
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
|
||||
Model model) {
|
||||
model.addAttribute(REVIEW_ATTRIBUTE, new ReviewDto());
|
||||
model.addAttribute(PAGE_ATTRIBUTE, page);
|
||||
model.addAttribute("news", newsService.getAll());
|
||||
return REVIEW_EDIT_VIEW;
|
||||
}
|
||||
|
||||
@PostMapping("/edit/")
|
||||
public String create(
|
||||
@AuthenticationPrincipal UserPrincipal principal,
|
||||
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
|
||||
@ModelAttribute(name = REVIEW_ATTRIBUTE) @Valid ReviewDto review,
|
||||
BindingResult bindingResult,
|
||||
Model model,
|
||||
RedirectAttributes redirectAttributes) {
|
||||
if (bindingResult.hasErrors()) {
|
||||
model.addAttribute(PAGE_ATTRIBUTE, page);
|
||||
return REVIEW_EDIT_VIEW;
|
||||
}
|
||||
redirectAttributes.addAttribute(PAGE_ATTRIBUTE, page);
|
||||
review.setDate(new Date());
|
||||
reviewService.create(principal.getId(), toEntity(review));
|
||||
return Constants.REDIRECT_VIEW + URL;
|
||||
}
|
||||
|
||||
@GetMapping("/edit/{id}")
|
||||
public String update(
|
||||
@PathVariable(name = "id") Long id,
|
||||
Model model) {
|
||||
if (id <= 0) {
|
||||
throw new IllegalArgumentException();
|
||||
}
|
||||
model.addAttribute("news", newsService.getAll());
|
||||
|
||||
model.addAttribute(REVIEW_ATTRIBUTE, toDto(reviewService.get(id)));
|
||||
return REVIEW_EDIT_VIEW;
|
||||
}
|
||||
|
||||
@PostMapping("/edit/{id}")
|
||||
public String update(
|
||||
@PathVariable(name = "id") Long id,
|
||||
@ModelAttribute(name = REVIEW_ATTRIBUTE) @Valid ReviewDto review,
|
||||
BindingResult bindingResult,
|
||||
Model model) {
|
||||
if (bindingResult.hasErrors()) {
|
||||
return REVIEW_EDIT_VIEW;
|
||||
}
|
||||
if (id <= 0) {
|
||||
throw new IllegalArgumentException();
|
||||
}
|
||||
reviewService.update(id, toEntity(review));
|
||||
return Constants.REDIRECT_VIEW + URL;
|
||||
}
|
||||
|
||||
@PostMapping("/delete/{id}")
|
||||
public String delete(
|
||||
@PathVariable(name = "id") Long id) {
|
||||
reviewService.delete(id);
|
||||
return Constants.REDIRECT_VIEW + URL;
|
||||
}
|
||||
}
|
@ -0,0 +1,64 @@
|
||||
package com.example.demo.reviews.api;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import java.util.Date;
|
||||
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
|
||||
public class ReviewDto {
|
||||
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
|
||||
private Long id;
|
||||
|
||||
// @JsonProperty(access = JsonProperty.Access.READ_ONLY)
|
||||
// @NotNull
|
||||
// @Min(1)
|
||||
// private Long userId;
|
||||
// @NotNull
|
||||
private Date date;
|
||||
@NotNull
|
||||
private String text;
|
||||
@NotNull
|
||||
private Long newsId;
|
||||
|
||||
private String newsName;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getNewsName() {
|
||||
return newsName;
|
||||
}
|
||||
|
||||
public void setNewsName(String name) {
|
||||
this.newsName = name;
|
||||
}
|
||||
|
||||
public Long getNewsId() {
|
||||
return newsId;
|
||||
}
|
||||
|
||||
public void setNewsId(Long id) {
|
||||
this.newsId = id;
|
||||
}
|
||||
|
||||
public Date getDate() {
|
||||
return date;
|
||||
}
|
||||
|
||||
public void setDate(Date date) {
|
||||
this.date = date;
|
||||
}
|
||||
|
||||
public String getText() {
|
||||
return text;
|
||||
}
|
||||
|
||||
public void setText(String text) {
|
||||
this.text = text;
|
||||
}
|
||||
}
|
@ -0,0 +1,87 @@
|
||||
package com.example.demo.reviews.model;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.Objects;
|
||||
import com.example.demo.core.model.BaseEntity;
|
||||
import com.example.demo.users.model.UserEntity;
|
||||
import com.example.demo.news.model.NewsEntity;
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.JoinColumn;
|
||||
import jakarta.persistence.ManyToOne;
|
||||
import jakarta.persistence.Table;
|
||||
|
||||
@Entity
|
||||
@Table(name = "reviews")
|
||||
public class ReviewEntity extends BaseEntity {
|
||||
@ManyToOne
|
||||
@JoinColumn(name = "userId", nullable = false)
|
||||
private UserEntity user;
|
||||
|
||||
@ManyToOne
|
||||
@JoinColumn(name = "newsId", nullable = false)
|
||||
private NewsEntity news;
|
||||
|
||||
@Column(nullable = false)
|
||||
private Date date;
|
||||
|
||||
@Column(nullable = false)
|
||||
private String text;
|
||||
|
||||
public ReviewEntity() {
|
||||
}
|
||||
|
||||
public ReviewEntity(Date date, String text) {
|
||||
this.date = date;
|
||||
this.text = text;
|
||||
}
|
||||
|
||||
public UserEntity getUser() {
|
||||
return user;
|
||||
}
|
||||
|
||||
public void setUser(UserEntity user) {
|
||||
this.user = user;
|
||||
}
|
||||
|
||||
public NewsEntity getNews() {
|
||||
return news;
|
||||
}
|
||||
|
||||
public void setNews(NewsEntity news) {
|
||||
this.news = news;
|
||||
}
|
||||
|
||||
public Date getDate() {
|
||||
return date;
|
||||
}
|
||||
|
||||
public void setDate(Date date) {
|
||||
this.date = date;
|
||||
}
|
||||
|
||||
public String getText() {
|
||||
return text;
|
||||
}
|
||||
|
||||
public void setText(String text) {
|
||||
this.text = text;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(id, user, news, date, text);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null || getClass() != obj.getClass())
|
||||
return false;
|
||||
final ReviewEntity other = (ReviewEntity) obj;
|
||||
return Objects.equals(other.getId(), id)
|
||||
&& Objects.equals(other.getDate(), date)
|
||||
&& Objects.equals(other.getText(), text);
|
||||
}
|
||||
}
|
@ -0,0 +1,29 @@
|
||||
package com.example.demo.reviews.repository;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.repository.CrudRepository;
|
||||
import org.springframework.data.repository.PagingAndSortingRepository;
|
||||
|
||||
import com.example.demo.reviews.model.ReviewEntity;
|
||||
|
||||
public interface ReviewRepository
|
||||
extends CrudRepository<ReviewEntity, Long>, PagingAndSortingRepository<ReviewEntity, Long> {
|
||||
// поиск одного отзыва по айди пользователя и айди отзыва
|
||||
Optional<ReviewEntity> findOneByUserIdAndId(long userId, long id);
|
||||
|
||||
Optional<ReviewEntity> findOneById(long id);
|
||||
// поиск одного отзыва по айди новости и айди отзыва
|
||||
Optional<ReviewEntity> findOneByNewsIdAndId(long newsId, long id);
|
||||
// поиск всех отзывов пользователя
|
||||
List<ReviewEntity> findByUserId(long userId);
|
||||
|
||||
List<ReviewEntity> findByNewsId(long newsId);
|
||||
|
||||
Page<ReviewEntity> findByUserId(long userId, Pageable pageable);
|
||||
|
||||
Page<ReviewEntity> findByNewsId(long newsId,Pageable pageable);
|
||||
}
|
@ -0,0 +1,117 @@
|
||||
package com.example.demo.reviews.service;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.stream.StreamSupport;
|
||||
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import com.example.demo.core.error.NotFoundException;
|
||||
import com.example.demo.news.service.NewsService;
|
||||
import com.example.demo.reviews.model.ReviewEntity;
|
||||
import com.example.demo.reviews.repository.ReviewRepository;
|
||||
import com.example.demo.users.model.UserEntity;
|
||||
import com.example.demo.users.service.UserService;
|
||||
|
||||
@Service
|
||||
public class ReviewService {
|
||||
private final ReviewRepository repository;
|
||||
private final UserService userService;
|
||||
private final NewsService newsService;
|
||||
|
||||
public ReviewService(ReviewRepository repository, UserService userService,NewsService newsService) {
|
||||
this.repository = repository;
|
||||
this.userService = userService;
|
||||
this.newsService = newsService;
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<ReviewEntity> getAll(long userId) {
|
||||
// если айдишник юзера 0 или -, чего не может быть, то мы выдаем все отзывы в
|
||||
// принципе
|
||||
if (userId <= 0) {
|
||||
return StreamSupport.stream(repository.findAll().spliterator(), false).toList();
|
||||
}
|
||||
userService.get(userId);
|
||||
return repository.findByUserId(userId);
|
||||
}
|
||||
@Transactional(readOnly = true)
|
||||
public Page<ReviewEntity> getAll(int page, int size) {
|
||||
final Pageable pageable = PageRequest.of(page, size);
|
||||
return repository.findAll(pageable);
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public Page<ReviewEntity> getAll(long userId, int page, int size) {
|
||||
final Pageable pageable = PageRequest.of(page, size);
|
||||
return repository.findByUserId(userId, pageable);
|
||||
}
|
||||
|
||||
public List<ReviewEntity> getAllForNews(Long newsId) {
|
||||
if (newsId == null || newsId <= 0) {
|
||||
return StreamSupport.stream(repository.findAll().spliterator(), false).toList();
|
||||
}
|
||||
newsService.getNews(newsId);
|
||||
return repository.findByNewsId(newsId);
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public Page<ReviewEntity> getAllForNews(long newsId, int page, int size) {
|
||||
if (Objects.equals(newsId, 0L)) {
|
||||
return getAll(page, size);
|
||||
}
|
||||
|
||||
final Pageable pageRequest = PageRequest.of(page, size);
|
||||
newsService.getNews(newsId);
|
||||
return repository.findByNewsId(newsId, pageRequest);
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public ReviewEntity get(long id) {
|
||||
|
||||
return repository.findOneById(id)
|
||||
.orElseThrow(() -> new NotFoundException(ReviewEntity.class, id));
|
||||
}
|
||||
@Transactional(readOnly = true)
|
||||
public ReviewEntity getForNews(long newsId, Long id) {
|
||||
newsService.getNews(newsId);
|
||||
return repository.findOneByNewsIdAndId(newsId, id)
|
||||
.orElseThrow(() -> new NotFoundException(ReviewEntity.class, id));
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public ReviewEntity create(long userId, ReviewEntity entity) {
|
||||
if (entity == null) {
|
||||
throw new IllegalArgumentException("Entity is null");
|
||||
}
|
||||
final UserEntity existsUser = userService.get(userId);
|
||||
entity.setUser(existsUser);
|
||||
return repository.save(entity);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public ReviewEntity update(long id, ReviewEntity entity) {
|
||||
// userService.get(userId);
|
||||
final ReviewEntity existsEntity = get(id);
|
||||
// existsEntity.setUser(entity.getUser());
|
||||
existsEntity.setDate(new Date());
|
||||
existsEntity.setText(entity.getText());
|
||||
existsEntity.setNews(entity.getNews());
|
||||
return repository.save(existsEntity);
|
||||
}
|
||||
|
||||
// метод удаления принимает в себя айди юзера и айди отзыва.
|
||||
@Transactional
|
||||
public ReviewEntity delete(long id) {
|
||||
// userService.get(userId); // зачем эта строчка вообще?
|
||||
final ReviewEntity existsEntity = get(id);
|
||||
repository.delete(existsEntity);
|
||||
return existsEntity;
|
||||
}
|
||||
}
|
@ -0,0 +1,104 @@
|
||||
package com.example.demo.types.api;
|
||||
|
||||
import org.modelmapper.ModelMapper;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.validation.BindingResult;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.ModelAttribute;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
|
||||
import com.example.demo.core.configuration.Constants;
|
||||
import com.example.demo.types.model.TypeEntity;
|
||||
import com.example.demo.types.service.TypeService;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
|
||||
@Controller
|
||||
@RequestMapping(TypeController.URL)
|
||||
public class TypeController {
|
||||
public static final String URL = Constants.ADMIN_PREFIX + "/type";
|
||||
private static final String TYPE_VIEW = "type";
|
||||
private static final String TYPE_EDIT_VIEW = "type-edit";
|
||||
private static final String TYPE_ATTRIBUTE = "type";
|
||||
|
||||
private final TypeService typeService;
|
||||
private final ModelMapper modelMapper;
|
||||
|
||||
public TypeController(TypeService typeService, ModelMapper modelMapper) {
|
||||
this.typeService = typeService;
|
||||
this.modelMapper = modelMapper;
|
||||
}
|
||||
|
||||
private TypeDto toDto(TypeEntity entity) {
|
||||
return modelMapper.map(entity, TypeDto.class);
|
||||
}
|
||||
|
||||
private TypeEntity toEntity(TypeDto dto) {
|
||||
return modelMapper.map(dto, TypeEntity.class);
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public String getAll(Model model) {
|
||||
model.addAttribute(
|
||||
"items",
|
||||
typeService.getAll().stream()
|
||||
.map(this::toDto)
|
||||
.toList());
|
||||
return TYPE_VIEW;
|
||||
}
|
||||
|
||||
@GetMapping("/edit/")
|
||||
public String create(Model model) {
|
||||
model.addAttribute(TYPE_ATTRIBUTE, new TypeDto());
|
||||
return TYPE_EDIT_VIEW;
|
||||
}
|
||||
|
||||
@PostMapping("/edit/")
|
||||
public String create(
|
||||
@ModelAttribute(name = TYPE_ATTRIBUTE) @Valid TypeDto type,
|
||||
BindingResult bindingResult,
|
||||
Model model) {
|
||||
if (bindingResult.hasErrors()) {
|
||||
return TYPE_EDIT_VIEW;
|
||||
}
|
||||
typeService.create(toEntity(type));
|
||||
return Constants.REDIRECT_VIEW + URL;
|
||||
}
|
||||
|
||||
@GetMapping("/edit/{id}")
|
||||
public String update(
|
||||
@PathVariable(name = "id") Long id,
|
||||
Model model) {
|
||||
if (id <= 0) {
|
||||
throw new IllegalArgumentException();
|
||||
}
|
||||
model.addAttribute(TYPE_ATTRIBUTE, toDto(typeService.get(id)));
|
||||
return TYPE_EDIT_VIEW;
|
||||
}
|
||||
|
||||
@PostMapping("/edit/{id}")
|
||||
public String update(
|
||||
@PathVariable(name = "id") Long id,
|
||||
@ModelAttribute(name = TYPE_ATTRIBUTE) @Valid TypeDto type,
|
||||
BindingResult bindingResult,
|
||||
Model model) {
|
||||
if (bindingResult.hasErrors()) {
|
||||
return TYPE_EDIT_VIEW;
|
||||
}
|
||||
if (id <= 0) {
|
||||
throw new IllegalArgumentException();
|
||||
}
|
||||
typeService.update(id, toEntity(type));
|
||||
return Constants.REDIRECT_VIEW + URL;
|
||||
}
|
||||
|
||||
@PostMapping("/delete/{id}")
|
||||
public String delete(
|
||||
@PathVariable(name = "id") Long id) {
|
||||
typeService.delete(id);
|
||||
return Constants.REDIRECT_VIEW + URL;
|
||||
}
|
||||
}
|
@ -0,0 +1,28 @@
|
||||
package com.example.demo.types.api;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Size;
|
||||
|
||||
public class TypeDto {
|
||||
private Long id;
|
||||
@NotBlank
|
||||
@Size(min = 5, max = 50)
|
||||
private String name;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,47 @@
|
||||
package com.example.demo.types.model;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
import com.example.demo.core.model.BaseEntity;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.Table;
|
||||
|
||||
@Entity
|
||||
@Table(name = "types")
|
||||
public class TypeEntity extends BaseEntity {
|
||||
|
||||
@Column(nullable = false, unique = true, length = 50)
|
||||
private String name;
|
||||
|
||||
public TypeEntity() {
|
||||
}
|
||||
|
||||
public TypeEntity(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(getId(), name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null || getClass() != obj.getClass())
|
||||
return false;
|
||||
final TypeEntity other = (TypeEntity) obj;
|
||||
return Objects.equals(other.getId(), getId()) && Objects.equals(other.getName(), name);
|
||||
}
|
||||
}
|
@ -0,0 +1,13 @@
|
||||
package com.example.demo.types.repository;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.data.repository.CrudRepository;
|
||||
import org.springframework.data.repository.PagingAndSortingRepository;
|
||||
|
||||
import com.example.demo.types.model.TypeEntity;
|
||||
|
||||
public interface TypeRepository
|
||||
extends CrudRepository<TypeEntity, Long>, PagingAndSortingRepository<TypeEntity, Long> {
|
||||
Optional<TypeEntity> findByNameIgnoreCase(String name);
|
||||
}
|
@ -0,0 +1,75 @@
|
||||
package com.example.demo.types.service;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.StreamSupport;
|
||||
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import com.example.demo.core.error.NotFoundException;
|
||||
import com.example.demo.types.model.TypeEntity;
|
||||
import com.example.demo.types.repository.TypeRepository;
|
||||
|
||||
@Service
|
||||
public class TypeService {
|
||||
private final TypeRepository repository;
|
||||
|
||||
public TypeService(TypeRepository repository) {
|
||||
this.repository = repository;
|
||||
}
|
||||
|
||||
private void checkName(Long id, String name) {
|
||||
final Optional<TypeEntity> existsType = repository.findByNameIgnoreCase(name);
|
||||
if (existsType.isPresent() && !existsType.get().getId().equals(id)) {
|
||||
throw new IllegalArgumentException(
|
||||
String.format("Type with name %s is already exists", name));
|
||||
}
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<TypeEntity> getAll() {
|
||||
return StreamSupport.stream(repository.findAll(Sort.by("id")).spliterator(), false).toList();
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<TypeEntity> getByIds(Collection<Long> ids) {
|
||||
final List<TypeEntity> types = StreamSupport.stream(repository.findAllById(ids).spliterator(), false).toList();
|
||||
if (types.size() < ids.size()) {
|
||||
throw new IllegalArgumentException("Invalid type");
|
||||
}
|
||||
return types;
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public TypeEntity get(long id) {
|
||||
return repository.findById(id)
|
||||
.orElseThrow(() -> new NotFoundException(TypeEntity.class, id));
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public TypeEntity create(TypeEntity entity) {
|
||||
if (entity == null) {
|
||||
throw new IllegalArgumentException("Entity is null");
|
||||
}
|
||||
checkName(null, entity.getName());
|
||||
return repository.save(entity);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public TypeEntity update(Long id, TypeEntity entity) {
|
||||
final TypeEntity existsEntity = get(id);
|
||||
checkName(id, entity.getName());
|
||||
existsEntity.setName(entity.getName());
|
||||
return repository.save(existsEntity);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public TypeEntity delete(Long id) {
|
||||
final TypeEntity existsEntity = get(id);
|
||||
repository.delete(existsEntity);
|
||||
return existsEntity;
|
||||
}
|
||||
}
|
@ -0,0 +1,127 @@
|
||||
package com.example.demo.users.api;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import org.modelmapper.ModelMapper;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.validation.BindingResult;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.ModelAttribute;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
|
||||
|
||||
import com.example.demo.core.api.PageAttributesMapper;
|
||||
import com.example.demo.core.configuration.Constants;
|
||||
import com.example.demo.users.model.UserEntity;
|
||||
import com.example.demo.users.service.UserService;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
|
||||
@Controller
|
||||
@RequestMapping(UserController.URL)
|
||||
public class UserController {
|
||||
public static final String URL = Constants.ADMIN_PREFIX + "/user";
|
||||
private static final String USER_VIEW = "user";
|
||||
private static final String USER_EDIT_VIEW = "user-edit";
|
||||
private static final String PAGE_ATTRIBUTE = "page";
|
||||
private static final String USER_ATTRIBUTE = "user";
|
||||
|
||||
private final UserService userService;
|
||||
private final ModelMapper modelMapper;
|
||||
|
||||
public UserController(UserService userService, ModelMapper modelMapper) {
|
||||
this.userService = userService;
|
||||
this.modelMapper = modelMapper;
|
||||
}
|
||||
|
||||
private UserDto toDto(UserEntity entity) {
|
||||
return modelMapper.map(entity, UserDto.class);
|
||||
}
|
||||
|
||||
private UserEntity toEntity(UserDto dto) {
|
||||
return modelMapper.map(dto, UserEntity.class);
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public String getAll(
|
||||
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
|
||||
Model model) {
|
||||
final Map<String, Object> attributes = PageAttributesMapper.toAttributes(
|
||||
userService.getAll(page, Constants.DEFUALT_PAGE_SIZE), this::toDto);
|
||||
model.addAllAttributes(attributes);
|
||||
model.addAttribute(PAGE_ATTRIBUTE, page);
|
||||
return USER_VIEW;
|
||||
}
|
||||
|
||||
@GetMapping("/edit/")
|
||||
public String create(
|
||||
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
|
||||
Model model) {
|
||||
model.addAttribute(USER_ATTRIBUTE, new UserDto());
|
||||
model.addAttribute(PAGE_ATTRIBUTE, page);
|
||||
return USER_EDIT_VIEW;
|
||||
}
|
||||
|
||||
@PostMapping("/edit/")
|
||||
public String create(
|
||||
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
|
||||
@ModelAttribute(name = USER_ATTRIBUTE) @Valid UserDto user,
|
||||
BindingResult bindingResult,
|
||||
Model model,
|
||||
RedirectAttributes redirectAttributes) {
|
||||
if (bindingResult.hasErrors()) {
|
||||
model.addAttribute(PAGE_ATTRIBUTE, page);
|
||||
return USER_EDIT_VIEW;
|
||||
}
|
||||
redirectAttributes.addAttribute(PAGE_ATTRIBUTE, page);
|
||||
userService.create(toEntity(user));
|
||||
return Constants.REDIRECT_VIEW + URL;
|
||||
}
|
||||
|
||||
@GetMapping("/edit/{id}")
|
||||
public String update(
|
||||
@PathVariable(name = "id") Long id,
|
||||
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
|
||||
Model model) {
|
||||
if (id <= 0) {
|
||||
throw new IllegalArgumentException();
|
||||
}
|
||||
model.addAttribute(USER_ATTRIBUTE, toDto(userService.get(id)));
|
||||
model.addAttribute(PAGE_ATTRIBUTE, page);
|
||||
return USER_EDIT_VIEW;
|
||||
}
|
||||
|
||||
@PostMapping("/edit/{id}")
|
||||
public String update(
|
||||
@PathVariable(name = "id") Long id,
|
||||
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
|
||||
@ModelAttribute(name = USER_ATTRIBUTE) @Valid UserDto user,
|
||||
BindingResult bindingResult,
|
||||
Model model,
|
||||
RedirectAttributes redirectAttributes) {
|
||||
if (bindingResult.hasErrors()) {
|
||||
model.addAttribute(PAGE_ATTRIBUTE, page);
|
||||
return USER_EDIT_VIEW;
|
||||
}
|
||||
if (id <= 0) {
|
||||
throw new IllegalArgumentException();
|
||||
}
|
||||
redirectAttributes.addAttribute(PAGE_ATTRIBUTE, page);
|
||||
userService.update(id, toEntity(user));
|
||||
return Constants.REDIRECT_VIEW + URL;
|
||||
}
|
||||
|
||||
@PostMapping("/delete/{id}")
|
||||
public String delete(
|
||||
@PathVariable(name = "id") Long id,
|
||||
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
|
||||
RedirectAttributes redirectAttributes) {
|
||||
redirectAttributes.addAttribute(PAGE_ATTRIBUTE, page);
|
||||
userService.delete(id);
|
||||
return Constants.REDIRECT_VIEW + URL;
|
||||
}
|
||||
}
|
@ -0,0 +1,36 @@
|
||||
package com.example.demo.users.api;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Size;
|
||||
|
||||
public class UserDto {
|
||||
private Long id;
|
||||
@NotBlank
|
||||
@Size(min = 3, max = 20)
|
||||
private String login;
|
||||
private String role;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getLogin() {
|
||||
return login;
|
||||
}
|
||||
|
||||
public void setLogin(String login) {
|
||||
this.login = login;
|
||||
}
|
||||
|
||||
public String getRole() {
|
||||
return role;
|
||||
}
|
||||
|
||||
public void setRole(String role) {
|
||||
this.role = role;
|
||||
}
|
||||
}
|
@ -0,0 +1,65 @@
|
||||
package com.example.demo.users.api;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
import org.modelmapper.ModelMapper;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.validation.BindingResult;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.ModelAttribute;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
|
||||
import com.example.demo.core.configuration.Constants;
|
||||
import com.example.demo.users.model.UserEntity;
|
||||
import com.example.demo.users.service.UserService;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
|
||||
@Controller
|
||||
@RequestMapping(UserSignupController.URL)
|
||||
public class UserSignupController {
|
||||
public static final String URL = "/signup";
|
||||
|
||||
private static final String SIGNUP_VIEW = "signup";
|
||||
private static final String USER_ATTRIBUTE = "user";
|
||||
|
||||
private final UserService userService;
|
||||
private final ModelMapper modelMapper;
|
||||
|
||||
public UserSignupController(
|
||||
UserService userService,
|
||||
ModelMapper modelMapper) {
|
||||
this.userService = userService;
|
||||
this.modelMapper = modelMapper;
|
||||
}
|
||||
|
||||
private UserEntity toEntity(UserSignupDto dto) {
|
||||
return modelMapper.map(dto, UserEntity.class);
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public String getSignup(Model model) {
|
||||
model.addAttribute(USER_ATTRIBUTE, new UserSignupDto());
|
||||
return SIGNUP_VIEW;
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public String signup(
|
||||
@ModelAttribute(name = USER_ATTRIBUTE) @Valid UserSignupDto user,
|
||||
BindingResult bindingResult,
|
||||
Model model) {
|
||||
if (bindingResult.hasErrors()) {
|
||||
return SIGNUP_VIEW;
|
||||
}
|
||||
if (!Objects.equals(user.getPassword(), user.getPasswordConfirm())) {
|
||||
bindingResult.rejectValue("password", "signup:passwords", "Пароли не совпадают.");
|
||||
model.addAttribute(USER_ATTRIBUTE, user);
|
||||
return SIGNUP_VIEW;
|
||||
}
|
||||
userService.create(toEntity(user));
|
||||
return Constants.REDIRECT_VIEW + Constants.LOGIN_URL + "?signup";
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,40 @@
|
||||
package com.example.demo.users.api;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Size;
|
||||
|
||||
public class UserSignupDto {
|
||||
@NotBlank
|
||||
@Size(min = 3, max = 20)
|
||||
private String login;
|
||||
@NotBlank
|
||||
@Size(min = 3, max = 20)
|
||||
private String password;
|
||||
@NotBlank
|
||||
@Size(min = 3, max = 20)
|
||||
private String passwordConfirm;
|
||||
|
||||
public String getlogin() {
|
||||
return login;
|
||||
}
|
||||
|
||||
public void setlogin(String login) {
|
||||
this.login = login;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
public String getPasswordConfirm() {
|
||||
return passwordConfirm;
|
||||
}
|
||||
|
||||
public void setPasswordConfirm(String passwordConfirm) {
|
||||
this.passwordConfirm = passwordConfirm;
|
||||
}
|
||||
}
|
@ -0,0 +1,108 @@
|
||||
package com.example.demo.users.model;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
|
||||
import com.example.demo.news.model.NewsEntity;
|
||||
import com.example.demo.reviews.model.ReviewEntity;
|
||||
import com.example.demo.core.model.BaseEntity;
|
||||
import jakarta.persistence.CascadeType;
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.OneToMany;
|
||||
import jakarta.persistence.OrderBy;
|
||||
import jakarta.persistence.Table;
|
||||
|
||||
@Entity
|
||||
@Table(name = "users")
|
||||
public class UserEntity extends BaseEntity {
|
||||
@Column(nullable = false, unique = true, length = 20)
|
||||
private String login;
|
||||
@Column(nullable = false, length = 80)
|
||||
private String password;
|
||||
@Column(nullable = false)
|
||||
private UserRole role;
|
||||
// связь один ко многим с новостями
|
||||
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
|
||||
@OrderBy("id ASC")
|
||||
private Set<NewsEntity> news = new HashSet<>();
|
||||
|
||||
// связь один ко многим с отзывами
|
||||
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
|
||||
@OrderBy("id ASC")
|
||||
private Set<ReviewEntity> reviews = new HashSet<>();
|
||||
|
||||
public UserEntity() {
|
||||
}
|
||||
|
||||
public UserEntity(String login, String password) {
|
||||
this.login = login;
|
||||
this.password = password;
|
||||
this.role = UserRole.USER;
|
||||
}
|
||||
|
||||
public String getLogin() {
|
||||
return login;
|
||||
}
|
||||
|
||||
public void setLogin(String login) {
|
||||
this.login = login;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
public UserRole getRole() {
|
||||
return role;
|
||||
}
|
||||
|
||||
public void setRole(UserRole role) {
|
||||
this.role = role;
|
||||
}
|
||||
|
||||
public Set<NewsEntity> getNews() {
|
||||
return news;
|
||||
}
|
||||
|
||||
public Set<ReviewEntity> getReviews() {
|
||||
return reviews;
|
||||
}
|
||||
|
||||
public void addReview(ReviewEntity review) {
|
||||
if (review.getUser() != this) {
|
||||
review.setUser(this);
|
||||
}
|
||||
reviews.add(review);
|
||||
}
|
||||
|
||||
public void addNews(NewsEntity news) {
|
||||
if (news.getUser() != this) {
|
||||
news.setUser(this);
|
||||
}
|
||||
this.news.add(news);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(id, login, password, role);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null || getClass() != obj.getClass())
|
||||
return false;
|
||||
final UserEntity other = (UserEntity) obj;
|
||||
return Objects.equals(other.getId(), id)
|
||||
&& Objects.equals(other.getLogin(), login)
|
||||
&& Objects.equals(other.getPassword(), password)
|
||||
&& Objects.equals(other.getRole(), role);
|
||||
}
|
||||
}
|
@ -0,0 +1,15 @@
|
||||
package com.example.demo.users.model;
|
||||
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
|
||||
public enum UserRole implements GrantedAuthority {
|
||||
ADMIN,
|
||||
USER;
|
||||
|
||||
private static final String PREFIX = "ROLE_";
|
||||
|
||||
@Override
|
||||
public String getAuthority() {
|
||||
return PREFIX + this.name();
|
||||
}
|
||||
}
|
@ -0,0 +1,17 @@
|
||||
package com.example.demo.users.repository;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.data.repository.CrudRepository;
|
||||
import org.springframework.data.repository.PagingAndSortingRepository;
|
||||
|
||||
import com.example.demo.users.model.UserEntity;
|
||||
import com.example.demo.users.model.UserRole;
|
||||
|
||||
public interface UserRepository
|
||||
extends CrudRepository<UserEntity, Long>, PagingAndSortingRepository<UserEntity, Long> {
|
||||
Optional<UserEntity> findByLoginIgnoreCase(String login);
|
||||
|
||||
List<UserEntity> findByRole(UserRole role);
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user