first commit

main
Aleksey Filippov 1 year ago
commit 7b46d9ea34

39
.gitignore vendored

@ -0,0 +1,39 @@
HELP.md
.gradle
build/
!gradle/wrapper/gradle-wrapper.jar
!**/src/main/**/build/
!**/src/test/**/build/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
bin/
!**/src/main/**/bin/
!**/src/test/**/bin/
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
out/
!**/src/main/**/out/
!**/src/test/**/out/
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
### VS Code ###
.vscode/
*.db

@ -0,0 +1,23 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="SbappApplication (prod)" type="GradleRunConfiguration" factoryName="Gradle">
<ExternalSystemSettings>
<option name="executionName"/>
<option name="externalProjectPath" value="$PROJECT_DIR$"/>
<option name="externalSystemIdString" value="GRADLE"/>
<option name="scriptParameters" value="-Pprod"/>
<option name="taskDescriptions">
<list/>
</option>
<option name="taskNames">
<list>
<option value="bootRun"/>
</list>
</option>
<option name="vmOptions"/>
</ExternalSystemSettings>
<ExternalSystemDebugServerProcess>true</ExternalSystemDebugServerProcess>
<ExternalSystemReattachDebugProcess>true</ExternalSystemReattachDebugProcess>
<DebugAllEnabled>false</DebugAllEnabled>
<method v="2"/>
</configuration>
</component>

@ -0,0 +1,23 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="SbappApplication" type="GradleRunConfiguration" factoryName="Gradle">
<ExternalSystemSettings>
<option name="executionName"/>
<option name="externalProjectPath" value="$PROJECT_DIR$"/>
<option name="externalSystemIdString" value="GRADLE"/>
<option name="scriptParameters" value=""/>
<option name="taskDescriptions">
<list/>
</option>
<option name="taskNames">
<list>
<option value="bootRun"/>
</list>
</option>
<option name="vmOptions"/>
</ExternalSystemSettings>
<ExternalSystemDebugServerProcess>true</ExternalSystemDebugServerProcess>
<ExternalSystemReattachDebugProcess>true</ExternalSystemReattachDebugProcess>
<DebugAllEnabled>false</DebugAllEnabled>
<method v="2"/>
</configuration>
</component>

@ -0,0 +1,62 @@
plugins {
id 'org.springframework.boot' version '2.6.3'
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
id 'java'
}
group = 'ru.ulstu.is'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '17'
def profile = project.hasProperty('prod') ? 'prod' : 'dev'
println 'Current profile is ' + profile
bootRun {
systemProperties = System.properties
systemProperty 'spring.profiles.active', profile
}
test {
systemProperty 'spring.profiles.active', profile
}
jar {
enabled = false
}
repositories {
mavenCentral()
}
dependencies {
if (profile == 'prod') {
implementation 'org.postgresql:postgresql:42.3.5'
} else {
implementation 'com.h2database:h2:2.1.210'
}
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
implementation 'org.springframework.boot:spring-boot-devtools'
implementation 'nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect'
implementation 'org.webjars:bootstrap:5.1.3'
implementation 'org.webjars:jquery:3.6.0'
implementation 'org.webjars:font-awesome:6.1.0'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.liquibase:liquibase-core:4.10.0'
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity5'
implementation 'org.hibernate.validator:hibernate-validator'
implementation 'org.springdoc:springdoc-openapi-ui:1.6.5'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
tasks.named('test') {
useJUnitPlatform()
}

Binary file not shown.

@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.3-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

234
gradlew vendored

@ -0,0 +1,234 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
APP_NAME="Gradle"
APP_BASE_NAME=${0##*/}
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# 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" "$@"

89
gradlew.bat vendored

@ -0,0 +1,89 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "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%"=="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!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

@ -0,0 +1,2 @@
createdb -U postgres sbapp
gradlew bootRun -Pprod

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

@ -0,0 +1,11 @@
package ru.ulstu.is.sbapp;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SbappApplication {
public static void main(String[] args) {
SpringApplication.run(SbappApplication.class, args);
}
}

@ -0,0 +1,14 @@
package ru.ulstu.is.sbapp.configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
public class PasswordEncoderConfiguration {
@Bean
public PasswordEncoder createPasswordEncoder() {
return new BCryptPasswordEncoder();
}
}

@ -0,0 +1,57 @@
package ru.ulstu.is.sbapp.configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import ru.ulstu.is.sbapp.user.controller.UserSignupMvcController;
import ru.ulstu.is.sbapp.user.service.UserService;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
private final Logger log = LoggerFactory.getLogger(SecurityConfiguration.class);
private static final String LOGIN_URL = "/login";
private final UserService userService;
public SecurityConfiguration(UserService userService) {
this.userService = userService;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.headers().frameOptions().sameOrigin().and()
.cors().and()
.csrf().disable()
.authorizeRequests()
.antMatchers(UserSignupMvcController.SIGNUP_URL).permitAll()
.antMatchers(HttpMethod.GET, LOGIN_URL).permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage(LOGIN_URL).permitAll()
.and()
.logout().permitAll();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userService);
}
@Override
public void configure(WebSecurity web) {
web.ignoring()
.antMatchers("/css/**")
.antMatchers("/js/**")
.antMatchers("/templates/**")
.antMatchers("/webjars/**");
}
}

@ -0,0 +1,24 @@
package ru.ulstu.is.sbapp.configuration;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfiguration implements WebMvcConfigurer {
public static final String REST_API = "/api";
@Override
public void addViewControllers(ViewControllerRegistry registry) {
WebMvcConfigurer.super.addViewControllers(registry);
registry.addViewController("rest-test");
registry.addViewController("login");
}
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedMethods("*");
}
}

@ -0,0 +1,26 @@
package ru.ulstu.is.sbapp.speaker.configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import ru.ulstu.is.sbapp.speaker.domain.Speaker;
import ru.ulstu.is.sbapp.speaker.domain.SpeakerEng;
import ru.ulstu.is.sbapp.speaker.domain.SpeakerRus;
@Configuration
public class SpeakerConfiguration {
private final Logger log = LoggerFactory.getLogger(SpeakerConfiguration.class);
@Bean(value = "ru", initMethod = "init", destroyMethod = "destroy")
public SpeakerRus createRusSpeaker() {
log.info("Call createRusSpeaker()");
return new SpeakerRus();
}
@Bean(value = "en")
public Speaker createEngSpeaker() {
log.info("Call createEngSpeaker()");
return new SpeakerEng();
}
}

@ -0,0 +1,24 @@
package ru.ulstu.is.sbapp.speaker.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import ru.ulstu.is.sbapp.configuration.WebConfiguration;
import ru.ulstu.is.sbapp.speaker.service.SpeakerService;
@RestController
@RequestMapping(WebConfiguration.REST_API + "/speaker")
public class SpeakerController {
private final SpeakerService speakerService;
public SpeakerController(SpeakerService speakerService) {
this.speakerService = speakerService;
}
@GetMapping
public String hello(@RequestParam(value = "name", defaultValue = "Мир") String name,
@RequestParam(value = "lang", defaultValue = "ru") String lang) {
return speakerService.say(name, lang);
}
}

@ -0,0 +1,33 @@
package ru.ulstu.is.sbapp.speaker.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import ru.ulstu.is.sbapp.speaker.service.SpeakerService;
import java.util.List;
@Controller
@RequestMapping("/speaker")
public class SpeakerMvcController {
private final SpeakerService speakerService;
private final List<String> langs;
public SpeakerMvcController(SpeakerService speakerService) {
this.speakerService = speakerService;
this.langs = List.of("ru", "en", "de", "deu");
}
@GetMapping
public String hello(@RequestParam(value = "name", defaultValue = "Мир") String name,
@RequestParam(value = "lang", defaultValue = "ru") String lang,
Model model) {
model.addAttribute("langs", langs);
model.addAttribute("name", name);
model.addAttribute("lang", lang);
model.addAttribute("say", speakerService.say(name, lang));
return "speaker";
}
}

@ -0,0 +1,5 @@
package ru.ulstu.is.sbapp.speaker.domain;
public interface Speaker {
String say();
}

@ -0,0 +1,28 @@
package ru.ulstu.is.sbapp.speaker.domain;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
@Component(value = "de")
public class SpeakerDeu implements Speaker {
private final Logger log = LoggerFactory.getLogger(SpeakerDeu.class);
@Override
public String say() {
return "Hallo";
}
@PostConstruct
public void init() {
log.info("SpeakerDeu.init()");
}
@PreDestroy
public void destroy() {
log.info("SpeakerDeu.destroy()");
}
}

@ -0,0 +1,26 @@
package ru.ulstu.is.sbapp.speaker.domain;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
public class SpeakerEng implements Speaker, InitializingBean, DisposableBean {
private final Logger log = LoggerFactory.getLogger(SpeakerEng.class);
@Override
public String say() {
return "Hello";
}
@Override
public void afterPropertiesSet() {
log.info("SpeakerEng.afterPropertiesSet()");
}
@Override
public void destroy() {
log.info("SpeakerEng.destroy()");
}
}

@ -0,0 +1,21 @@
package ru.ulstu.is.sbapp.speaker.domain;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SpeakerRus implements Speaker {
private final Logger log = LoggerFactory.getLogger(SpeakerRus.class);
@Override
public String say() {
return "Привет";
}
public void init() {
log.info("SpeakerRus.init()");
}
public void destroy() {
log.info("SpeakerRus.destroy()");
}
}

@ -0,0 +1,19 @@
package ru.ulstu.is.sbapp.speaker.service;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import ru.ulstu.is.sbapp.speaker.domain.Speaker;
@Service
public class SpeakerService {
private final ApplicationContext applicationContext;
public SpeakerService(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
public String say(String name, String lang) {
final Speaker speaker = (Speaker) applicationContext.getBean(lang);
return String.format("%s %s!", speaker.say(), name);
}
}

@ -0,0 +1,53 @@
package ru.ulstu.is.sbapp.student.controller;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import ru.ulstu.is.sbapp.configuration.WebConfiguration;
import ru.ulstu.is.sbapp.student.service.StudentService;
import javax.validation.Valid;
import java.util.List;
@RestController
@RequestMapping(WebConfiguration.REST_API + "/student")
public class StudentController {
private final StudentService studentService;
public StudentController(StudentService studentService) {
this.studentService = studentService;
}
@GetMapping("/{id}")
public StudentDto getStudent(@PathVariable Long id) {
return new StudentDto(studentService.findStudent(id));
}
@GetMapping
public List<StudentDto> getStudents() {
return studentService.findAllStudents().stream()
.map(StudentDto::new)
.toList();
}
@PostMapping
public StudentDto createStudent(@RequestBody @Valid StudentDto studentDto) {
return new StudentDto(studentService.addStudent(studentDto.getFirstName(), studentDto.getLastName()));
}
@PutMapping("/{id}")
public StudentDto updateStudent(@PathVariable Long id,
@RequestBody @Valid StudentDto studentDto) {
return new StudentDto(studentService.updateStudent(id, studentDto.getFirstName(), studentDto.getLastName()));
}
@DeleteMapping("/{id}")
public StudentDto deleteStudent(@PathVariable Long id) {
return new StudentDto(studentService.deleteStudent(id));
}
}

@ -0,0 +1,44 @@
package ru.ulstu.is.sbapp.student.controller;
import com.fasterxml.jackson.annotation.JsonProperty;
import ru.ulstu.is.sbapp.student.model.Student;
import javax.validation.constraints.NotBlank;
public class StudentDto {
private long id;
@NotBlank(message = "Firstname can't be null or empty")
private String firstName;
@NotBlank(message = "Lastname can't be null or empty")
private String lastName;
public StudentDto() {
}
public StudentDto(Student student) {
this.id = student.getId();
this.firstName = student.getFirstName();
this.lastName = student.getLastName();
}
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public long getId() {
return id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}

@ -0,0 +1,67 @@
package ru.ulstu.is.sbapp.student.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import ru.ulstu.is.sbapp.student.service.StudentService;
import javax.validation.Valid;
@Controller
@RequestMapping("/student")
public class StudentMvcController {
private final StudentService studentService;
public StudentMvcController(StudentService studentService) {
this.studentService = studentService;
}
@GetMapping
public String getStudents(Model model) {
model.addAttribute("students",
studentService.findAllStudents().stream()
.map(StudentDto::new)
.toList());
return "student";
}
@GetMapping(value = {"/edit", "/edit/{id}"})
public String editStudent(@PathVariable(required = false) Long id,
Model model) {
if (id == null || id <= 0) {
model.addAttribute("studentDto", new StudentDto());
} else {
model.addAttribute("studentId", id);
model.addAttribute("studentDto", new StudentDto(studentService.findStudent(id)));
}
return "student-edit";
}
@PostMapping(value = {"/edit", "/edit/{id}"})
public String saveStudent(@PathVariable(required = false) Long id,
@ModelAttribute @Valid StudentDto studentDto,
BindingResult bindingResult,
Model model) {
if (bindingResult.hasErrors()) {
model.addAttribute("errors", bindingResult.getAllErrors());
return "student-edit";
}
if (id == null || id <= 0) {
studentService.addStudent(studentDto.getFirstName(), studentDto.getLastName());
} else {
studentService.updateStudent(id, studentDto.getFirstName(), studentDto.getLastName());
}
return "redirect:/student";
}
@PostMapping("/delete/{id}")
public String deleteStudent(@PathVariable Long id) {
studentService.deleteStudent(id);
return "redirect:/student";
}
}

@ -0,0 +1,69 @@
package ru.ulstu.is.sbapp.student.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.validation.constraints.NotBlank;
import java.util.Objects;
@Entity
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@NotBlank(message = "Firstname can't be null or empty")
private String firstName;
@NotBlank(message = "Lastname can't be null or empty")
private String lastName;
public Student() {
}
public Student(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public Long getId() {
return id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return Objects.equals(id, student.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
'}';
}
}

@ -0,0 +1,7 @@
package ru.ulstu.is.sbapp.student.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import ru.ulstu.is.sbapp.student.model.Student;
public interface StudentRepository extends JpaRepository<Student, Long> {
}

@ -0,0 +1,7 @@
package ru.ulstu.is.sbapp.student.service;
public class StudentNotFoundException extends RuntimeException {
public StudentNotFoundException(Long id) {
super(String.format("Student with id [%s] is not found", id));
}
}

@ -0,0 +1,61 @@
package ru.ulstu.is.sbapp.student.service;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ru.ulstu.is.sbapp.student.model.Student;
import ru.ulstu.is.sbapp.student.repository.StudentRepository;
import ru.ulstu.is.sbapp.util.validation.ValidatorUtil;
import java.util.List;
import java.util.Optional;
@Service
public class StudentService {
private final StudentRepository studentRepository;
private final ValidatorUtil validatorUtil;
public StudentService(StudentRepository studentRepository,
ValidatorUtil validatorUtil) {
this.studentRepository = studentRepository;
this.validatorUtil = validatorUtil;
}
@Transactional
public Student addStudent(String firstName, String lastName) {
final Student student = new Student(firstName, lastName);
validatorUtil.validate(student);
return studentRepository.save(student);
}
@Transactional(readOnly = true)
public Student findStudent(Long id) {
final Optional<Student> student = studentRepository.findById(id);
return student.orElseThrow(() -> new StudentNotFoundException(id));
}
@Transactional(readOnly = true)
public List<Student> findAllStudents() {
return studentRepository.findAll();
}
@Transactional
public Student updateStudent(Long id, String firstName, String lastName) {
final Student currentStudent = findStudent(id);
currentStudent.setFirstName(firstName);
currentStudent.setLastName(lastName);
validatorUtil.validate(currentStudent);
return studentRepository.save(currentStudent);
}
@Transactional
public Student deleteStudent(Long id) {
final Student currentStudent = findStudent(id);
studentRepository.delete(currentStudent);
return currentStudent;
}
@Transactional
public void deleteAllStudents() {
studentRepository.deleteAll();
}
}

@ -0,0 +1,26 @@
package ru.ulstu.is.sbapp.test.controller;
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 ru.ulstu.is.sbapp.configuration.WebConfiguration;
import ru.ulstu.is.sbapp.test.model.TestDto;
import ru.ulstu.is.sbapp.test.service.TestService;
import javax.validation.Valid;
@RestController
@RequestMapping(WebConfiguration.REST_API + "/test")
public class TestController {
private final TestService testService;
public TestController(TestService testService) {
this.testService = testService;
}
@PostMapping
public TestDto testValidation(@RequestBody @Valid TestDto testDto) {
return testService.doSomething(testDto);
}
}

@ -0,0 +1,41 @@
package ru.ulstu.is.sbapp.test.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import ru.ulstu.is.sbapp.test.model.TestDto;
import ru.ulstu.is.sbapp.test.service.TestService;
import javax.validation.Valid;
@Controller
@RequestMapping("/test")
public class TestMvcController {
private final TestService testService;
public TestMvcController(TestService testService) {
this.testService = testService;
}
@GetMapping
public String test(Model model) {
model.addAttribute("testDto", new TestDto());
return "test";
}
@PostMapping
public String testValidation(@ModelAttribute @Valid TestDto testDto,
BindingResult bindingResult,
Model model) {
if (bindingResult.hasErrors()) {
model.addAttribute("errors", bindingResult.getAllErrors());
return "test";
}
model.addAttribute("testDto", testService.doSomething(testDto));
return "test-result";
}
}

@ -0,0 +1,40 @@
package ru.ulstu.is.sbapp.test.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
public class TestDto {
@NotNull(message = "Id can't be null")
private Long id;
@NotBlank(message = "Name can't be null or empty")
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public String getData() {
return String.format("%s %s", id, name);
}
@JsonIgnore
public String getAnotherData() {
return "Test";
}
}

@ -0,0 +1,7 @@
package ru.ulstu.is.sbapp.test.service;
import ru.ulstu.is.sbapp.test.model.TestDto;
public interface TestService {
TestDto doSomething(TestDto testDto);
}

@ -0,0 +1,20 @@
package ru.ulstu.is.sbapp.test.service;
import org.springframework.context.annotation.Profile;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import ru.ulstu.is.sbapp.test.model.TestDto;
@Service
@Profile("dev")
public class TestServiceDevImpl extends TestServiceImpl {
public TestServiceDevImpl(Environment environment) {
super(environment);
}
@Override
public TestDto doSomething(TestDto testDto) {
log.info("TestServiceDevImpl.doSomething");
return testDto;
}
}

@ -0,0 +1,27 @@
package ru.ulstu.is.sbapp.test.service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.env.Environment;
import ru.ulstu.is.sbapp.test.model.TestDto;
abstract class TestServiceImpl implements TestService {
protected final Logger log = LoggerFactory.getLogger(TestServiceImpl.class);
protected final Environment environment;
TestServiceImpl(Environment environment) {
this.environment = environment;
printCurrentProfile();
}
private void printCurrentProfile() {
final String[] profiles = environment.getActiveProfiles().length == 0 ?
environment.getDefaultProfiles() :
environment.getActiveProfiles();
log.warn("Current profile is {}", String.join(", ", profiles));
}
@Override
abstract public TestDto doSomething(TestDto testDto);
}

@ -0,0 +1,20 @@
package ru.ulstu.is.sbapp.test.service;
import org.springframework.context.annotation.Profile;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import ru.ulstu.is.sbapp.test.model.TestDto;
@Service
@Profile("prod")
public class TestServiceProdImpl extends TestServiceImpl {
public TestServiceProdImpl(Environment environment) {
super(environment);
}
@Override
public TestDto doSomething(TestDto testDto) {
log.info("TestServiceProdImpl.doSomething");
return testDto;
}
}

@ -0,0 +1,42 @@
package ru.ulstu.is.sbapp.user.controller;
import org.springframework.data.domain.Page;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import ru.ulstu.is.sbapp.user.model.UserDto;
import ru.ulstu.is.sbapp.user.model.UserRole;
import ru.ulstu.is.sbapp.user.service.UserService;
import java.util.List;
import java.util.stream.IntStream;
@Controller
@RequestMapping("/users")
public class UserMvcController {
private final UserService userService;
public UserMvcController(UserService userService) {
this.userService = userService;
}
@GetMapping
@Secured({UserRole.AsString.ADMIN})
public String getUsers(@RequestParam(defaultValue = "1") int page,
@RequestParam(defaultValue = "5") int size,
Model model) {
final Page<UserDto> users = userService.findAllPages(page, size)
.map(UserDto::new);
model.addAttribute("users", users);
final int totalPages = users.getTotalPages();
final List<Integer> pageNumbers = IntStream.rangeClosed(1, totalPages)
.boxed()
.toList();
model.addAttribute("pages", pageNumbers);
model.addAttribute("totalPages", totalPages);
return "users";
}
}

@ -0,0 +1,51 @@
package ru.ulstu.is.sbapp.user.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import ru.ulstu.is.sbapp.user.model.User;
import ru.ulstu.is.sbapp.user.model.UserSignupDto;
import ru.ulstu.is.sbapp.user.service.UserService;
import ru.ulstu.is.sbapp.util.validation.ValidationException;
import javax.validation.Valid;
@Controller
@RequestMapping(UserSignupMvcController.SIGNUP_URL)
public class UserSignupMvcController {
public static final String SIGNUP_URL = "/signup";
private final UserService userService;
public UserSignupMvcController(UserService userService) {
this.userService = userService;
}
@GetMapping
public String showSignupForm(Model model) {
model.addAttribute("userDto", new UserSignupDto());
return "signup";
}
@PostMapping
public String signup(@ModelAttribute("userDto") @Valid UserSignupDto userSignupDto,
BindingResult bindingResult,
Model model) {
if (bindingResult.hasErrors()) {
model.addAttribute("errors", bindingResult.getAllErrors());
return "signup";
}
try {
final User user = userService.createUser(
userSignupDto.getLogin(), userSignupDto.getPassword(), userSignupDto.getPasswordConfirm());
return "redirect:/login?created=" + user.getLogin();
} catch (ValidationException e) {
model.addAttribute("errors", e.getMessage());
return "signup";
}
}
}

@ -0,0 +1,78 @@
package ru.ulstu.is.sbapp.user.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
import java.util.Objects;
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(nullable = false, unique = true, length = 64)
@NotBlank
@Size(min = 3, max = 64)
private String login;
@Column(nullable = false, length = 64)
@NotBlank
@Size(min = 6, max = 64)
private String password;
private UserRole role;
public User() {
}
public User(String login, String password) {
this(login, password, UserRole.USER);
}
public User(String login, String password, UserRole role) {
this.login = login;
this.password = password;
this.role = role;
}
public Long getId() {
return id;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public UserRole getRole() {
return role;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
return Objects.equals(id, user.id) && Objects.equals(login, user.login);
}
@Override
public int hashCode() {
return Objects.hash(id, login);
}
}

@ -0,0 +1,25 @@
package ru.ulstu.is.sbapp.user.model;
public class UserDto {
private final long id;
private final String login;
private final UserRole role;
public UserDto(User user) {
this.id = user.getId();
this.login = user.getLogin();
this.role = user.getRole();
}
public long getId() {
return id;
}
public String getLogin() {
return login;
}
public UserRole getRole() {
return role;
}
}

@ -0,0 +1,20 @@
package ru.ulstu.is.sbapp.user.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();
}
public static final class AsString {
public static final String ADMIN = PREFIX + "ADMIN";
public static final String USER = PREFIX + "USER";
}
}

@ -0,0 +1,40 @@
package ru.ulstu.is.sbapp.user.model;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
public class UserSignupDto {
@NotBlank
@Size(min = 3, max = 64)
private String login;
@NotBlank
@Size(min = 6, max = 64)
private String password;
@NotBlank
@Size(min = 6, max = 64)
private String passwordConfirm;
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPasswordConfirm() {
return passwordConfirm;
}
public void setPasswordConfirm(String passwordConfirm) {
this.passwordConfirm = passwordConfirm;
}
}

@ -0,0 +1,8 @@
package ru.ulstu.is.sbapp.user.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import ru.ulstu.is.sbapp.user.model.User;
public interface UserRepository extends JpaRepository<User, Long> {
User findOneByLoginIgnoreCase(String login);
}

@ -0,0 +1,67 @@
package ru.ulstu.is.sbapp.user.service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import ru.ulstu.is.sbapp.user.model.User;
import ru.ulstu.is.sbapp.user.model.UserRole;
import ru.ulstu.is.sbapp.user.repository.UserRepository;
import ru.ulstu.is.sbapp.util.validation.ValidationException;
import ru.ulstu.is.sbapp.util.validation.ValidatorUtil;
import java.util.Collections;
import java.util.Objects;
@Service
public class UserService implements UserDetailsService {
private final UserRepository userRepository;
private final PasswordEncoder passwordEncoder;
private final ValidatorUtil validatorUtil;
public UserService(UserRepository userRepository,
PasswordEncoder passwordEncoder,
ValidatorUtil validatorUtil) {
this.userRepository = userRepository;
this.passwordEncoder = passwordEncoder;
this.validatorUtil = validatorUtil;
}
public Page<User> findAllPages(int page, int size) {
return userRepository.findAll(PageRequest.of(page - 1, size, Sort.by("id").ascending()));
}
public User findByLogin(String login) {
return userRepository.findOneByLoginIgnoreCase(login);
}
public User createUser(String login, String password, String passwordConfirm) {
return createUser(login, password, passwordConfirm, UserRole.USER);
}
public User createUser(String login, String password, String passwordConfirm, UserRole role) {
if (findByLogin(login) != null) {
throw new ValidationException(String.format("User '%s' already exists", login));
}
final User user = new User(login, passwordEncoder.encode(password), role);
validatorUtil.validate(user);
if (!Objects.equals(password, passwordConfirm)) {
throw new ValidationException("Passwords not equals");
}
return userRepository.save(user);
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
final User userEntity = findByLogin(username);
if (userEntity == null) {
throw new UsernameNotFoundException(username);
}
return new org.springframework.security.core.userdetails.User(
userEntity.getLogin(), userEntity.getPassword(), Collections.singleton(userEntity.getRole()));
}
}

@ -0,0 +1,39 @@
package ru.ulstu.is.sbapp.util.error;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import ru.ulstu.is.sbapp.student.service.StudentNotFoundException;
import ru.ulstu.is.sbapp.util.validation.ValidationException;
import java.util.stream.Collectors;
@ControllerAdvice(annotations = RestController.class)
public class AdviceController {
@ExceptionHandler({
StudentNotFoundException.class,
ValidationException.class
})
public ResponseEntity<Object> handleException(Throwable e) {
return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<Object> handleBindException(MethodArgumentNotValidException e) {
final ValidationException validationException = new ValidationException(
e.getBindingResult().getAllErrors().stream()
.map(DefaultMessageSourceResolvable::getDefaultMessage)
.collect(Collectors.toSet()));
return handleException(validationException);
}
@ExceptionHandler(Exception.class)
public ResponseEntity<Object> handleUnknownException(Throwable e) {
e.printStackTrace();
return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}

@ -0,0 +1,13 @@
package ru.ulstu.is.sbapp.util.validation;
import java.util.Set;
public class ValidationException extends RuntimeException {
public <T> ValidationException(Set<String> errors) {
super(String.join("\n", errors));
}
public <T> ValidationException(String error) {
super(error);
}
}

@ -0,0 +1,27 @@
package ru.ulstu.is.sbapp.util.validation;
import org.springframework.stereotype.Component;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;
import java.util.stream.Collectors;
@Component
public class ValidatorUtil {
private final Validator validator;
public ValidatorUtil() {
this.validator = Validation.buildDefaultValidatorFactory().getValidator();
}
public <T> void validate(T object) {
final Set<ConstraintViolation<T>> errors = validator.validate(object);
if (!errors.isEmpty()) {
throw new ValidationException(errors.stream()
.map(ConstraintViolation::getMessage)
.collect(Collectors.toSet()));
}
}
}

@ -0,0 +1,9 @@
# JPA
spring.datasource.url=jdbc:h2:file:./data
spring.datasource.username=sa
spring.datasource.password=password
spring.datasource.driverClassName=org.h2.Driver
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.h2.console.enabled=true
spring.h2.console.settings.trace=false
spring.h2.console.settings.web-allow-others=false

@ -0,0 +1,7 @@
# Dev tools
spring.devtools.add-properties=false
# JPA
spring.datasource.url=jdbc:postgresql://127.0.0.1:5432/sbapp
spring.datasource.username=postgres
spring.datasource.password=postgres
spring.datasource.driverclassName=org.postgresql.Driver

@ -0,0 +1,11 @@
# Server
spring.main.banner-mode=off
server.port=8080
# Profiles
spring.profiles.default=dev
# JPA
spring.jpa.hibernate.ddl-auto=validate
# Liquibase Settings
spring.liquibase.enabled=true
spring.liquibase.drop-first=false
spring.liquibase.change-log=classpath:migrations/changelog-master.yml

@ -0,0 +1,13 @@
databaseChangeLog:
- include:
file: migrations/student/student-schema-1.yml
- include:
file: migrations/user/user-schema-1.yml
- include:
file: migrations/user/user-data-1.yml
- include:
file: migrations/user/user-schema-2.yml
- include:
file: migrations/user/user-data-2.yml
- include:
file: migrations/user/user-schema-3.yml

@ -0,0 +1,24 @@
databaseChangeLog:
- changeSet:
id: 2022-04-01-schema-1
author: user
changes:
- createTable:
tableName: student
columns:
- column:
name: id
type: bigint
constraints:
primaryKey: true
nullable: false
- column:
name: first_name
type: varchar(255)
constraints:
nullable: false
- column:
name: last_name
type: varchar(255)
constraints:
nullable: false

@ -0,0 +1,17 @@
databaseChangeLog:
- changeSet:
id: 2022-04-15-data-1
author: user
changes:
- insert:
tableName: users
columns:
- column:
name: id
value: 1
- column:
name: login
value: admin
- column:
name: password
value: $2a$10$WZg1ajfZBi1wqecE85yV..sfw8Fj9z1ZzRBszlDbNn97EKlD2jfsC

@ -0,0 +1,7 @@
databaseChangeLog:
- changeSet:
id: 2022-05-01-data-2
author: user
changes:
- sql:
sql: update users set role=0 where id = 1

@ -0,0 +1,28 @@
databaseChangeLog:
- changeSet:
id: 2022-04-15-schema-1
author: user
changes:
- createTable:
tableName: users
columns:
- column:
name: id
type: bigint
constraints:
primaryKey: true
nullable: false
- column:
name: login
type: varchar(64)
constraints:
nullable: false
unique: true
- column:
name: password
type: varchar(64)
constraints:
nullable: false
- createSequence:
sequenceName: hibernate_sequence
startValue: 10

@ -0,0 +1,11 @@
databaseChangeLog:
- changeSet:
id: 2022-05-01-schema-1
author: user
changes:
- addColumn:
tableName: users
columns:
- column:
name: role
type: int

@ -0,0 +1,8 @@
databaseChangeLog:
- changeSet:
id: 2022-05-01-schema-3
author: user
changes:
- addNotNullConstraint:
tableName: users
columnName: role

@ -0,0 +1,32 @@
.container-padding {
padding: 10px;
}
.margin-bottom {
margin-bottom: 10px;
}
.button-fixed {
min-width: 140px;
}
.button-sm {
padding: 1px;
}
.pagination {
display: inline-block;
}
.pagination a {
color: black;
float: left;
padding: 5px 5px;
text-decoration: none;
}
.pagination a.active {
background-color: gray;
color: white;
border-radius: 2px;
}

@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 448 512"><!--! Font Awesome Pro 6.1.1 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license (Commercial License) Copyright 2022 Fonticons, Inc. -->
<path d="M448 48V384c-63.09 22.54-82.34 32-119.5 32c-62.82 0-86.6-32-149.3-32C158.6 384 142.6 387.6 128 392.2v-64C142.6 323.6 158.6 320 179.2 320c62.73 0 86.51 32 149.3 32C348.9 352 364.1 349 384 342.7v-208C364.1 141 348.9 144 328.5 144c-62.82 0-86.6-32-149.3-32C128.4 112 104.3 132.6 64 140.7v307.3C64 465.7 49.67 480 32 480S0 465.7 0 448V63.1C0 46.33 14.33 32 31.1 32S64 46.33 64 63.1V76.66C104.3 68.63 128.4 48 179.2 48c62.73 0 86.51 32 149.3 32C365.7 80 384.9 70.54 448 48z"/>
</svg>

After

Width:  |  Height:  |  Size: 727 B

@ -0,0 +1,63 @@
<!DOCTYPE html>
<html lang="ru"
xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5">
<head>
<meta charset="UTF-8"/>
<title>IP Example</title>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<link rel="icon" href="/favicon.svg">
<script type="text/javascript" src="/webjars/bootstrap/5.1.3/js/bootstrap.bundle.min.js"></script>
<link rel="stylesheet" href="/webjars/bootstrap/5.1.3/css/bootstrap.min.css"/>
<link rel="stylesheet" href="/webjars/font-awesome/6.1.0/css/all.min.css"/>
<link rel="stylesheet" href="/css/style.css"/>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container-fluid">
<a class="navbar-brand" href="/">
<i class="fa-solid fa-font-awesome"></i>
IP Example
</a>
<button class="navbar-toggler" type="button"
data-bs-toggle="collapse" data-bs-target="#navbarNav"
aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav" th:with="activeLink=${#request.requestURI}" sec:authorize="isAuthenticated()">
<a class="nav-link" href="/"
th:classappend="${#strings.equals(activeLink, '/')} ? 'active' : ''">Главная</a>
<a class="nav-link" href="/speaker"
th:classappend="${#strings.equals(activeLink, '/speaker')} ? 'active' : ''">Пример Speaker</a>
<a class="nav-link" href="/test"
th:classappend="${#strings.equals(activeLink, '/test')} ? 'active' : ''">Пример Test</a>
<a class="nav-link" href="/student"
th:classappend="${#strings.equals(activeLink, '/student')} ? 'active' : ''">Пример Student</a>
<a class="nav-link" href="/rest-test"
th:classappend="${#strings.equals(activeLink, '/rest-test')} ? 'active' : ''">
Пример запроса к REST API
</a>
<a sec:authorize="hasRole('ROLE_ADMIN')" class="nav-link" href="/users"
th:classappend="${#strings.equals(activeLink, '/users')} ? 'active' : ''">Пользователи</a>
<a class="nav-link" href="/swagger-ui/index.html" target="_blank">Документация REST API</a>
<a class="nav-link" href="/h2-console/" target="_blank"
th:if="${#arrays.contains(@environment.getActiveProfiles(),'dev')}">
Консоль H2
</a>
<a class="nav-link" href="/logout">
Выход (<span th:text="${#authentication.name}"></span>)
</a>
</ul>
</div>
</div>
</nav>
<div class="container-fluid">
<div class="container container-padding" layout:fragment="content">
</div>
</div>
</body>
<th:block layout:fragment="scripts">
</th:block>
</html>

@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}">
<body>
<div class="container" layout:fragment="content">
<div class="alert alert-danger">
<span th:text="${error}"></span>
</div>
<a href="/">На главную</a>
</div>
</body>
</html>

@ -0,0 +1,11 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}">
<body>
<div class="container" layout:fragment="content">
<div>It's works!</div>
<a href="123">ERROR</a>
</div>
</body>
</html>

@ -0,0 +1,30 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}">
<body>
<div class="container" layout:fragment="content">
<div th:if="${param.error}" class="alert alert-danger margin-bottom">
Пользователь не найден или пароль указан не верно
</div>
<div th:if="${param.logout}" class="alert alert-success margin-bottom">
Выход успешно произведен
</div>
<div th:if="${param.created}" class="alert alert-success margin-bottom">
Пользователь '<span th:text="${param.created}"></span>' успешно создан
</div>
<form th:action="@{/login}" method="post" class="container-padding">
<div class="mb-3">
<input type="text" name="username" id="username" class="form-control"
placeholder="Логин" required="true" autofocus="true"/>
</div>
<div class="mb-3">
<input type="password" name="password" id="password" class="form-control"
placeholder="Пароль" required="true"/>
</div>
<button type="submit" class="btn btn-success button-fixed">Войти</button>
<a class="btn btn-primary button-fixed" href="/signup">Регистрация</a>
</form>
</div>
</body>
</html>

@ -0,0 +1,47 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}">
<head>
<script type="text/javascript" src="/webjars/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<div class="container" layout:fragment="content">
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">ID</th>
<th scope="col">Имя</th>
</tr>
</thead>
<tbody id="students">
</tbody>
</table>
</div>
</div>
</body>
<th:block layout:fragment="scripts">
<script>
$(document).ready(function () {
$.ajax({
url: "http://localhost:8080/api/student/"
}).then(function (data) {
$.each(data, function (index, value) {
const row = $("<tr>");
const number = $("<th>")
.attr("scope", "row")
.text(index + 1);
const id = $("<td>").text(value.id);
const name = $("<td>").text(value.firstName + ' ' + value.lastName);
row.append(number);
row.append(id);
row.append(name);
$("#students").append(row);
});
});
});
</script>
</th:block>
</html>

@ -0,0 +1,28 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}">
<body>
<div class="container container-padding" layout:fragment="content">
<div th:if="${errors}" th:text="${errors}" class="margin-bottom alert alert-danger"></div>
<form action="#" th:action="@{/signup}" th:object="${userDto}" method="post">
<div class="mb-3">
<input type="text" class="form-control" th:field="${userDto.login}"
placeholder="Логин" required="true" autofocus="true" maxlength="64"/>
</div>
<div class="mb-3">
<input type="password" class="form-control" th:field="${userDto.password}"
placeholder="Пароль" required="true" minlength="6" maxlength="64"/>
</div>
<div class="mb-3">
<input type="password" class="form-control" th:field="${userDto.passwordConfirm}"
placeholder="Пароль (подтверждение)" required="true" minlength="6" maxlength="64"/>
</div>
<div class="mb-3">
<button type="submit" class="btn btn-success button-fixed">Создать</button>
<a class="btn btn-primary button-fixed" href="/login">Назад</a>
</div>
</form>
</div>
</body>
</html>

@ -0,0 +1,25 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}">
<body>
<div class="container" layout:fragment="content">
<p th:text="${say}"></p>
<form action="#" th:action="@{/speaker}" method="get">
<div class="mb-3">
<label for="name" class="form-label">Имя</label>
<input type="text" class="form-control" id="name" th:name="name" th:value="${name}" required="true">
</div>
<div class="mb-3">
<label for="lang" class="form-label">Язык</label>
<select id="lang" class="form-select" th:name="lang">
<option th:each="value: ${langs}" th:selected="${lang} == ${value}">
<span th:text="${value}"></span>
</option>
</select>
</div>
<button type="submit" class="btn btn-primary">Отправить</button>
</form>
</div>
</body>
</html>

@ -0,0 +1,29 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}">
<body>
<div class="container" layout:fragment="content">
<div th:if="${errors}" th:text="${errors}" class="margin-bottom alert alert-danger"></div>
<form action="#" th:action="@{/student/edit/{id}(id=${id})}" th:object="${studentDto}" method="post">
<div class="mb-3">
<label for="firstName" class="form-label">Имя</label>
<input type="text" class="form-control" id="firstName" th:field="${studentDto.firstName}" required="true">
</div>
<div class="mb-3">
<label for="lastName" class="form-label">Фамилия</label>
<input type="text" class="form-control" id="lastName" th:field="${studentDto.lastName}" required="true">
</div>
<div class="mb-3">
<button type="submit" class="btn btn-primary button-fixed">
<span th:if="${id == null}">Добавить</span>
<span th:if="${id != null}">Обновить</span>
</button>
<a class="btn btn-secondary button-fixed" href="/student">
Назад
</a>
</div>
</form>
</div>
</body>
</html>

@ -0,0 +1,50 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}">
<body>
<div class="container" layout:fragment="content">
<div>
<a class="btn btn-success button-fixed" href="/student/edit/">
<i class="fa-solid fa-plus"></i> Добавить
</a>
</div>
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">ID</th>
<th scope="col">Имя</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
<tr th:each="student, iterator: ${students}">
<th scope="row" th:text="${iterator.index} + 1"></th>
<td th:text="${student.id}"></td>
<td th:text="${student.firstName} + ' ' + ${student.lastName}" style="width: 60%"></td>
<td style="width: 10%">
<div class="btn-group" role="group" aria-label="Basic example">
<a class="btn btn-warning button-fixed button-sm"
th:href="@{/student/edit/{id}(id=${student.id})}">
<i class="fa fa-pencil" aria-hidden="true"></i> Изменить
</a>
<button type="button" class="btn btn-danger button-fixed button-sm"
th:attr="onclick=|confirm('Удалить запись?') && document.getElementById('remove-${student.id}').click()|">
<i class="fa fa-trash" aria-hidden="true"></i> Удалить
</button>
</div>
<form th:action="@{/student/delete/{id}(id=${student.id})}" method="post">
<button th:id="'remove-' + ${student.id}" type="submit" style="display: none">
Удалить
</button>
</form>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</body>
</html>

@ -0,0 +1,24 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}">
<body>
<div class="container" layout:fragment="content">
<div class="mb-3">
<label for="id" class="form-label">ID</label>
<input type="text" class="form-control" id="id" th:value="${testDto.id}" readonly="readonly">
</div>
<div class="mb-3">
<label for="name" class="form-label">Имя</label>
<input type="text" class="form-control" id="name" th:value="${testDto.name}" readonly="readonly">
</div>
<div class="mb-3">
<label for="data" class="form-label">Данные</label>
<input type="text" class="form-control" id="data" th:value="${testDto.data}" readonly="readonly">
</div>
<div>
<a href="/test">Повторить ввод</a>
</div>
</div>
</body>
</html>

@ -0,0 +1,21 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}">
<body>
<div class="container" layout:fragment="content">
<div th:if="${errors}" th:text="${errors}" class="margin-bottom alert alert-danger"></div>
<form action="#" th:action="@{/test}" th:object="${testDto}" method="post">
<div class="mb-3">
<label for="id" class="form-label">ID</label>
<input type="text" class="form-control" id="id" th:field="${testDto.id}" required="true">
</div>
<div class="mb-3">
<label for="name" class="form-label">Имя</label>
<input type="text" class="form-control" id="name" th:field="${testDto.name}" required="true">
</div>
<button type="submit" class="btn btn-primary">Отправить</button>
</form>
</div>
</body>
</html>

@ -0,0 +1,36 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}">
<body>
<div class="container" layout:fragment="content">
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">ID</th>
<th scope="col">Логин</th>
<th scope="col">Роль</th>
</tr>
</thead>
<tbody>
<tr th:each="user, iterator: ${users}">
<th scope="row" th:text="${iterator.index} + 1"></th>
<td th:text="${user.id}"></td>
<td th:text="${user.login}" style="width: 60%"></td>
<td th:text="${user.role}" style="width: 20%"></td>
</tr>
</tbody>
</table>
</div>
<div th:if="${totalPages > 0}" class="pagination">
<span style="float: left; padding: 5px 5px;">Страницы:</span>
<a th:each="page : ${pages}"
th:href="@{/users(page=${page}, size=${users.size})}"
th:text="${page}"
th:class="${page == users.number + 1} ? active"></a>
</div>
</div>
</body>
</html>
Loading…
Cancel
Save