This commit is contained in:
Sergey Kozyrev 2024-05-13 13:12:35 +04:00
commit 7a77cb66e0
72 changed files with 3955 additions and 0 deletions

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

12
.vscode/extensions.json vendored Normal file
View File

@ -0,0 +1,12 @@
{
"recommendations": [
// fronted
"AndersEAndersen.html-class-suggestions",
"dbaeumer.vscode-eslint",
// backend
"vscjava.vscode-java-pack",
"vmware.vscode-boot-dev-pack",
"vscjava.vscode-gradle",
"redhat.vscode-xml"
]
}

21
.vscode/launch.json vendored Normal file
View File

@ -0,0 +1,21 @@
{
"configurations": [
{
"type": "java",
"name": "DemoApplication",
"request": "launch",
"mainClass": "com.example.demo.DemoApplication",
"projectName": "lab45-my"
},
{
"type": "java",
"name": "Demo",
"request": "launch",
"cwd": "${workspaceFolder}",
"mainClass": "com.example.demo.DemoApplication",
"projectName": "lec6",
"args": "--populate",
"envFile": "${workspaceFolder}/.env"
}
]
}

24
.vscode/settings.json vendored Normal file
View File

@ -0,0 +1,24 @@
{
"editor.tabSize": 4,
"editor.detectIndentation": false,
"editor.insertSpaces": true,
"editor.formatOnPaste": true,
"editor.formatOnSave": true,
"editor.formatOnType": false,
"java.compile.nullAnalysis.mode": "disabled",
"java.configuration.updateBuildConfiguration": "automatic",
"[java]": {
"editor.pasteAs.enabled": false,
},
"gradle.nestedProjects": true,
"java.saveActions.organizeImports": true,
"java.dependency.packagePresentation": "hierarchical",
"spring-boot.ls.problem.boot2.JAVA_CONSTRUCTOR_PARAMETER_INJECTION": "WARNING",
"spring.initializr.defaultLanguage": "Java",
"java.format.settings.url": ".vscode/eclipse-formatter.xml",
"java.project.explorer.showNonJavaResources": true,
"java.codeGeneration.hashCodeEquals.useJava7Objects": true,
"cSpell.words": [
"classappend"
],
}

51
build.gradle Normal file
View File

@ -0,0 +1,51 @@
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
gradle/wrapper/gradle-wrapper.jar vendored Normal file

Binary file not shown.

View 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
gradlew vendored Normal file
View 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
gradlew.bat vendored Normal file
View 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
readme.md Normal file
View 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/

1
settings.gradle Normal file
View File

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

View File

@ -0,0 +1,48 @@
package com.example.demo;
import java.util.List;
import java.util.Objects;
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.users.service.UserService;
import com.example.demo.videos.service.VideoService;
import com.example.demo.users.model.UserEntity;
import com.example.demo.users.model.UserRole;
import com.example.demo.videos.model.VideoEntity;
import com.example.demo.core.configuration.Constants;
import com.example.demo.users.model.UserEntity;
@SpringBootApplication
public class DemoApplication implements CommandLineRunner {
private final Logger log = LoggerFactory.getLogger(DemoApplication.class);
private final UserService userService;
private final VideoService videoService;
public DemoApplication(UserService user, VideoService video) {
userService = user;
videoService = video;
}
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]) && false) {
final var user1 = userService.create(new UserEntity("login", "pass"));
final var user2 = userService.create(new UserEntity("aaa", "pass"));
user1.setRole(UserRole.ADMIN);
videoService.create(new VideoEntity(user1, "aboba", "boba", "oba", "ba"));
videoService.create(new VideoEntity(user2, "cicic", "icic", "ici", "i"));
}
}
}

View File

@ -0,0 +1,110 @@
package com.example.demo.comments.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.comments.model.CommentEntity;
import com.example.demo.comments.service.CommentService;
import com.example.demo.core.api.PageAttributesMapper;
import com.example.demo.core.configuration.Constants;
import com.example.demo.videos.service.VideoService;
import com.example.demo.users.service.UserService;
import jakarta.validation.Valid;
@Controller
@RequestMapping(CommentController.URL)
public class CommentController {
public static final String URL = Constants.ADMIN_PREFIX + "/comment";
private static final String COMMENT_VIEW = "comment";
private static final String COMMENT_EDIT_VIEW = "comment-edit-admin ";
private static final String PAGE_ATTRIBUTE = "page";
private static final String COMMENT_ATTRIBUTE = "comment";
private final CommentService commentService;
private final UserService userService;
private final VideoService videoService;
private final ModelMapper modelMapper;
public CommentController(CommentService comment, UserService user, VideoService video, ModelMapper model) {
commentService = comment;
userService = user;
videoService = video;
modelMapper = model;
}
private CommentDto toDto(CommentEntity entity) {
return modelMapper.map(entity, CommentDto.class);
}
private CommentEntity toEntity(CommentDto dto) {
final CommentEntity entity = modelMapper.map(dto, CommentEntity.class);
entity.setUser(userService.get(dto.getUserId()));
entity.setVideo(videoService.get(dto.getVideoId()));
return entity;
}
@GetMapping
public String getAll(@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
Model model) {
final Map<String, Object> attrib = PageAttributesMapper.toAttributes(
commentService.getAllByUser(0L, page, Constants.DEFUALT_PAGE_SIZE), this::toDto);
model.addAllAttributes(attrib);
model.addAttribute(PAGE_ATTRIBUTE, page);
return COMMENT_VIEW;
}
@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(COMMENT_ATTRIBUTE, toDto(commentService.get(id)));
model.addAttribute(PAGE_ATTRIBUTE, page);
return COMMENT_EDIT_VIEW;
}
@PostMapping("/edit/{id}")
public String update(
@PathVariable(name = "id") Long id,
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
@ModelAttribute(name = COMMENT_ATTRIBUTE) @Valid CommentDto comment,
BindingResult bindingResult,
Model model,
RedirectAttributes redirectAttributes) {
if (bindingResult.hasErrors()) {
model.addAttribute(PAGE_ATTRIBUTE, page);
return COMMENT_EDIT_VIEW;
}
if (id <= 0) {
throw new IllegalArgumentException();
}
redirectAttributes.addAttribute(PAGE_ATTRIBUTE, page);
commentService.update(id, toEntity(comment));
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);
commentService.delete(id);
return Constants.REDIRECT_VIEW + URL;
}
}

View File

@ -0,0 +1,51 @@
package com.example.demo.comments.api;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Min;
public class CommentDto {
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private Long id;
@NotNull
@Min(1)
private Long userId;
@NotNull
@Min(1)
private Long videoId;
@NotNull
private String text;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public Long getVideoId() {
return videoId;
}
public void setVideoId(Long videoId) {
this.videoId = videoId;
}
}

View File

@ -0,0 +1,79 @@
package com.example.demo.comments.model;
import java.util.Objects;
import com.example.demo.core.model.BaseEntity;
import com.example.demo.videos.model.VideoEntity;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.Table;
import com.example.demo.users.model.UserEntity;
@Entity
@Table(name = "comments")
public class CommentEntity extends BaseEntity {
@ManyToOne
@JoinColumn(name = "videoId")
private VideoEntity video;
@ManyToOne
@JoinColumn(name = "userId")
private UserEntity user;
@Column(nullable = false, length = 255)
private String text;
public CommentEntity() {
}
public CommentEntity(VideoEntity video, UserEntity user, String text) {
this.video = video;
this.user = user;
this.text = text;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public UserEntity getUser() {
return user;
}
public void setUser(UserEntity user) {
this.user = user;
}
public VideoEntity getVideo() {
return video;
}
public void setVideo(VideoEntity video) {
this.video = video;
}
@Override
public int hashCode() {
return Objects.hash(id, user, video, text);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null || getClass() != obj.getClass())
return false;
final CommentEntity other = (CommentEntity) obj;
return Objects.equals(other.getId(), getId())
&& Objects.equals(other.getUser(), getUser())
&& Objects.equals(other.getText(), getText())
&& Objects.equals(other.getVideo(), getVideo());
}
}

View File

@ -0,0 +1,19 @@
package com.example.demo.comments.repository;
import java.util.List;
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.comments.model.CommentEntity;
public interface CommentRepository
extends CrudRepository<CommentEntity, Long>, PagingAndSortingRepository<CommentEntity, Long> {
List<CommentEntity> findAllByVideoId(Long videoId);
Page<CommentEntity> findAllByUserId(Long userId, Pageable pageable);
Page<CommentEntity> findAllByVideoId(Long videoId, Pageable pageable);
}

View File

@ -0,0 +1,83 @@
package com.example.demo.comments.service;
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.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.example.demo.core.error.NotFoundException;
import com.example.demo.users.model.UserEntity;
import com.example.demo.users.service.UserService;
import com.example.demo.videos.model.VideoEntity;
import com.example.demo.videos.service.VideoService;
import com.example.demo.comments.model.CommentEntity;
import com.example.demo.comments.repository.CommentRepository;
@Service
public class CommentService {
private final CommentRepository repository;
private final UserService userService;
private final VideoService videoService;
public CommentService(CommentRepository repos, UserService user, VideoService video) {
repository = repos;
userService = user;
videoService = video;
}
public List<CommentEntity> getAll(Long videoId) {
if (Objects.equals(videoId, 0L)) {
return StreamSupport.stream(repository.findAll().spliterator(), false).toList();
}
return StreamSupport.stream(repository.findAllByVideoId(videoId).spliterator(), false).toList();
}
@Transactional(readOnly = true)
public Page<CommentEntity> getAllByUser(Long userId, int page, int size) {
if (!Objects.equals(userId, 0L)) {
return repository.findAllByUserId(userId, PageRequest.of(page, size, Sort.by("id")));
}
return repository.findAll(PageRequest.of(page, size, Sort.by("id")));
}
@Transactional(readOnly = true)
public Page<CommentEntity> getAllByVideo(Long videoId, int page, int size) {
if (!Objects.equals(videoId, 0L)) {
return repository.findAllByVideoId(videoId, PageRequest.of(page, size, Sort.by("id")));
}
return repository.findAll(PageRequest.of(page, size, Sort.by("id")));
}
public CommentEntity get(Long id) {
return repository.findById(id).orElseThrow(() -> new NotFoundException(CommentEntity.class, id));
}
public CommentEntity create(CommentEntity entity) {
if (entity == null) {
throw new IllegalArgumentException("Entity is null");
}
return repository.save(entity);
}
public CommentEntity update(Long id, CommentEntity entity) {
final CommentEntity existsEntity = get(id);
final VideoEntity video = videoService.get(entity.getVideo().getId());
final UserEntity user = userService.get(entity.getUser().getId());
existsEntity.setText(entity.getText());
existsEntity.setUser(user);
existsEntity.setVideo(video);
return repository.save(existsEntity);
}
public CommentEntity delete(Long id) {
final CommentEntity existsEntity = get(id);
repository.delete(existsEntity);
return existsEntity;
}
}

View File

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

View File

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

View File

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

View File

@ -0,0 +1,13 @@
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");
}
}

View File

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

View File

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

View File

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

View File

@ -0,0 +1,63 @@
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/**", "/webjars/**", "/*.svg")
.permitAll());
httpSecurity.authorizeHttpRequests(requests -> requests
.requestMatchers(Constants.ADMIN_PREFIX + "/**").hasRole(UserRole.ADMIN.name())
.requestMatchers("/h2-console/**").hasRole(UserRole.ADMIN.name())
.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();
}
@Bean
DaoAuthenticationProvider authenticationProvider(UserDetailsService userDetailsService) {
final DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
authProvider.setUserDetailsService(userDetailsService);
authProvider.setPasswordEncoder(passwordEncoder());
return authProvider;
}
@Bean
PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}

View File

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

View File

@ -0,0 +1,82 @@
package com.example.demo.likes.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.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.likes.model.LikeEntity;
import com.example.demo.likes.service.LikeService;
import com.example.demo.videos.service.VideoService;
import com.example.demo.users.service.UserService;
import jakarta.validation.Valid;
@RestController
@RequestMapping("/like")
public class LikeController {
private final LikeService likeService;
private final UserService userService;
private final VideoService videoService;
private final ModelMapper modelMapper;
public LikeController(LikeService like, UserService user, VideoService video, ModelMapper model) {
likeService = like;
userService = user;
videoService = video;
modelMapper = model;
}
private LikeDto toDto(LikeEntity entity) {
return modelMapper.map(entity, LikeDto.class);
}
private LikeEntity toEntity(LikeDto dto) {
final LikeEntity entity = modelMapper.map(dto, LikeEntity.class);
entity.setUser(userService.get(dto.getUserId()));
entity.setVideo(videoService.get(dto.getVideoId()));
return entity;
}
@GetMapping
public List<LikeDto> getAll() {
return likeService.getAll(0L).stream().map(this::toDto).toList();
}
@GetMapping("/user/{userId}")
public List<LikeDto> getAllByUser(@PathVariable(name = "userId") Long userId) {
return likeService.getAllByUser(userId).stream().map(this::toDto).toList();
}
@GetMapping("/video/{videoId}")
public List<LikeDto> getAllByVideo(@PathVariable(name = "videoId") Long videoId) {
return likeService.getAll(videoId).stream().map(this::toDto).toList();
}
@GetMapping("/{id}")
public LikeDto get(@PathVariable(name = "id") Long id) {
return toDto(likeService.get(id));
}
@PostMapping
public LikeDto create(@RequestBody @Valid LikeDto dto) {
return toDto(likeService.create(toEntity(dto)));
}
@DeleteMapping("/{id}")
public LikeDto delete(@PathVariable(name = "id") Long id) {
return toDto(likeService.delete(id));
}
@DeleteMapping("/{userId}/{videoId}")
public void deleteVideoUser(@PathVariable(name = "userId") Long userId,
@PathVariable(name = "videoId") Long videoId) {
likeService.deleteByUserIdAndVideoId(userId, videoId);
}
}

View File

@ -0,0 +1,41 @@
package com.example.demo.likes.api;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Min;
public class LikeDto {
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private Long id;
@NotNull
@Min(1)
private Long userId;
@NotNull
@Min(1)
private Long videoId;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public Long getVideoId() {
return videoId;
}
public void setVideoId(Long videoId) {
this.videoId = videoId;
}
}

View File

@ -0,0 +1,66 @@
package com.example.demo.likes.model;
import java.util.Objects;
import com.example.demo.core.model.BaseEntity;
import com.example.demo.videos.model.VideoEntity;
import jakarta.persistence.Entity;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.Table;
import com.example.demo.users.model.UserEntity;
@Entity
@Table(name = "likes")
public class LikeEntity extends BaseEntity {
@ManyToOne
@JoinColumn(name = "videoId")
private VideoEntity video;
@ManyToOne
@JoinColumn(name = "userId")
private UserEntity user;
public LikeEntity() {
}
public LikeEntity(VideoEntity video, UserEntity user) {
this.video = video;
this.user = user;
}
public UserEntity getUser() {
return user;
}
public void setUser(UserEntity user) {
this.user = user;
}
public VideoEntity getVideo() {
return video;
}
public void setVideo(VideoEntity video) {
this.video = video;
}
@Override
public int hashCode() {
return Objects.hash(id, user, video);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null || getClass() != obj.getClass())
return false;
final LikeEntity other = (LikeEntity) obj;
return Objects.equals(other.getId(), getId())
&& Objects.equals(other.getUser(), getUser())
&& Objects.equals(other.getVideo(), getVideo());
}
}

View File

@ -0,0 +1,33 @@
package com.example.demo.likes.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.jpa.repository.Modifying;
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 org.springframework.transaction.annotation.Transactional;
import com.example.demo.likes.model.LikeEntity;
public interface LikeRepository extends CrudRepository<LikeEntity, Long>,
PagingAndSortingRepository<LikeEntity, Long> {
List<LikeEntity> findAllByUserId(Long userId);
Page<LikeEntity> findAllByUserId(Long userId, Pageable pageable);
@Transactional
@Modifying
@Query("DELETE FROM LikeEntity l WHERE l.user.id = :userId AND l.video.id = :videoId")
void deleteByUserIdAndVideoId(@Param("userId") Long userId, @Param("videoId") Long videoId);
List<LikeEntity> findAllByVideoId(Long videoId);
Page<LikeEntity> findAllByVideoId(Long videoId, Pageable pageable);
Optional<LikeEntity> findByUserIdAndVideoId(Long userId, Long videoId);
}

View File

@ -0,0 +1,70 @@
package com.example.demo.likes.service;
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.Sort;
import org.springframework.stereotype.Service;
import com.example.demo.core.error.NotFoundException;
import com.example.demo.likes.model.LikeEntity;
import com.example.demo.likes.repository.LikeRepository;
@Service
public class LikeService {
private final LikeRepository repository;
public LikeService(LikeRepository repos) {
repository = repos;
}
public List<LikeEntity> getAll(Long videoId) {
if (Objects.equals(videoId, 0L)) {
return StreamSupport.stream(repository.findAll().spliterator(), false).toList();
}
return StreamSupport.stream(repository.findAllByVideoId(videoId).spliterator(), false).toList();
}
public List<LikeEntity> getAllByUser(Long userId) {
return StreamSupport.stream(repository.findAllByUserId(userId).spliterator(), false).toList();
}
public Page<LikeEntity> getAll(Long videoId, int page, int size) {
if (Objects.equals(videoId, 0L)) {
return repository.findAll(PageRequest.of(page, size, Sort.by("id")));
}
return repository.findAllByVideoId(videoId, PageRequest.of(page, size, Sort.by("id")));
}
public Page<LikeEntity> getAllByUser(Long userId, int page, int size) {
return repository.findAllByUserId(userId, PageRequest.of(page, size, Sort.by("id")));
}
public LikeEntity get(Long id) {
return repository.findById(id).orElseThrow(() -> new NotFoundException(LikeEntity.class, id));
}
public LikeEntity create(LikeEntity entity) {
if (entity == null) {
throw new IllegalArgumentException("Entity is null");
}
return repository.save(entity);
}
public LikeEntity delete(Long id) {
final LikeEntity existsEntity = get(id);
repository.delete(existsEntity);
return existsEntity;
}
public void deleteByUserIdAndVideoId(Long userId, Long videoId) {
repository.deleteByUserIdAndVideoId(userId, videoId);
}
public boolean findByUserIdAndVideoId(Long userId, Long videoId) {
return repository.findByUserIdAndVideoId(userId, videoId).isPresent();
}
}

View File

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

View File

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

View File

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

View File

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

View File

@ -0,0 +1,69 @@
package com.example.demo.users.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 = "users")
public class UserEntity extends BaseEntity {
@Column(nullable = false, unique = true, length = 20)
private String login;
@Column(nullable = false, length = 60)
private String password;
private UserRole role;
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;
}
@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;
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);
}
}

View File

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

View File

@ -0,0 +1,13 @@
package com.example.demo.users.repository;
import java.util.Optional;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.PagingAndSortingRepository;
import com.example.demo.users.model.UserEntity;
public interface UserRepository
extends CrudRepository<UserEntity, Long>, PagingAndSortingRepository<UserEntity, Long> {
Optional<UserEntity> findByLoginIgnoreCase(String login);
}

View File

@ -0,0 +1,113 @@
package com.example.demo.users.service;
import java.util.List;
import java.util.Optional;
import java.util.stream.StreamSupport;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import com.example.demo.core.configuration.Constants;
import com.example.demo.core.error.NotFoundException;
import com.example.demo.core.security.UserPrincipal;
import com.example.demo.users.model.UserEntity;
import com.example.demo.users.model.UserRole;
import com.example.demo.users.repository.UserRepository;
@Service
public class UserService implements UserDetailsService {
private final UserRepository repository;
private final PasswordEncoder passwordEncoder;
public UserService(
UserRepository repository,
PasswordEncoder passwordEncoder) {
this.repository = repository;
this.passwordEncoder = passwordEncoder;
}
private void checkLogin(Long id, String login) {
final Optional<UserEntity> existsUser = repository.findByLoginIgnoreCase(login);
if (existsUser.isPresent() && !existsUser.get().getId().equals(id)) {
throw new IllegalArgumentException(
String.format("User with login %s is already exists", login));
}
}
@Transactional(readOnly = true)
public List<UserEntity> getAll() {
return StreamSupport.stream(repository.findAll().spliterator(), false).toList();
}
@Transactional(readOnly = true)
public Page<UserEntity> getAll(int page, int size) {
return repository.findAll(PageRequest.of(page, size, Sort.by("id")));
}
@Transactional(readOnly = true)
public UserEntity get(long id) {
return repository.findById(id)
.orElseThrow(() -> new NotFoundException(UserEntity.class, id));
}
@Transactional(readOnly = true)
public UserEntity getByLogin(String login) {
return repository.findByLoginIgnoreCase(login)
.orElseThrow(() -> new IllegalArgumentException("Invalid login"));
}
@Transactional
public UserEntity create(UserEntity entity) {
if (entity == null) {
throw new IllegalArgumentException("Entity is null");
}
checkLogin(null, entity.getLogin());
final String password = Optional.ofNullable(entity.getPassword()).orElse("");
entity.setPassword(
passwordEncoder.encode(
StringUtils.hasText(password.strip()) ? password : Constants.DEFAULT_PASSWORD));
entity.setRole(Optional.ofNullable(entity.getRole()).orElse(UserRole.USER));
return repository.save(entity);
}
@Transactional
public UserEntity update(long id, UserEntity entity) {
final UserEntity existsEntity = get(id);
checkLogin(id, entity.getLogin());
existsEntity.setLogin(entity.getLogin());
repository.save(existsEntity);
return existsEntity;
}
@Transactional
public UserEntity delete(long id) {
final UserEntity existsEntity = get(id);
repository.delete(existsEntity);
return existsEntity;
}
@Override
@Transactional(readOnly = true)
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
final UserEntity existsUser = getByLogin(username);
return new UserPrincipal(existsUser);
}
public Long getUserIdLong() {
Authentication aut = SecurityContextHolder.getContext().getAuthentication();
if (aut != null && aut.getPrincipal() instanceof UserDetails) {
return ((UserPrincipal) aut.getPrincipal()).getId();
}
return null;
}
}

View File

@ -0,0 +1,108 @@
package com.example.demo.videos.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.videos.model.VideoEntity;
import com.example.demo.videos.service.VideoService;
import com.example.demo.users.service.UserService;
import jakarta.validation.Valid;
@Controller
@RequestMapping(VideoAdminController.URL)
public class VideoAdminController {
public static final String URL = Constants.ADMIN_PREFIX + "/video";
private static final String VIDEO_VIEW = "video";
private static final String VIDEO_EDIT_VIEW = "video-edit";
private static final String VIDEO_ATTRIBUTE = "video";
private static final String PAGE_ATTRIBUTE = "page";
private final UserService userService;
private final VideoService videoService;
private final ModelMapper modelMapper;
public VideoAdminController(UserService user, VideoService video, ModelMapper model) {
userService = user;
videoService = video;
modelMapper = model;
}
private VideoDto toDto(VideoEntity entity) {
return modelMapper.map(entity, VideoDto.class);
}
private VideoEntity toEntity(VideoDto dto) {
final VideoEntity entity = modelMapper.map(dto, VideoEntity.class);
entity.setUser(userService.get(dto.getUserId()));
return entity;
}
@GetMapping
public String getAll(
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
Model model) {
final Map<String, Object> attrib = PageAttributesMapper.toAttributes(
videoService.getAll(0L, page, Constants.DEFUALT_PAGE_SIZE), this::toDto);
model.addAllAttributes(attrib);
model.addAttribute(PAGE_ATTRIBUTE, page);
return VIDEO_VIEW;
}
@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(VIDEO_ATTRIBUTE, toDto(videoService.get(id)));
model.addAttribute(PAGE_ATTRIBUTE, page);
return VIDEO_EDIT_VIEW;
}
@PostMapping("/edit/{id}")
public String update(
@PathVariable(name = "id") Long id,
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
@ModelAttribute(name = VIDEO_ATTRIBUTE) @Valid VideoDto video,
BindingResult bindingResult,
Model model,
RedirectAttributes redirectAttributes) {
if (bindingResult.hasErrors()) {
model.addAttribute(PAGE_ATTRIBUTE, page);
return VIDEO_EDIT_VIEW;
}
if (id <= 0) {
throw new IllegalArgumentException();
}
redirectAttributes.addAttribute(PAGE_ATTRIBUTE, page);
videoService.update(id, toEntity(video));
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);
videoService.delete(id);
return Constants.REDIRECT_VIEW + URL;
}
}

View File

@ -0,0 +1,68 @@
package com.example.demo.videos.api;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;
public class VideoDto {
private Long id;
@NotNull
@Min(1)
private Long userId;
@NotNull
private String title;
@NotNull
private String description;
@NotNull
private String image;
@NotNull
private String vid;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getVid() {
return vid;
}
public void setVid(String vid) {
this.vid = vid;
}
}

View File

@ -0,0 +1,14 @@
package com.example.demo.videos.api;
public class VideoDtoLike extends VideoDto {
private Boolean isLiked;
public Boolean getIsLiked() {
return isLiked;
}
public void setIsLiked(Boolean isLiked) {
this.isLiked = isLiked;
}
}

View File

@ -0,0 +1,85 @@
package com.example.demo.videos.api;
import java.util.Map;
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.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.example.demo.comments.api.CommentDto;
import com.example.demo.comments.model.CommentEntity;
import com.example.demo.comments.service.CommentService;
import com.example.demo.core.api.PageAttributesMapper;
import com.example.demo.core.configuration.Constants;
import com.example.demo.likes.service.LikeService;
import com.example.demo.users.service.UserService;
import com.example.demo.videos.model.VideoEntity;
import com.example.demo.videos.service.VideoService;
@Controller
@RequestMapping(VideoListController.URL)
public class VideoListController {
public static final String URL = "/list";
private static final String VIDEO_VIEW = "video";
private static final String PAGE_ATTRIBUTE = "page";
private static final String COMMENT_VIEW = "comment";
private final VideoService videoService;
private final UserService userService;
private final ModelMapper modelMapper;
private final CommentService commentService;
private final LikeService likeService;
public VideoListController(VideoService video, ModelMapper model, CommentService comment, LikeService like,
UserService user) {
videoService = video;
modelMapper = model;
commentService = comment;
likeService = like;
userService = user;
}
private VideoDtoLike toDto(VideoEntity entity) {
final Long userId = userService.getUserIdLong();
final VideoDtoLike dto = new VideoDtoLike();
dto.setDescription(entity.getDescription());
dto.setImage(entity.getImage());
dto.setTitle(entity.getTitle());
dto.setUserId(entity.getUser().getId());
dto.setVid(entity.getVid());
dto.setId(entity.getId());
boolean flag = likeService.findByUserIdAndVideoId(userId, entity.getId());
dto.setIsLiked(flag);
return dto;
}
private CommentDto toDto(CommentEntity entity) {
return modelMapper.map(entity, CommentDto.class);
}
@GetMapping("/video")
public String getAll(
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
Model model) {
final Map<String, Object> attrib = PageAttributesMapper.toAttributes(
videoService.getAll(0L, page, Constants.DEFUALT_PAGE_SIZE), this::toDto);
model.addAllAttributes(attrib);
model.addAttribute(PAGE_ATTRIBUTE, page);
return VIDEO_VIEW;
}
@GetMapping("/comment/{videoId}")
public String getAllComments(@PathVariable(name = "videoId") Long videoId,
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
Model model) {
final Map<String, Object> attrib = PageAttributesMapper
.toAttributes(commentService.getAllByVideo(videoId, page, Constants.DEFUALT_PAGE_SIZE), this::toDto);
model.addAllAttributes(attrib);
model.addAttribute(PAGE_ATTRIBUTE, page);
return COMMENT_VIEW;
}
}

View File

@ -0,0 +1,304 @@
package com.example.demo.videos.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.comments.api.CommentDto;
import com.example.demo.comments.model.CommentEntity;
import com.example.demo.comments.service.CommentService;
import com.example.demo.core.api.PageAttributesMapper;
import com.example.demo.core.configuration.Constants;
import com.example.demo.likes.api.LikeDto;
import com.example.demo.likes.model.LikeEntity;
import com.example.demo.likes.service.LikeService;
import com.example.demo.videos.model.VideoEntity;
import com.example.demo.videos.service.VideoService;
import com.example.demo.users.service.UserService;
import jakarta.validation.Valid;
@Controller
@RequestMapping(VideoUserController.URL)
public class VideoUserController {
public static final String URL = "/video";
private static final String VIDEO_VIEW = "user-video";
private static final String VIDEO_EDIT_VIEW = "video-edit";
private static final String PAGE_ATTRIBUTE = "page";
private static final String VIDEO_ATTRIBUTE = "video";
private static final String LIKE_VIEW = "video-like";
private static final String COMMENT_VIEW = "comment-user";
private static final String COMMENT_EDIT_VIEW = "comment-edit-user";
private static final String COMMENT_ATTRIBUTE = "comment";
private static final String COMMENT_ADD_VIEW = "comment-edit-add";
private final UserService userService;
private final VideoService videoService;
private final ModelMapper modelMapper;
private final LikeService likeService;
private final CommentService commentService;
public VideoUserController(UserService user, VideoService video, ModelMapper model, LikeService like,
CommentService comment) {
userService = user;
videoService = video;
modelMapper = model;
likeService = like;
commentService = comment;
}
private VideoDto toDto(VideoEntity entity) {
return modelMapper.map(entity, VideoDto.class);
}
private LikeDto toDto(LikeEntity entity) {
return modelMapper.map(entity, LikeDto.class);
}
private CommentDto toDto(CommentEntity entity) {
return modelMapper.map(entity, CommentDto.class);
}
private VideoEntity toEntity(VideoDto dto) {
final VideoEntity entity = modelMapper.map(dto, VideoEntity.class);
entity.setUser(userService.get(dto.getUserId()));
return entity;
}
private CommentEntity toEntity(CommentDto dto) {
final CommentEntity entity = modelMapper.map(dto, CommentEntity.class);
entity.setUser(userService.get(dto.getUserId()));
entity.setVideo(videoService.get(dto.getVideoId()));
return entity;
}
private LikeEntity toEntity(LikeDto dto) {
final LikeEntity entity = modelMapper.map(dto, LikeEntity.class);
entity.setUser(userService.get(dto.getUserId()));
entity.setVideo(videoService.get(dto.getVideoId()));
return entity;
}
@GetMapping
public String getAll(
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
Model model) {
final Long userId = userService.getUserIdLong();
final Map<String, Object> attrib = PageAttributesMapper.toAttributes(
videoService.getAll(userId, page, Constants.DEFUALT_PAGE_SIZE), this::toDto);
model.addAllAttributes(attrib);
model.addAttribute(PAGE_ATTRIBUTE, page);
return VIDEO_VIEW;
}
@GetMapping("/edit/")
public String create(@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
Model model) {
final VideoDto dto = new VideoDto();
dto.setUserId(userService.getUserIdLong());
model.addAttribute(VIDEO_ATTRIBUTE, dto);
model.addAttribute(PAGE_ATTRIBUTE, page);
return VIDEO_EDIT_VIEW;
}
@PostMapping("/edit/")
public String create(
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
@ModelAttribute(name = VIDEO_ATTRIBUTE) @Valid VideoDto video,
BindingResult bindingResult,
Model model,
RedirectAttributes redirectAttributes) {
if (bindingResult.hasErrors()) {
model.addAttribute(PAGE_ATTRIBUTE, page);
return VIDEO_EDIT_VIEW;
}
redirectAttributes.addAttribute(PAGE_ATTRIBUTE, page);
videoService.create(toEntity(video));
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(VIDEO_ATTRIBUTE, toDto(videoService.get(id)));
model.addAttribute(PAGE_ATTRIBUTE, page);
return VIDEO_EDIT_VIEW;
}
@PostMapping("/edit/{id}")
public String update(
@PathVariable(name = "id") Long id,
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
@ModelAttribute(name = VIDEO_ATTRIBUTE) @Valid VideoDto video,
BindingResult bindingResult,
Model model,
RedirectAttributes redirectAttributes) {
if (bindingResult.hasErrors()) {
model.addAttribute(PAGE_ATTRIBUTE, page);
return VIDEO_EDIT_VIEW;
}
if (id <= 0) {
throw new IllegalArgumentException();
}
redirectAttributes.addAttribute(PAGE_ATTRIBUTE, page);
videoService.update(id, toEntity(video));
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);
videoService.delete(id);
return Constants.REDIRECT_VIEW + URL;
}
@GetMapping("/title/{id}")
public String getName(@PathVariable(name = "id") Long id) {
final VideoEntity video = videoService.get(id);
return video.getTitle();
}
@GetMapping("/comment")
public String getComments(@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
Model model) {
final Long id = userService.getUserIdLong();
final Map<String, Object> attrib = PageAttributesMapper.toAttributes(
commentService.getAllByUser(id, page, Constants.DEFUALT_PAGE_SIZE), this::toDto);
model.addAllAttributes(attrib);
model.addAttribute(PAGE_ATTRIBUTE, page);
return COMMENT_VIEW;
}
@GetMapping("/comment/edit/add/{videoId}")
public String createComment(@PathVariable(name = "videoId") Long videoId,
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
Model model) {
final CommentDto dto = new CommentDto();
dto.setUserId(userService.getUserIdLong());
dto.setVideoId(videoId);
model.addAttribute(COMMENT_ATTRIBUTE, dto);
model.addAttribute(PAGE_ATTRIBUTE, page);
return COMMENT_ADD_VIEW;
}
@PostMapping("/comment/edit/add")
public String createComment(
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
@ModelAttribute(name = VIDEO_ATTRIBUTE) @Valid CommentDto comment,
BindingResult bindingResult,
Model model,
RedirectAttributes redirectAttributes) {
if (bindingResult.hasErrors()) {
model.addAttribute(PAGE_ATTRIBUTE, page);
return COMMENT_ADD_VIEW;
}
redirectAttributes.addAttribute(PAGE_ATTRIBUTE, page);
commentService.create(toEntity(comment));
return Constants.REDIRECT_VIEW + "/list/video";
}
@GetMapping("/comment/edit/{id}")
public String updateComment(
@PathVariable(name = "id") Long id,
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
Model model) {
if (id <= 0) {
throw new IllegalArgumentException();
}
model.addAttribute(COMMENT_ATTRIBUTE, toDto(commentService.get(id)));
model.addAttribute(PAGE_ATTRIBUTE, page);
return COMMENT_EDIT_VIEW;
}
@PostMapping("/comment/edit/{id}")
public String updateComment(@PathVariable(name = "id") Long id,
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
@ModelAttribute(name = VIDEO_ATTRIBUTE) @Valid CommentDto comment,
BindingResult bindingResult,
Model model,
RedirectAttributes redirectAttributes) {
if (bindingResult.hasErrors()) {
model.addAttribute(PAGE_ATTRIBUTE, page);
return VIDEO_EDIT_VIEW;
}
if (id <= 0) {
throw new IllegalArgumentException();
}
redirectAttributes.addAttribute(PAGE_ATTRIBUTE, page);
commentService.update(id, toEntity(comment));
return Constants.REDIRECT_VIEW + URL + "/comment";
}
@PostMapping("/comment/delete/{id}")
public String deleteComment(@PathVariable(name = "id") Long id,
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
RedirectAttributes redirectAttributes) {
redirectAttributes.addAttribute(PAGE_ATTRIBUTE, page);
commentService.delete(id);
return Constants.REDIRECT_VIEW + URL + "/comment";
}
@GetMapping("/like")
public String getLikes(@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
Model model) {
final Long id = userService.getUserIdLong();
final Map<String, Object> attrib = PageAttributesMapper.toAttributes(
likeService.getAllByUser(id, page, Constants.DEFUALT_PAGE_SIZE), this::toDto);
model.addAllAttributes(attrib);
model.addAttribute(PAGE_ATTRIBUTE, page);
return LIKE_VIEW;
}
@PostMapping("/like/{videoId}")
public String addLike(@PathVariable(name = "videoId") Long videoId,
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
RedirectAttributes redirectAttributes) {
final Long userid = userService.getUserIdLong();
final LikeDto dto = new LikeDto();
dto.setUserId(userid);
dto.setVideoId(videoId);
likeService.create(toEntity(dto));
redirectAttributes.addAttribute(PAGE_ATTRIBUTE, page);
return Constants.REDIRECT_VIEW + "/list/video";
}
@PostMapping("/dislike1/{id}")
public String deleteLike1(@PathVariable(name = "id") Long id,
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
RedirectAttributes redirectAttributes) {
redirectAttributes.addAttribute(PAGE_ATTRIBUTE, page);
final Long userid = userService.getUserIdLong();
likeService.deleteByUserIdAndVideoId(userid, id);
return Constants.REDIRECT_VIEW + "/list/video";
}
@PostMapping("/dislike2/{id}")
public String deleteLike2(@PathVariable(name = "id") Long id,
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
RedirectAttributes redirectAttributes) {
redirectAttributes.addAttribute(PAGE_ATTRIBUTE, page);
final Long userid = userService.getUserIdLong();
likeService.deleteByUserIdAndVideoId(userid, id);
return Constants.REDIRECT_VIEW + URL + "/like";
}
}

View File

@ -0,0 +1,99 @@
package com.example.demo.videos.model;
import java.util.Objects;
import com.example.demo.core.model.BaseEntity;
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 = "videos")
public class VideoEntity extends BaseEntity {
@ManyToOne
@JoinColumn(name = "userId")
private UserEntity user;
@Column(nullable = false, length = 30)
private String title;
@Column(nullable = false, length = 30)
private String description;
@Column(nullable = false, length = 30)
private String image;
@Column(nullable = false, length = 30)
private String vid;
public VideoEntity() {
}
public VideoEntity(UserEntity user, String title, String description, String image, String vid) {
this.title = title;
this.user = user;
this.description = description;
this.image = image;
this.vid = vid;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public UserEntity getUser() {
return user;
}
public void setUser(UserEntity user) {
this.user = user;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getVid() {
return vid;
}
public void setVid(String vid) {
this.vid = vid;
}
@Override
public int hashCode() {
return Objects.hash(id, user, title, description, image, vid);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null || getClass() != obj.getClass())
return false;
final VideoEntity other = (VideoEntity) obj;
return Objects.equals(other.getId(), getId())
&& Objects.equals(other.getUser(), getUser())
&& Objects.equals(other.getTitle(), getTitle())
&& Objects.equals(other.getDescription(), getDescription())
&& Objects.equals(other.getImage(), getImage())
&& Objects.equals(other.getVid(), getVid());
}
}

View File

@ -0,0 +1,17 @@
package com.example.demo.videos.repository;
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.videos.model.VideoEntity;
import java.util.List;
public interface VideoRepository
extends CrudRepository<VideoEntity, Long>, PagingAndSortingRepository<VideoEntity, Long> {
List<VideoEntity> findByUserId(Long userId);
Page<VideoEntity> findByUserId(Long userId, Pageable pageable);
}

View File

@ -0,0 +1,72 @@
package com.example.demo.videos.service;
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.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.example.demo.core.error.NotFoundException;
import com.example.demo.videos.model.VideoEntity;
import com.example.demo.videos.repository.VideoRepository;
@Service
public class VideoService {
private final VideoRepository repository;
public VideoService(VideoRepository repository) {
this.repository = repository;
}
@Transactional(readOnly = true)
public List<VideoEntity> getAll(Long userId) {
if (Objects.equals(userId, 0L)) {
return StreamSupport.stream(repository.findAll().spliterator(), false).toList();
}
return StreamSupport.stream(repository.findByUserId(userId).spliterator(), false).toList();
}
@Transactional(readOnly = true)
public Page<VideoEntity> getAll(Long userId, int page, int size) {
if (!Objects.equals(userId, 0L)) {
return repository.findByUserId(userId, PageRequest.of(page, size, Sort.by("id")));
}
return repository.findAll(PageRequest.of(page, size, Sort.by("id")));
}
@Transactional(readOnly = true)
public VideoEntity get(Long id) {
return repository.findById(id).orElseThrow(() -> new NotFoundException(VideoEntity.class, id));
}
@Transactional
public VideoEntity create(VideoEntity entity) {
if (entity == null) {
throw new IllegalArgumentException("Entity is null");
}
return repository.save(entity);
}
@Transactional
public VideoEntity update(Long id, VideoEntity entity) {
final VideoEntity existsEntity = get(id);
existsEntity.setUser(entity.getUser());
existsEntity.setImage(entity.getImage());
existsEntity.setDescription(entity.getDescription());
existsEntity.setTitle(entity.getTitle());
existsEntity.setVid(entity.getVid());
return repository.save(existsEntity);
}
@Transactional
public VideoEntity delete(Long id) {
final VideoEntity existsEntity = get(id);
repository.delete(existsEntity);
return existsEntity;
}
}

View File

@ -0,0 +1,20 @@
# Server
spring.main.banner-mode=off
server.port=8080
# Logger settings
# Available levels are: TRACE, DEBUG, INFO, WARN, ERROR, FATAL, OFF
logging.level.com.example.demo=DEBUG
# JPA Settings
spring.datasource.url=jdbc:h2:file:./data
spring.datasource.username=sa
spring.datasource.password=password
spring.datasource.driver-class-name=org.h2.Driver
spring.jpa.hibernate.ddl-auto=update
spring.jpa.open-in-view=false
# spring.jpa.show-sql=true
# spring.jpa.properties.hibernate.format_sql=true
# H2 console
spring.h2.console.enabled=true

View File

@ -0,0 +1,67 @@
html,
body {
height: 100%;
}
h1 {
font-size: 1.5em;
}
h2 {
font-size: 1.25em;
}
h3 {
font-size: 1.1em;
}
td form {
margin: 0;
padding: 0;
margin-top: -.25em;
}
.button-fixed-width {
width: 150px;
}
.button-link {
padding: 0;
}
.invalid-feedback {
display: block;
}
.w-10 {
width: 10% !important;
}
.my-navbar {
background-color: #3c3c3c !important;
}
.my-navbar .link a:hover {
text-decoration: underline;
}
.my-navbar .logo {
width: 26px;
height: 26px;
}
.my-footer {
background-color: #2c2c2c;
height: 32px;
color: rgba(255, 255, 255, 0.5);
}
.cart-image {
width: 3.1rem;
padding: 0.25rem;
border-radius: 0.5rem;
}
.cart-item {
height: auto;
}

View File

@ -0,0 +1,37 @@
<!DOCTYPE html>
<html lang="ru" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}">
<head>
<title>Редактировать текст комментария</title>
</head>
<body>
<main layout:fragment="content">
<form action="#" th:action="@{/video/comment/edit/add}" th:object="${comment}" method="post">
<div class="mb-3">
<label for="id" class="form-label">ID</label>
<input type="text" th:value="*{id}" id="id" class="form-control" readonly disabled>
</div>
<div class="mb-3">
<label for="userId" class="form-label">ID пользователя</label>
<input type="number" th:field="*{userId}" id="userId" class="form-control" readonly>
</div>
<div class="mb-3">
<label for="userId" class="form-label">ID видео</label>
<input type="number" th:field="*{videoId}" id="videoId" class="form-control" readonly>
</div>
<div class="mb-3">
<label for="name" class="form-label">Текст комментария</label>
<input type="text" th:field="*{text}" id="text" class="form-control">
<div th:if="${#fields.hasErrors('text')}" th:errors="*{text}" class="invalid-feedback"></div>
</div>
<div class="mb-3 d-flex flex-row">
<button class="btn btn-primary me-2 button-fixed-width" type="submit">Сохранить</button>
<a class="btn btn-secondary button-fixed-width" href="/video">Отмена</a>
</div>
</form>
</main>
</body>
</html>

View File

@ -0,0 +1,37 @@
<!DOCTYPE html>
<html lang="ru" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}">
<head>
<title>Редактировать текст комментария</title>
</head>
<body>
<main layout:fragment="content">
<form action="#" th:action="@{admin/comment/edit/{id}(id=${comment.id})}" th:object="${comment}" method="post">
<div class="mb-3">
<label for="id" class="form-label">ID</label>
<input type="text" th:value="*{id}" id="id" class="form-control" readonly disabled>
</div>
<div class="mb-3">
<label for="userId" class="form-label">ID пользователя</label>
<input type="number" th:field="*{userId}" id="userId" class="form-control" readonly>
</div>
<div class="mb-3">
<label for="userId" class="form-label">ID видео</label>
<input type="number" th:field="*{videoId}" id="videoId" class="form-control" readonly>
</div>
<div class="mb-3">
<label for="name" class="form-label">Текст комментария</label>
<input type="text" th:field="*{text}" id="text" class="form-control">
<div th:if="${#fields.hasErrors('text')}" th:errors="*{text}" class="invalid-feedback"></div>
</div>
<div class="mb-3 d-flex flex-row">
<button class="btn btn-primary me-2 button-fixed-width" type="submit">Сохранить</button>
<a class="btn btn-secondary button-fixed-width" href="/video">Отмена</a>
</div>
</form>
</main>
</body>
</html>

View File

@ -0,0 +1,37 @@
<!DOCTYPE html>
<html lang="ru" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}">
<head>
<title>Редактировать текст комментария</title>
</head>
<body>
<main layout:fragment="content">
<form action="#" th:action="@{/video/comment/edit/{id}(id=${comment.id})}" th:object="${comment}" method="post">
<div class="mb-3">
<label for="id" class="form-label">ID</label>
<input type="text" th:value="*{id}" id="id" class="form-control" readonly disabled>
</div>
<div class="mb-3">
<label for="userId" class="form-label">ID пользователя</label>
<input type="number" th:field="*{userId}" id="userId" class="form-control" readonly>
</div>
<div class="mb-3">
<label for="userId" class="form-label">ID видео</label>
<input type="number" th:field="*{videoId}" id="videoId" class="form-control" readonly>
</div>
<div class="mb-3">
<label for="name" class="form-label">Текст комментария</label>
<input type="text" th:field="*{text}" id="text" class="form-control">
<div th:if="${#fields.hasErrors('text')}" th:errors="*{text}" class="invalid-feedback"></div>
</div>
<div class="mb-3 d-flex flex-row">
<button class="btn btn-primary me-2 button-fixed-width" type="submit">Сохранить</button>
<a class="btn btn-secondary button-fixed-width" href="/video">Отмена</a>
</div>
</form>
</main>
</body>
</html>

View File

@ -0,0 +1,49 @@
<!DOCTYPE html>
<html lang="ru" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}">
<head>
<title>Список комментарие</title>
</head>
<body>
<main layout:fragment="content">
<th:block th:switch="${items.size()}">
<h2 th:case="0">Данные отсутствуют</h2>
<th:block th:case="*">
<h2>Видео</h2>
<table class="table">
<caption></caption>
<thead>
<tr>
<th scope="col" class="w-10">ID</th>
<th scope="col" class="w-10">ID Видео</th>
<th scope="col" class="w-auto">ID пользователя</th>
<th scope="col" class="w-10"></th>
<th scope="col" class="w-10"></th>
</tr>
</thead>
<tbody>
<tr th:each="comment : ${items}">
<th scope="row" th:text="${comment.id}"></th>
<th scope="row" th:text="${comment.videoId}"></th>
<th scope="row" th:text="${comment.userId}"></th>
<td>
<form th:action="@{/video/comment/edit/{id}(id=${comment.id})}" method="get">
<button type="submit" class="btn btn-link button-link">Редактировать</button>
</form>
</td>
<td>
<form th:action="@{/video/comment/delete/{id}(id=${comment.id})}" method="post">
<button type="submit" class="btn btn-link button-link"
onclick="return confirm('Вы уверены?')">Удалить</button>
</form>
</td>
</tr>
</tbody>
</table>
</th:block>
</th:block>
</main>
</body>
</html>

View File

@ -0,0 +1,55 @@
<!DOCTYPE html>
<html lang="ru" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}">
<head>
<title>Список комментарие</title>
</head>
<body>
<main layout:fragment="content">
<th:block th:switch="${items.size()}">
<h2 th:case="0">Данные отсутствуют</h2>
<th:block th:case="*">
<h2>Видео</h2>
<table class="table">
<caption></caption>
<thead>
<tr>
<th scope="col" class="w-10">ID</th>
<th scope="col" class="w-10">ID Видео</th>
<th scope="col" class="w-auto">ID пользователя</th>
<th scope="col" class="w-10"></th>
<th scope="col" class="w-10"></th>
</tr>
</thead>
<tbody>
<tr th:each="comment : ${items}">
<th scope="row" th:text="${comment.id}"></th>
<th scope="row" th:text="${comment.videoId}"></th>
<th scope="row" th:text="${comment.userId}"></th>
<th:block sec:authorize="hasRole('ADMIN')">
<td>
<form th:action="@{/admin/comment/edit/{id}(id=${comment.id})}" method="get">
<button type="submit" class="btn btn-link button-link">Редактировать</button>
</form>
</td>
<td>
<form th:action="@{/admin/comment/delete/{id}(id=${comment.id})}" method="post">
<button type="submit" class="btn btn-link button-link"
onclick="return confirm('Вы уверены?')">Удалить</button>
</form>
</td>
</th:block>
</tr>
</tbody>
</table>
</th:block>
<th:block th:replace="~{ pagination :: pagination (
url=${'admin/comment'},
totalPages=${totalPages},
currentPage=${currentPage}) }" />
</th:block>
</main>
</body>
</html>

View File

@ -0,0 +1,66 @@
<!DOCTYPE html>
<html lang="ru" data-bs-theme="dark" xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity6">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title layout:title-pattern="$LAYOUT_TITLE - $CONTENT_TITLE">Тарелька</title>
<script type="text/javascript" src="/webjars/bootstrap/5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<link rel="stylesheet" href="/webjars/bootstrap/5.3.3/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="/webjars/bootstrap-icons/1.11.3/font/bootstrap-icons.min.css" />
<link rel="stylesheet" href="/css/style.css" />
</head>
<body class="h-100 d-flex flex-column">
<nav class="navbar navbar-expand-md my-navbar" data-bs-theme="dark">
<div class="container-fluid">
<a class="navbar-brand" href="/">
<i class="bi bi-cart2 d-inline-block align-top me-1 logo"></i>
Тарелька
</a>
<th:block sec:authorize="isAuthenticated()" th:with="userName=${#authentication.name}">
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#main-navbar"
aria-controls="main-navbar" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="main-navbar">
<ul class="navbar-nav me-auto link" th:with="activeLink=${#objects.nullSafe(servletPath, '')}">
<th:block sec:authorize="hasRole('ADMIN')">
<a class="nav-link" href="/admin/user"
th:classappend="${activeLink.startsWith('/admin/user') ? 'active' : ''}">
Пользователи
</a>
<a class="nav-link" href="/admin/comment"
th:classappend="${activeLink.startsWith('/admin/comment') ? 'active' : ''}">
Комментарии
</a>
<a class="nav-link" href="/h2-console/" target="_blank">Консоль H2</a>
</th:block>
<a class="nav-link" href="/list/video"
th:classappend="${activeLink.startsWith('/list/video') ? 'active' : ''}">
Видео
</a>
</ul>
<ul class="navbar-nav" th:if="${not #strings.isEmpty(userName)}">
<form th:action="@{/logout}" method="post">
<button type="submit" class="navbar-brand nav-link" onclick="return confirm('Вы уверены?')">
Выход ([[${userName}]])
</button>
</form>
</ul>
</div>
</th:block>
</div>
</nav>
<main class="container-fluid p-2" layout:fragment="content">
</main>
<footer class="my-footer mt-auto d-flex flex-shrink-0 justify-content-center align-items-center">
Автор, [[${#dates.year(#dates.createNow())}]]
</footer>
</body>
</html>

View File

@ -0,0 +1,37 @@
<!DOCTYPE html>
<html lang="ru" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}">
<head>
<title>Ошибка</title>
</head>
<body>
<main layout:fragment="content">
<ul class="list-group mb-2">
<th:block th:if="${#strings.isEmpty(message)}">
<li class="list-group-item">
Неизвестная ошибка
</li>
</th:block>
<th:block th:if="${not #strings.isEmpty(message)}">
<li class="list-group-item">
<strong>Ошибка:</strong> [[${message}]]
</li>
</th:block>
<th:block th:if="${not #strings.isEmpty(url)}">
<li class="list-group-item">
<strong>Адрес:</strong> [[${url}]]
</li>
<li class="list-group-item">
<strong>Класс исключения:</strong> [[${exception}]]
</li>
<li class="list-group-item">
[[${method}]] ([[${file}]]:[[${line}]])
</li>
</th:block>
</ul>
<a class="btn btn-primary button-fixed-width" href="/">На главную</a>
</main>
</body>
</html>

View File

@ -0,0 +1,22 @@
<!DOCTYPE html>
<html lang="ru" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}">
<head>
<title>Главная страница</title>
</head>
<body>
<main layout:fragment="content">
<div>
<a th:href="@{/video}" class="btn btn-primary">Мои видео</a>
</div>
<div>
<a th:href="@{/video/comment}" class="btn btn-primary">Мои комментарии</a>
</div>
<div>
<a th:href="@{/video/like}" class="btn btn-primary">Понравившиеся видео</a>
</div>
</main>
</body>
</html>

View File

@ -0,0 +1,44 @@
<!DOCTYPE html>
<html lang="ru" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}">
<head>
<title>Вход</title>
</head>
<body>
<main layout:fragment="content">
<form action="#" th:action="@{/login}" method="post">
<div th:if="${param.error}" class="alert alert-danger">
Неверный логин или пароль
</div>
<div th:if="${param.logout}" class="alert alert-success">
Выход успешно произведен
</div>
<div th:if="${param.signup}" class="alert alert-success">
Пользователь успешно создан
</div>
<div class="mb-3">
<label for="username" class="form-label">Имя пользователя</label>
<input type="text" id="username" name="username" class="form-control" required minlength="3"
maxlength="20">
</div>
<div class="mb-3">
<label for="password" class="form-label">Пароль</label>
<input type="password" id="password" name="password" class="form-control" required minlength="3"
maxlength="20">
</div>
<div class="form-check mb-3">
<input class="form-check-input" type="checkbox" id="remember-me" name="remember-me" checked>
<label class="form-check-label" for="remember-me">Запомнить меня</label>
</div>
<div class="mb-3 d-flex flex-row">
<button class="btn btn-primary me-2 button-fixed-width" type="submit">Войти</button>
<a class="btn btn-secondary button-fixed-width" href="/signup">Регистрация</a>
</div>
</form>
</main>
</body>
</html>
</html>

View File

@ -0,0 +1,51 @@
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<body>
<th:block th:fragment="pagination (url, totalPages, currentPage)">
<nav th:if="${totalPages > 1}" th:with="
maxPage=2,
currentPage=${currentPage + 1}">
<ul class="pagination justify-content-center"
th:with="
seqFrom=${currentPage - maxPage < 1 ? 1 : currentPage - maxPage},
seqTo=${currentPage + maxPage > totalPages ? totalPages : currentPage + maxPage}">
<th:block th:if="${currentPage > maxPage + 1}">
<li class="page-item">
<a class="page-link" aria-label="Previous" th:href="@{/{url}?page=0(url=${url})}">
<span aria-hidden="true">&laquo;</span>
</a>
</li>
<li class="page-item disabled">
<span class="page-link" aria-label="Previous">
<span aria-hidden="true">&hellip;</span>
</span>
</li>
</th:block>
<li class="page-item" th:each="page : ${#numbers.sequence(seqFrom, seqTo)}"
th:classappend="${page == currentPage} ? 'active' : ''">
<a class=" page-link" th:href="@{/{url}?page={page}(url=${url},page=${page - 1})}">
<span th:text="${page}" />
</a>
</li>
<th:block th:if="${currentPage < totalPages - maxPage}">
<li class="page-item disabled">
<span class="page-link" aria-label="Previous">
<span aria-hidden="true">&hellip;</span>
</span>
</li>
<li class="page-item">
<a class="page-link" aria-label="Next"
th:href="@{/{url}?page={page}(url=${url},page=${totalPages - 1})}">
<span aria-hidden="true">&raquo;</span>
</a>
</li>
</th:block>
</ul>
</nav>
</th:block>
</body>
</html>

View File

@ -0,0 +1,37 @@
<!DOCTYPE html>
<html lang="ru" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}">
<head>
<title>Вход</title>
</head>
<body>
<main layout:fragment="content">
<form action="#" th:action="@{/signup}" th:object="${user}" method="post">
<div class="mb-3">
<label for="login" class="form-label">Имя пользователя</label>
<input type="text" th:field="*{login}" id="login" class="form-control">
<div th:if="${#fields.hasErrors('login')}" th:errors="*{login}" class="invalid-feedback"></div>
</div>
<div class="mb-3">
<label for="password" class="form-label">Пароль</label>
<input type="password" th:field="*{password}" id="password" class="form-control">
<div th:if="${#fields.hasErrors('password')}" th:errors="*{password}" class="invalid-feedback"></div>
</div>
<div class="mb-3">
<label for="passwordConfirm" class="form-label">Пароль (подтверждение)</label>
<input type="password" th:field="*{passwordConfirm}" id="passwordConfirm" class="form-control">
<div th:if="${#fields.hasErrors('passwordConfirm')}" th:errors="*{passwordConfirm}"
class="invalid-feedback"></div>
</div>
<div class="mb-3 d-flex flex-row">
<button class="btn btn-primary me-2 button-fixed-width" type="submit">Регистрация</button>
<a class="btn btn-secondary button-fixed-width" href="/">Отмена</a>
</div>
</form>
</main>
</body>
</html>
</html>

View File

@ -0,0 +1,53 @@
<!DOCTYPE html>
<html lang="ru" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}">
<head>
<title>Список комментариев</title>
</head>
<body>
<main layout:fragment="content">
<th:block th:switch="${items.size()}">
<h2 th:case="0">Данные отсутствуют</h2>
<th:block th:case="*">
<h2>Видео</h2>
<table class="table">
<caption></caption>
<thead>
<tr>
<th scope="col" class="w-10">ID</th>
<th scope="col" class="w-10">ID Видео</th>
<th scope="col" class="w-auto">ID пользователя</th>
<th scope="col" class="w-10"></th>
<th scope="col" class="w-10"></th>
</tr>
</thead>
<tbody>
<tr th:each="comment : ${items}">
<th scope="row" th:text="${comment.id}"></th>
<th scope="row" th:text="${comment.videoId}"></th>
<th scope="row" th:text="${comment.userId}"></th>
<td>
<form th:action="@{/video/comment/edit/{id}(id=${video.id})}" method="get">
<button type="submit" class="btn btn-link button-link">Редактировать</button>
</form>
</td>
<td>
<form th:action="@{/video/comment/delete/{id}(id=${video.id})}" method="post">
<button type="submit" class="btn btn-link button-link"
onclick="return confirm('Вы уверены?')">Удалить</button>
</form>
</td>
</tr>
</tbody>
</table>
</th:block>
<th:block th:replace="~{ pagination :: pagination (
url=${'video/comment'},
totalPages=${totalPages},
currentPage=${currentPage}) }" />
</th:block>
</main>
</body>
</html>

View File

@ -0,0 +1,29 @@
<!DOCTYPE html>
<html lang="ru" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}">
<head>
<title>Редактировать пользователя</title>
</head>
<body>
<main layout:fragment="content">
<form action="#" th:action="@{/admin/user/edit/{id}(id=${user.id},page=${page})}" th:object="${user}"
method="post">
<div class="mb-3">
<label for="id" class="form-label">ID</label>
<input type="text" th:value="*{id}" id="id" class="form-control" readonly disabled>
</div>
<div class="mb-3">
<label for="login" class="form-label">Имя пользователя</label>
<input type="text" th:field="*{login}" id="login" class="form-control">
<div th:if="${#fields.hasErrors('login')}" th:errors="*{login}" class="invalid-feedback"></div>
</div>
<div class="mb-3 d-flex flex-row">
<button class="btn btn-primary me-2 button-fixed-width" type="submit">Сохранить</button>
<a class="btn btn-secondary button-fixed-width" th:href="@{/admin/user(page=${page})}">Отмена</a>
</div>
</form>
</main>
</body>
</html>

View File

@ -0,0 +1,54 @@
<!DOCTYPE html>
<html lang="ru" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}">
<head>
<title>Мои видео</title>
</head>
<body>
<main layout:fragment="content">
<th:block th:switch="${items.size()}">
<h2 th:case="0">Видео отсутствуют</h2>
<div>
<a th:href="@{/video/edit/(page=${page})}" class="btn btn-primary">Добавить видео</a>
</div>
<th:block th:case="*">
<h2>Видео</h2>
<table class="table">
<caption></caption>
<thead>
<tr>
<th scope="col" class="w-10">ID</th>
<th scope="col" class="w-auto">Название видео</th>
<th scope="col" class="w-10"></th>
<th scope="col" class="w-10"></th>
</tr>
</thead>
<tbody>
<tr th:each="video : ${items}">
<th scope="row" th:text="${video.id}"></th>
<td th:text="${video.title}"></td>
<td>
<form th:action="@{/video/edit/{id}(id=${video.id})}" method="get">
<button type="submit" class="btn btn-link button-link">Редактировать</button>
</form>
</td>
<td>
<form th:action="@{/video/delete/{id}(id=${video.id})}" method="post">
<button type="submit" class="btn btn-link button-link"
onclick="return confirm('Вы уверены?')">Удалить</button>
</form>
</td>
</tr>
</tbody>
</table>
</th:block>
<th:block th:replace="~{ pagination :: pagination (
url=${'video'},
totalPages=${totalPages},
currentPage=${currentPage}) }" />
</th:block>
</main>
</body>
</html>

View File

@ -0,0 +1,56 @@
<!DOCTYPE html>
<html lang="ru" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}">
<head>
<title>Пользователи</title>
</head>
<body>
<main layout:fragment="content">
<th:block th:switch="${items.size()}">
<h2 th:case="0">Данные отсутствуют</h2>
<th:block th:case="*">
<h2>Пользователи</h2>
<div>
<a th:href="@{/admin/user/edit/(page=${page})}" class="btn btn-primary">Добавить пользователя</a>
</div>
<table class="table">
<caption></caption>
<thead>
<tr>
<th scope="col" class="w-10">ID</th>
<th scope="col" class="w-auto">Имя пользователя</th>
<th scope="col" class="w-10"></th>
<th scope="col" class="w-10"></th>
</tr>
</thead>
<tbody>
<tr th:each="user : ${items}">
<th scope="row" th:text="${user.id}"></th>
<td th:text="${user.login}"></td>
<td>
<form th:action="@{/admin/user/edit/{id}(id=${user.id})}" method="get">
<input type="hidden" th:name="page" th:value="${page}">
<button type="submit" class="btn btn-link button-link">Редактировать</button>
</form>
</td>
<td>
<form th:action="@{/admin/user/delete/{id}(id=${user.id})}" method="post">
<input type="hidden" th:name="page" th:value="${page}">
<button type="submit" class="btn btn-link button-link"
onclick="return confirm('Вы уверены?')">Удалить</button>
</form>
</td>
</tr>
</tbody>
</table>
</th:block>
<th:block th:replace="~{ pagination :: pagination (
url=${'admin/user'},
totalPages=${totalPages},
currentPage=${currentPage}) }" />
</th:block>
</main>
</body>
</html>

View File

@ -0,0 +1,48 @@
<!DOCTYPE html>
<html lang="ru" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}">
<head>
<title>Редактировать видео</title>
</head>
<body>
<main layout:fragment="content">
<form action="#" th:action="@{/video/edit/{id}(id=${video.id})}" th:object="${video}" method="post">
<div class="mb-3">
<label for="id" class="form-label">ID</label>
<input type="text" th:value="*{id}" id="id" class="form-control" readonly disabled>
</div>
<div class="mb-3">
<label for="userId" class="form-label">ID пользователя</label>
<input type="number" th:field="*{userId}" id="userId" class="form-control" readonly>
</div>
<div class="mb-3">
<label for="name" class="form-label">Название видео</label>
<input type="text" th:field="*{title}" id="title" class="form-control">
<div th:if="${#fields.hasErrors('title')}" th:errors="*{title}" class="invalid-feedback"></div>
</div>
<div class="mb-3">
<label for="name" class="form-label">Описание видео</label>
<input type="text" th:field="*{description}" id="description" class="form-control">
<div th:if="${#fields.hasErrors('description')}" th:errors="*{description}" class="invalid-feedback">
</div>
</div>
<div class="mb-3">
<label for="name" class="form-label">Изображение видео</label>
<input type="text" th:field="*{image}" id="image" class="form-control">
<div th:if="${#fields.hasErrors('image')}" th:errors="*{image}" class="invalid-feedback"></div>
</div>
<div class="mb-3">
<label for="name" class="form-label">Ссылка на видео</label>
<input type="text" th:field="*{vid}" id="vid" class="form-control">
<div th:if="${#fields.hasErrors('vid')}" th:errors="*{vid}" class="invalid-feedback"></div>
</div>
<div class="mb-3 d-flex flex-row">
<button class="btn btn-primary me-2 button-fixed-width" type="submit">Сохранить</button>
<a class="btn btn-secondary button-fixed-width" href="/admin/video">Отмена</a>
</div>
</form>
</main>
</body>
</html>

View File

@ -0,0 +1,47 @@
<!DOCTYPE html>
<html lang="ru" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}">
<head>
<title>Понравившиеся</title>
</head>
<body>
<main layout:fragment="content">
<th:block th:switch="${items.size()}">
<h2 th:case="0">Данные отсутствуют</h2>
<th:block th:case="*">
<h2>Понравившиеся видео</h2>
<table class="table">
<caption></caption>
<thead>
<tr>
<th scope="col" class="w-10">ID</th>
<th scope="col" class="w-10">ID автора</th>
<th scope="col" class="w-auto">ID видео</th>
<th scope="col" class="w-10"></th>
</tr>
</thead>
<tbody>
<tr th:each="like : ${items}">
<th scope="row" th:text="${like.id}"></th>
<th scope="row" th:text="${like.userId}"></th>
<td th:text="${like.videoId}"></td>
<td>
<form th:action="@{/video/dislike2/{id}(id=${like.videoId})}" method="post">
<button type="submit" class="btn btn-link button-link"
onclick="return confirm('Вы уверены?')">Удалить</button>
</form>
</td>
</tr>
</tbody>
</table>
</th:block>
<th:block th:replace="~{ pagination :: pagination (
url=${'video/like'},
totalPages=${totalPages},
currentPage=${currentPage}) }" />
</th:block>
</main>
</body>
</html>

View File

@ -0,0 +1,80 @@
<!DOCTYPE html>
<html lang="ru" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}">
<head>
<title>Видео</title>
</head>
<body>
<main layout:fragment="content">
<th:block th:switch="${items.size()}">
<h2 th:case="0">Данные отсутствуют</h2>
<th:block th:case="*">
<h2>Видео</h2>
<table class="table">
<caption></caption>
<thead>
<tr>
<th scope="col" class="w-10">ID</th>
<th scope="col" class="w-10">ID пользователя</th>
<th scope="col" class="w-auto">Название видео</th>
<th scope="col" class="w-10"></th>
<th scope="col" class="w-10"></th>
<th:block sec:authorize="hasRole('ADMIN')">
<th scope="col" class="w-10"></th>
<th scope="col" class="w-10"></th>
</th:block>
</tr>
</thead>
<tbody>
<tr th:each="video : ${items}">
<th scope="row" th:text="${video.id}"></th>
<th scope="row" th:text="${video.userId}"></th>
<td th:text="${video.title}"></td>
<td>
<form
th:action="${video.isLiked} ? @{/video/dislike1/{id}(id=${video.id})} : @{/video/like/{id}(id=${video.id})}"
method="post">
<button type="submit" class="btn btn-link button-link"
th:text="${video.isLiked} ? 'Удалить лайк' : 'Поставить лайк'"></button>
</form>
</td>
<td>
<form th:action="@{/video/comment/edit/add/{videoId}(videoId=${video.id})}"
method="get">
<button type="submit" class="btn btn-link button-link"
onclick="return confirm('Вы уверены?')">Добавить комментарий</button>
</form>
</td>
<td>
<form th:action="@{/list/comment/{videoId}(page=${page}, videoId=${video.id})}"
method="get">
<button type="submit" class="btn btn-link button-link">Список комментариев</button>
</form>
</td>
<th:block sec:authorize="hasRole('ADMIN')">
<td>
<form th:action="@{/admin/video/edit/{id}(id=${video.id})}" method="get">
<button type="submit" class="btn btn-link button-link">Редактировать</button>
</form>
</td>
<td>
<form th:action="@{/admin/video/delete/{id}(id=${video.id})}" method="post">
<button type="submit" class="btn btn-link button-link"
onclick="return confirm('Вы уверены?')">Удалить</button>
</form>
</td>
</th:block>
</tr>
</tbody>
</table>
</th:block>
<th:block th:replace="~{ pagination :: pagination (
url=${'list/video'},
totalPages=${totalPages},
currentPage=${currentPage}) }" />
</th:block>
</main>
</body>
</html>

View File

@ -0,0 +1,73 @@
package com.example.demo;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.dao.DataIntegrityViolationException;
import com.example.demo.comments.model.CommentEntity;
import com.example.demo.comments.service.CommentService;
import com.example.demo.users.model.UserEntity;
import com.example.demo.users.service.UserService;
import com.example.demo.videos.model.VideoEntity;
import com.example.demo.videos.service.VideoService;
@SpringBootTest
class CommentServiceTests {
@Autowired
private VideoService videoService;
@Autowired
private UserService userService;
@Autowired
private CommentService commentService;
private CommentEntity comment;
private VideoEntity video;
private UserEntity user;
@BeforeEach
void createData() {
user = userService.create(new UserEntity("null", "null"));
video = videoService.create(new VideoEntity(user, "null", "null", "null", "null"));
comment = commentService.create(new CommentEntity(video, user, "test"));
commentService.create(new CommentEntity(video, user, "second"));
commentService.create(new CommentEntity(video, user, "third"));
}
@AfterEach
void removeData() {
commentService.getAll(0L).forEach(item -> commentService.delete(item.getId()));
videoService.getAll(0L).forEach(item -> videoService.delete(item.getId()));
userService.getAll().forEach(item -> userService.delete(item.getId()));
}
@Test
void createTest() {
Assertions.assertEquals(3, commentService.getAll(0L).size());
Assertions.assertEquals(comment, commentService.get(comment.getId()));
Assertions.assertEquals(3, commentService.getAll(video.getId()).size());
}
@Test
void createNullableTest() {
final CommentEntity nullCom = new CommentEntity(video, user, null);
Assertions.assertThrows(DataIntegrityViolationException.class, () -> commentService.create(nullCom));
}
@Test
void updateTest() {
final String test = "TEST";
final String lastText = comment.getText();
final CommentEntity updatedEntity = commentService.update(comment.getId(),
new CommentEntity(video, user, test));
Assertions.assertEquals(3, commentService.getAll(0L).size());
Assertions.assertEquals(updatedEntity, commentService.get(comment.getId()));
Assertions.assertNotEquals(lastText, updatedEntity.getText());
}
}

View File

@ -0,0 +1,76 @@
package com.example.demo;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import com.example.demo.likes.model.LikeEntity;
import com.example.demo.likes.service.LikeService;
import com.example.demo.users.model.UserEntity;
import com.example.demo.users.service.UserService;
import com.example.demo.videos.model.VideoEntity;
import com.example.demo.videos.service.VideoService;
@SpringBootTest
class LikeServiceTests {
@Autowired
private VideoService videoService;
@Autowired
private UserService userService;
@Autowired
private LikeService likeService;
private LikeEntity like;
private VideoEntity video;
private UserEntity user;
private VideoEntity video1;
private UserEntity user1;
@BeforeEach
void createData() {
user = userService.create(new UserEntity("null", "null"));
video = videoService.create(new VideoEntity(user, "null", "null", "null", "null"));
user1 = userService.create(new UserEntity("aboba", "null"));
video1 = videoService.create(new VideoEntity(user, "null", "null", "null", "null"));
like = likeService.create(new LikeEntity(video, user));
likeService.create(new LikeEntity(video1, user));
likeService.create(new LikeEntity(video, user1));
likeService.create(new LikeEntity(video1, user1));
}
@AfterEach
void removeData() {
likeService.getAll(0L).forEach(item -> likeService.delete(item.getId()));
videoService.getAll(0L).forEach(item -> videoService.delete(item.getId()));
userService.getAll().forEach(item -> userService.delete(item.getId()));
}
@Test
void createTest() {
Assertions.assertEquals(4, likeService.getAll(0L).size());
Assertions.assertEquals(like, likeService.get(like.getId()));
Assertions.assertEquals(4, likeService.getAll(0L).size());
}
@Test
void removeOne() {
likeService.deleteByUserIdAndVideoId(user.getId(), video.getId());
Assertions.assertEquals(3, likeService.getAll(0L).size());
}
@Test
void getByUser() {
Assertions.assertEquals(2, likeService.getAll(video.getId()).size());
Assertions.assertEquals(2, likeService.getAll(video1.getId()).size());
}
@Test
void getByVideo() {
Assertions.assertEquals(2, likeService.getAllByUser(user.getId()).size());
Assertions.assertEquals(2, likeService.getAllByUser(user1.getId()).size());
}
}

View File

@ -0,0 +1,69 @@
package com.example.demo;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.dao.DataIntegrityViolationException;
import com.example.demo.core.error.NotFoundException;
import com.example.demo.users.model.UserEntity;
import com.example.demo.users.service.UserService;
@SpringBootTest
class UserServiceTests {
@Autowired
private UserService userService;
private UserEntity user;
@BeforeEach
void createData() {
removeData();
user = userService.create(new UserEntity("mail", "pass"));
userService.create(new UserEntity("mailru", "pass"));
userService.create(new UserEntity("mailcom", "pass"));
}
@AfterEach
void removeData() {
userService.getAll().forEach(item -> userService.delete(item.getId()));
}
@Test
void getTest() {
Assertions.assertThrows(NotFoundException.class, () -> userService.get(0L));
}
@Test
void createTest() {
Assertions.assertEquals(3, userService.getAll().size());
Assertions.assertEquals(user, userService.get(user.getId()));
}
@Test
void createNotUniqueTest() {
final UserEntity nonUniqueUser = new UserEntity("mailru", "pass");
Assertions.assertThrows(IllegalArgumentException.class, () -> userService.create(nonUniqueUser));
}
@Test
void createNullableTest() {
final UserEntity nullableUser = new UserEntity(null, null);
Assertions.assertThrows(DataIntegrityViolationException.class, () -> userService.create(nullableUser));
}
@Test
void updateTest() {
final String testString = "TEST";
final String lastName = user.getLogin();
final UserEntity updatedUser = userService.update(user.getId(),
new UserEntity(testString, testString));
Assertions.assertEquals(3, userService.getAll().size());
Assertions.assertEquals(updatedUser, userService.get(user.getId()));
Assertions.assertNotEquals(lastName, updatedUser.getLogin());
}
}

View File

@ -0,0 +1,74 @@
package com.example.demo;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.dao.DataIntegrityViolationException;
import com.example.demo.users.model.UserEntity;
import com.example.demo.users.service.UserService;
import com.example.demo.videos.model.VideoEntity;
import com.example.demo.videos.service.VideoService;
@SpringBootTest
class VideoServiceTests {
@Autowired
private VideoService videoService;
@Autowired
private UserService userService;
private VideoEntity video;
private UserEntity user1;
private UserEntity user2;
@BeforeEach
void createData() {
removeData();
user1 = userService.create(new UserEntity("mail1", "pass"));
user2 = userService.create(new UserEntity("mail2", "pass"));
videoService.create(new VideoEntity(user1, "first", "null", "pas", "pas"));
videoService.create(new VideoEntity(user2, "second", "null", "pas", "pas"));
video = videoService.create(new VideoEntity(user2, "third", "null", "pas", "pas"));
}
@AfterEach
void removeData() {
videoService.getAll(0L).forEach(item -> videoService.delete(item.getId()));
userService.getAll().forEach(item -> userService.delete(item.getId()));
}
@Test
void createTest() {
Assertions.assertEquals(3, videoService.getAll(0L).size());
Assertions.assertEquals(2, videoService.getAll(user2.getId()).size());
Assertions.assertEquals(video, videoService.get(video.getId()));
}
@Test
void createNullableTest() {
final VideoEntity nullableVideo = new VideoEntity(user1, null, null, null, null);
Assertions.assertThrows(DataIntegrityViolationException.class, () -> videoService.create(nullableVideo));
}
@Test
void updateTest() {
final String test = "TEST";
final String lastTitle = video.getTitle();
final String lastDesc = video.getDescription();
final String lastVid = video.getVid();
final String lastImage = video.getImage();
final VideoEntity updatedEntity = videoService.update(video.getId(),
new VideoEntity(user1, test, test, test, test));
Assertions.assertEquals(3, videoService.getAll(0L).size());
Assertions.assertEquals(updatedEntity, videoService.get(video.getId()));
Assertions.assertNotEquals(lastTitle, updatedEntity.getTitle());
Assertions.assertNotEquals(lastDesc, updatedEntity.getDescription());
Assertions.assertNotEquals(lastVid, updatedEntity.getVid());
Assertions.assertNotEquals(lastImage, updatedEntity.getImage());
}
}

View File

@ -0,0 +1,14 @@
# Server
spring.main.banner-mode=off
# Logger settings
# Available levels are: TRACE, DEBUG, INFO, WARN, ERROR, FATAL, OFF
logging.level.com.example.demo=DEBUG
# JPA Settings
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.username=sa
spring.datasource.password=password
spring.datasource.driver-class-name=org.h2.Driver
spring.jpa.hibernate.ddl-auto=create
spring.jpa.open-in-view=false