hello world

This commit is contained in:
sardq 2024-06-07 21:11:19 +04:00
parent a72377bd98
commit 639e1e42dd
192 changed files with 10423 additions and 0 deletions

37
1 lab/.gitignore vendored Normal file
View File

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

27
1 lab/build.gradle Normal file
View File

@ -0,0 +1,27 @@
plugins {
id 'java'
id 'org.springframework.boot' version '3.2.2'
id 'io.spring.dependency-management' version '1.1.4'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
java {
sourceCompatibility = '17'
}
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.3.0'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
tasks.named('test') {
useJUnitPlatform()
}

BIN
1 lab/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
1 lab/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
1 lab/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

64
1 lab/index.html Normal file
View File

@ -0,0 +1,64 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<p id="out">Push the button</p>
<input id="name" />
<br />
<button onclick="get()">Get</button>
<br />
<button onclick="getTest()">Get Test</button>
<br />
<button onclick="post()">Post</button>
<br />
<button onclick="put()">Put</button>
</body>
<script>
const url = "http://localhost:8080/messages";
const out = document.getElementById("out");
const name = document.getElementById("name");
const get = async () => {
const res = await fetch(`${url}?name=${name.value}`);
const text = await res.text();
out.innerText = text;
}
const getTest = async () => {
const res = await fetch(`${url}/test`);
const text = await res.text();
out.innerText = text;
}
const post = async () => {
if (!name.value) {
alert("Name is required");
return;
}
const res = await fetch(url, {
method: 'post',
headers: { 'Content-Type': 'application/json' },
body: name.value
});
const text = await res.text();
out.innerText = text;
}
const put = async () => {
if (!name.value) {
alert("Name is required");
return;
}
const res = await fetch(`${url}/${name.value}`, {
method: 'put',
headers: { 'Content-Type': 'application/json' },
body: name.value
});
const text = await res.text();
out.innerText = text;
}
</script>
</html>

1
1 lab/settings.gradle Normal file
View File

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

View File

@ -0,0 +1,54 @@
package com.example.demo;
import java.util.ArrayList;
import java.util.List;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
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 jakarta.validation.Valid;
@RestController
@RequestMapping("/message")
public class ApiController {
// private final Logger log = LoggerFactory.getLogger(ApiController.class);
public List<UserDto> dataList = new ArrayList<UserDto>();
@PostMapping
public UserDto create(@RequestBody @Valid UserDto testDto) {
dataList.add(testDto);
return testDto;
}
@GetMapping
public List<UserDto> readAll() {
return dataList;
}
@GetMapping("{id}")
public UserDto read(@PathVariable(name = "id") int id) {
return dataList.get(id);
}
@PutMapping("/{id}")
public UserDto update(@PathVariable Integer id, @RequestBody UserDto testDto) {
dataList.set(id, testDto);
return testDto;
}
@DeleteMapping("/{id}")
public UserDto delete(@PathVariable(name = "id") int id) {
UserDto temp = dataList.remove(id);
return temp;
}
}

View File

@ -0,0 +1,12 @@
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}

View File

@ -0,0 +1,43 @@
package com.example.demo;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
public class UserDto {
private Integer groupId;
private Integer senderId;
private String msg;
private String time;
public UserDto() {
}
@JsonCreator
public UserDto(
@JsonProperty(value = "groupId") Integer groupId,
@JsonProperty(value = "senderId") Integer senderId,
@JsonProperty(value = "msg") String msg,
@JsonProperty(value = "time") String time) {
this.groupId = groupId;
this.senderId = senderId;
this.msg = msg;
this.time = time;
}
public Integer getGroupId() {
return groupId;
}
public Integer getSenderId() {
return senderId;
}
public String getMsg() {
return msg;
}
public String getTime() {
return time;
}
}

View File

@ -0,0 +1,15 @@
package com.example.demo;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.NonNull;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(@NonNull CorsRegistry registry) {
registry.addMapping("/**")
.allowedMethods("GET", "POST", "PUT", "DELETE");
}
}

View File

@ -0,0 +1 @@

View File

@ -0,0 +1,13 @@
package com.example.demo;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class DemoApplicationTests {
@Test
void contextLoads() {
}
}

37
2 lab/.gitignore vendored Normal file
View File

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

View File

BIN
2 lab/.vs/IP/v17/.wsuo Normal file

Binary file not shown.

View File

@ -0,0 +1,3 @@
{
"CurrentProjectSetting": null
}

View File

@ -0,0 +1,7 @@
{
"ExpandedNodes": [
""
],
"SelectedNode": "\\.gitignore",
"PreviewInSolutionExplorer": false
}

BIN
2 lab/.vs/slnx.sqlite Normal file

Binary file not shown.

28
2 lab/build.gradle Normal file
View File

@ -0,0 +1,28 @@
plugins {
id 'java'
id 'org.springframework.boot' version '3.2.3'
id 'io.spring.dependency-management' version '1.1.4'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
java {
sourceCompatibility = '17'
}
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.3.0'
implementation 'org.modelmapper:modelmapper:3.2.0'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
tasks.named('test') {
useJUnitPlatform()
}

BIN
2 lab/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
2 lab/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
2 lab/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

1
2 lab/settings.gradle Normal file
View File

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

View File

@ -0,0 +1,85 @@
package com.example.demo;
import java.sql.Time;
import java.util.ArrayList;
import java.util.Objects;
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 java.util.List;
import com.example.demo.comments.model.CommentEntity;
import com.example.demo.comments.service.CommentService;
import com.example.demo.messages.model.MessageEntity;
import com.example.demo.messages.service.MessageService;
import com.example.demo.posts.model.PostEntity;
import com.example.demo.posts.service.PostService;
import com.example.demo.users.model.UserEntity;
import com.example.demo.users.service.UserService;
@SpringBootApplication
public class DemoApplication implements CommandLineRunner {
private final Logger log = LoggerFactory.getLogger(DemoApplication.class);
private final UserService userService;
private final PostService postService;
private final CommentService commentService;
private final MessageService messageService;
public DemoApplication(UserService userService, PostService postService, CommentService commentService,
MessageService messageService) {
this.userService = userService;
this.postService = postService;
this.commentService = commentService;
this.messageService = messageService;
}
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
if (args.length > 0 && Objects.equals("--populate", args[0])) {
log.info("Create default items values");
final List<UserEntity> blank = new ArrayList<UserEntity>();
final var user1 = userService.create(new UserEntity(null, "sardq", "aasd@asd", "asdsd", blank));
final var user2 = userService.create(new UserEntity(null, "sardasdq", "aasdsad@asd", "123", blank));
final List<UserEntity> friends = new ArrayList<>();
friends.add(user1);
friends.add(user2);
final var user3 = userService.create(new UserEntity(null, "sxzcvardq", "aaxsd@asd", "asfgd", friends));
final var user4 = userService.create(new UserEntity(null, "sarbvljdq", "aacbxcsd@asd", "zxvb", blank));
log.info("Create default posts values");
final var post1 = postService.create(
new PostEntity(null, user1, new Time(System.currentTimeMillis()), "test", Long.valueOf(0),
Long.valueOf(0)));
final var post2 = postService.create(
new PostEntity(null, user3, new Time(System.currentTimeMillis()), "test", Long.valueOf(11),
Long.valueOf(2)));
final var post3 = postService.create(
new PostEntity(null, user4, new Time(System.currentTimeMillis()), "test", Long.valueOf(40),
Long.valueOf(15)));
log.info("Create default comments values");
commentService
.create(new CommentEntity(null, user1, post2, new Time(System.currentTimeMillis()), "my comment"));
commentService
.create(new CommentEntity(null, user3, post1, new Time(System.currentTimeMillis()), "my comment2"));
commentService
.create(new CommentEntity(null, user4, post3, new Time(System.currentTimeMillis()), "my comment3"));
log.info("Create default messages values");
messageService.create(new MessageEntity(null, user1, user2, new Time(System.currentTimeMillis()), "hello"));
messageService
.create(new MessageEntity(null, user1, user2, new Time(System.currentTimeMillis()), "how are you"));
messageService
.create(new MessageEntity(null, user2, user1, new Time(System.currentTimeMillis()), "I'm ok"));
}
}
}

View File

@ -0,0 +1,78 @@
package com.example.demo.comments.api;
import java.util.List;
import org.modelmapper.ModelMapper;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.comments.model.CommentEntity;
import com.example.demo.comments.service.CommentService;
import com.example.demo.core.convert;
import com.example.demo.core.configuration.Constants;
import com.example.demo.posts.service.PostService;
import com.example.demo.users.service.UserService;
import jakarta.validation.Valid;
@RestController
@RequestMapping(Constants.API_URL + "/comment")
public class CommentController {
private final UserService userService;
private final PostService postService;
private final CommentService commentService;
private final ModelMapper modelMapper;
public CommentController(CommentService commentService, UserService userService, PostService postService,
ModelMapper modelMapper) {
this.userService = userService;
this.commentService = commentService;
this.postService = postService;
this.modelMapper = modelMapper;
}
private CommentDto toDto(CommentEntity entity) {
var model = modelMapper.map(entity, CommentDto.class);
convert time = new convert();
model.setTime(time.dateToString(entity.getTime()));
return model;
}
private CommentEntity toEntity(CommentDto dto) {
final CommentEntity entity = modelMapper.map(dto, CommentEntity.class);
entity.setUser(userService.get(dto.getUserId()));
entity.setPost(postService.get(dto.getPostId()));
return entity;
}
@GetMapping
public List<CommentDto> getAll() {
return commentService.getAll().stream().map(this::toDto).toList();
}
@GetMapping("/{id}")
public CommentDto get(@PathVariable(name = "id") Long id) {
return toDto(commentService.get(id));
}
@PostMapping
public CommentDto create(@RequestBody @Valid CommentDto dto) {
return toDto(commentService.create(toEntity(dto)));
}
@PutMapping("/{id}")
public CommentDto update(@PathVariable(name = "id") Long id, @RequestBody CommentDto dto) {
return toDto(commentService.update(id, toEntity(dto)));
}
@DeleteMapping("/{id}")
public CommentDto delete(@PathVariable(name = "id") Long id) {
return toDto(commentService.delete(id));
}
}

View File

@ -0,0 +1,62 @@
package com.example.demo.comments.api;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
public class CommentDto {
private Long id;
@NotNull
@Min(1)
private Long userId;
@NotBlank
private String text;
@NotNull
@Min(1)
private Long postId;
@NotBlank
private String time;
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
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 getPostId() {
return postId;
}
public void setPostId(Long postId) {
this.postId = postId;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
}

View File

@ -0,0 +1,78 @@
package com.example.demo.comments.model;
import java.util.Date;
import java.util.Objects;
import com.example.demo.core.model.BaseEntity;
import com.example.demo.posts.model.PostEntity;
import com.example.demo.users.model.UserEntity;
public class CommentEntity extends BaseEntity {
private UserEntity user;
private PostEntity post;
private Date time;
private String text;
public CommentEntity() {
super();
}
public CommentEntity(Long id, UserEntity user, PostEntity post, Date time, String text) {
super(id);
this.user = user;
this.post = post;
this.time = time;
this.text = text;
}
public UserEntity getUser() {
return user;
}
public void setUser(UserEntity user) {
this.user = user;
}
public PostEntity getPost() {
return post;
}
public void setPost(PostEntity post) {
this.post = post;
}
public Date getTime() {
return time;
}
public void setTime(Date time) {
this.time = time;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
@Override
public int hashCode() {
return Objects.hash(id, user, post, text, time);
}
@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(), id)
&& Objects.equals(other.getUser(), user)
&& Objects.equals(other.getPost(), post)
&& Objects.equals(other.getText(), text)
&& Objects.equals(other.getTime(), time);
}
}

View File

@ -0,0 +1,10 @@
package com.example.demo.comments.repository;
import org.springframework.stereotype.Repository;
import com.example.demo.comments.model.CommentEntity;
import com.example.demo.core.repository.MapRepository;
@Repository
public class CommentRepository extends MapRepository<CommentEntity> {
}

View File

@ -0,0 +1,43 @@
package com.example.demo.comments.service;
import java.util.List;
import java.util.Optional;
import org.springframework.stereotype.Service;
import com.example.demo.comments.model.CommentEntity;
import com.example.demo.comments.repository.CommentRepository;
import com.example.demo.core.error.NotFoundException;
@Service
public class CommentService {
private final CommentRepository repository;
public CommentService(CommentRepository repository) {
this.repository = repository;
}
public List<CommentEntity> getAll() {
return repository.getAll();
}
public CommentEntity get(Long id) {
return Optional.ofNullable(repository.get(id))
.orElseThrow(() -> new NotFoundException(id));
}
public CommentEntity create(CommentEntity entity) {
return repository.create(entity);
}
public CommentEntity update(Long id, CommentEntity entity) {
final CommentEntity existsEntity = get(id);
existsEntity.setText(entity.getText());
return repository.update(existsEntity);
}
public CommentEntity delete(Long id) {
final CommentEntity existsEntity = get(id);
return repository.delete(existsEntity);
}
}

View File

@ -0,0 +1,8 @@
package com.example.demo.core.configuration;
public class Constants {
public static final String API_URL = "/api/1.0";
private Constants() {
}
}

View File

@ -0,0 +1,13 @@
package com.example.demo.core.configuration;
import org.modelmapper.ModelMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MapperConfiguration {
@Bean
ModelMapper modelMapper() {
return new ModelMapper();
}
}

View File

@ -0,0 +1,15 @@
package com.example.demo.core.configuration;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.NonNull;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfiguration implements WebMvcConfigurer {
@Override
public void addCorsMappings(@NonNull CorsRegistry registry) {
registry.addMapping("/**")
.allowedMethods("GET", "POST", "PUT", "DELETE");
}
}

View File

@ -0,0 +1,17 @@
package com.example.demo.core;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class convert {
public Date stringToDate(String string) throws Exception {
DateFormat format = new SimpleDateFormat("HH:mm:ss");
return (Date) format.parse(string);
}
public String dateToString(Date date) {
DateFormat dateFormat = new SimpleDateFormat("dd.MM.YYYY hh:mm:ss");
return dateFormat.format(date);
}
}

View File

@ -0,0 +1,7 @@
package com.example.demo.core.error;
public class NotFoundException extends RuntimeException {
public NotFoundException(Long id) {
super(String.format("Entity with id [%s] is not found or not exists", id));
}
}

View File

@ -0,0 +1,20 @@
package com.example.demo.core.model;
public abstract class BaseEntity {
protected Long id;
protected BaseEntity() {
}
protected BaseEntity(Long id) {
this.id = id;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}

View File

@ -0,0 +1,17 @@
package com.example.demo.core.repository;
import java.util.List;
public interface CommonRepository<E, T> {
List<E> getAll();
E get(T id);
E create(E entity);
E update(E entity);
E delete(E entity);
void deleteAll();
}

View File

@ -0,0 +1,57 @@
package com.example.demo.core.repository;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import com.example.demo.core.model.BaseEntity;
public abstract class MapRepository<E extends BaseEntity> implements CommonRepository<E, Long> {
private final Map<Long, E> entities = new TreeMap<>();
private Long lastId = 0L;
protected MapRepository() {
}
@Override
public List<E> getAll() {
return entities.values().stream().toList();
}
@Override
public E get(Long id) {
return entities.get(id);
}
@Override
public E create(E entity) {
lastId++;
entity.setId(lastId);
entities.put(lastId, entity);
return entity;
}
@Override
public E update(E entity) {
if (get(entity.getId()) == null) {
return null;
}
entities.put(entity.getId(), entity);
return entity;
}
@Override
public E delete(E entity) {
if (get(entity.getId()) == null) {
return null;
}
entities.remove(entity.getId());
return entity;
}
@Override
public void deleteAll() {
lastId = 0L;
entities.clear();
}
}

View File

@ -0,0 +1,75 @@
package com.example.demo.messages.api;
import java.util.List;
import org.modelmapper.ModelMapper;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.core.convert;
import com.example.demo.core.configuration.Constants;
import com.example.demo.messages.model.MessageEntity;
import com.example.demo.messages.service.MessageService;
import com.example.demo.users.service.UserService;
import jakarta.validation.Valid;
@RestController
@RequestMapping(Constants.API_URL + "/message")
public class MessageController {
private final UserService userService;
private final MessageService messageService;
private final ModelMapper modelMapper;
public MessageController(MessageService messageService, UserService userService, ModelMapper modelMapper) {
this.messageService = messageService;
this.userService = userService;
this.modelMapper = modelMapper;
}
private MessageDto toDto(MessageEntity entity) {
var model = modelMapper.map(entity, MessageDto.class);
convert time = new convert();
model.setTime(time.dateToString(entity.getTime()));
return model;
}
private MessageEntity toEntity(MessageDto dto) {
final MessageEntity entity = modelMapper.map(dto, MessageEntity.class);
entity.setFriend(userService.get(dto.getFriendId()));
entity.setPerson(userService.get(dto.getPersonId()));
return entity;
}
@GetMapping
public List<MessageDto> getAll() {
return messageService.getAll().stream().map(this::toDto).toList();
}
@GetMapping("/{id}")
public MessageDto get(@PathVariable(name = "id") Long id) {
return toDto(messageService.get(id));
}
@PostMapping
public MessageDto create(@RequestBody @Valid MessageDto dto) {
return toDto(messageService.create(toEntity(dto)));
}
@PutMapping("/{id}")
public MessageDto update(@PathVariable(name = "id") Long id, @RequestBody MessageDto dto) {
return toDto(messageService.update(id, toEntity(dto)));
}
@DeleteMapping("/{id}")
public MessageDto delete(@PathVariable(name = "id") Long id) {
return toDto(messageService.delete(id));
}
}

View File

@ -0,0 +1,62 @@
package com.example.demo.messages.api;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
public class MessageDto {
private Long id;
@NotNull
@Min(1)
private Long friendId;
@NotNull
@Min(1)
private Long personId;
@NotBlank
private String text;
@NotBlank
private String time;
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getPersonId() {
return personId;
}
public void setPersonId(Long personId) {
this.personId = personId;
}
public Long getFriendId() {
return friendId;
}
public void setFriendId(Long friendId) {
this.friendId = friendId;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}

View File

@ -0,0 +1,78 @@
package com.example.demo.messages.model;
import java.util.Date;
import java.util.Objects;
import com.example.demo.core.model.BaseEntity;
import com.example.demo.users.model.UserEntity;
public class MessageEntity extends BaseEntity {
private UserEntity person;
private UserEntity friend;
private Date time;
private String text;
public MessageEntity() {
super();
}
public MessageEntity(Long id, UserEntity person, UserEntity friend, Date time, String text) {
super(id);
this.person = person;
this.friend = friend;
this.text = text;
this.time = time;
}
public UserEntity getFriend() {
return friend;
}
public void setFriend(UserEntity friend) {
this.friend = friend;
}
public UserEntity getPerson() {
return person;
}
public void setPerson(UserEntity person) {
this.person = person;
}
public Date getTime() {
return time;
}
public void setTime(Date time) {
this.time = time;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
@Override
public int hashCode() {
return Objects.hash(id, friend, person, time, text);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null || getClass() != obj.getClass())
return false;
final MessageEntity other = (MessageEntity) obj;
return Objects.equals(other.getId(), id)
&& Objects.equals(other.getPerson(), person)
&& Objects.equals(other.getFriend(), friend)
&& Objects.equals(other.getText(), text)
&& Objects.equals(other.getTime(), time);
}
}

View File

@ -0,0 +1,10 @@
package com.example.demo.messages.repository;
import org.springframework.stereotype.Repository;
import com.example.demo.core.repository.MapRepository;
import com.example.demo.messages.model.MessageEntity;
@Repository
public class MessageRepository extends MapRepository<MessageEntity> {
}

View File

@ -0,0 +1,43 @@
package com.example.demo.messages.service;
import java.util.List;
import java.util.Optional;
import org.springframework.stereotype.Service;
import com.example.demo.core.error.NotFoundException;
import com.example.demo.messages.model.MessageEntity;
import com.example.demo.messages.repository.MessageRepository;
@Service
public class MessageService {
private final MessageRepository repository;
public MessageService(MessageRepository repository) {
this.repository = repository;
}
public List<MessageEntity> getAll() {
return repository.getAll();
}
public MessageEntity get(Long id) {
return Optional.ofNullable(repository.get(id))
.orElseThrow(() -> new NotFoundException(id));
}
public MessageEntity create(MessageEntity entity) {
return repository.create(entity);
}
public MessageEntity update(Long id, MessageEntity entity) {
final MessageEntity existsEntity = get(id);
existsEntity.setText(entity.getText());
return repository.update(existsEntity);
}
public MessageEntity delete(Long id) {
final MessageEntity existsEntity = get(id);
return repository.delete(existsEntity);
}
}

View File

@ -0,0 +1,89 @@
package com.example.demo.posts.api;
import java.util.List;
import org.modelmapper.ModelMapper;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.core.convert;
import com.example.demo.core.configuration.Constants;
import com.example.demo.posts.model.PostEntity;
import com.example.demo.posts.service.PostService;
import com.example.demo.users.service.UserService;
import jakarta.validation.Valid;
@RestController
@RequestMapping(Constants.API_URL + "/post")
public class PostController {
private final UserService userService;
private final PostService postService;
private final ModelMapper modelMapper;
public PostController(PostService postService, UserService userService, ModelMapper modelMapper) {
this.postService = postService;
this.userService = userService;
this.modelMapper = modelMapper;
}
private PostDto toDto(PostEntity entity) {
var model = modelMapper.map(entity, PostDto.class);
convert time = new convert();
model.setTime(time.dateToString(entity.getTime()));
return model;
}
private PostEntity toEntity(PostDto dto) {
final PostEntity entity = modelMapper.map(dto, PostEntity.class);
entity.setPerson(userService.get(dto.getPersonId()));
return entity;
}
@GetMapping
public List<PostDto> getAll() {
return postService.getAll().stream().map(this::toDto).toList();
}
@GetMapping("/{id}")
public PostDto get(@PathVariable(name = "id") Long id) {
return toDto(postService.get(id));
}
@PostMapping
public PostDto create(@RequestBody @Valid PostDto dto) {
return toDto(postService.create(toEntity(dto)));
}
@PostMapping("/like/{id}")
public PostDto addLike(@PathVariable(name = "id") Long id) {
return toDto(postService.addLike(id));
}
@DeleteMapping("/like/{id}")
public PostDto removeLike(@PathVariable(name = "id") Long id) {
return toDto(postService.removeLiked(id));
}
@PostMapping("/view/{id}")
public PostDto addView(@PathVariable(name = "id") Long id) {
return toDto(postService.addView(id));
}
@PutMapping("/{id}")
public PostDto update(@PathVariable(name = "id") Long id, @RequestBody PostDto dto) {
return toDto(postService.update(id, toEntity(dto)));
}
@DeleteMapping("/{id}")
public PostDto delete(@PathVariable(name = "id") Long id) {
return toDto(postService.delete(id));
}
}

View File

@ -0,0 +1,73 @@
package com.example.demo.posts.api;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
public class PostDto {
private Long id;
@NotBlank
@Min(1)
private Long personId;
@NotBlank
private String time;
@NotBlank
private String text;
@NotNull
@Min(0)
private Long viewed;
@NotNull
@Min(0)
private Long liked;
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getPersonId() {
return personId;
}
public void setPersonId(Long personId) {
this.personId = personId;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public Long getViewed() {
return viewed;
}
public void setViewed(Long viewed) {
this.viewed = viewed;
}
public Long getLiked() {
return liked;
}
public void setLiked(Long liked) {
this.liked = liked;
}
}

View File

@ -0,0 +1,89 @@
package com.example.demo.posts.model;
import java.util.Date;
import java.util.Objects;
import com.example.demo.core.model.BaseEntity;
import com.example.demo.users.model.UserEntity;
public class PostEntity extends BaseEntity {
private UserEntity person;
private Date time;
private String text;
private Long viewed;
private Long liked;
public PostEntity() {
super();
}
public PostEntity(Long id, UserEntity person, Date time, String text, Long viewed, Long liked) {
super(id);
this.person = person;
this.text = text;
this.time = time;
this.viewed = viewed;
this.liked = liked;
}
public UserEntity getPerson() {
return person;
}
public void setPerson(UserEntity person) {
this.person = person;
}
public Date getTime() {
return time;
}
public void setTime(Date time) {
this.time = time;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public Long getViewed() {
return viewed;
}
public void setViewed(Long viewed) {
this.viewed = viewed;
}
public Long getLiked() {
return liked;
}
public void setLiked(Long liked) {
this.liked = liked;
}
@Override
public int hashCode() {
return Objects.hash(id, person, time, text, viewed, liked);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null || getClass() != obj.getClass())
return false;
final PostEntity other = (PostEntity) obj;
return Objects.equals(other.getId(), id)
&& Objects.equals(other.getPerson(), person)
&& Objects.equals(other.getText(), text)
&& Objects.equals(other.getTime(), time)
&& Objects.equals(other.getLiked(), liked)
&& Objects.equals(other.getViewed(), viewed);
}
}

View File

@ -0,0 +1,10 @@
package com.example.demo.posts.repository;
import org.springframework.stereotype.Repository;
import com.example.demo.core.repository.MapRepository;
import com.example.demo.posts.model.PostEntity;
@Repository
public class PostRepository extends MapRepository<PostEntity> {
}

View File

@ -0,0 +1,61 @@
package com.example.demo.posts.service;
import java.util.List;
import java.util.Optional;
import org.springframework.stereotype.Service;
import com.example.demo.core.error.NotFoundException;
import com.example.demo.posts.model.PostEntity;
import com.example.demo.posts.repository.PostRepository;
@Service
public class PostService {
private final PostRepository repository;
public PostService(PostRepository repository) {
this.repository = repository;
}
public List<PostEntity> getAll() {
return repository.getAll();
}
public PostEntity get(Long id) {
return Optional.ofNullable(repository.get(id))
.orElseThrow(() -> new NotFoundException(id));
}
public PostEntity create(PostEntity entity) {
return repository.create(entity);
}
public PostEntity addLike(Long id) {
final PostEntity existsEntity = get(id);
existsEntity.setLiked((existsEntity.getLiked() + 1));
return repository.update(existsEntity);
}
public PostEntity removeLiked(Long id) {
final PostEntity existsEntity = get(id);
existsEntity.setLiked((existsEntity.getLiked() - 1));
return repository.update(existsEntity);
}
public PostEntity addView(Long id) {
final PostEntity existsEntity = get(id);
existsEntity.setViewed((existsEntity.getViewed() + 1));
return repository.update(existsEntity);
}
public PostEntity update(Long id, PostEntity entity) {
final PostEntity existsEntity = get(id);
existsEntity.setText(entity.getText());
return repository.update(existsEntity);
}
public PostEntity delete(Long id) {
final PostEntity existsEntity = get(id);
return repository.delete(existsEntity);
}
}

View File

@ -0,0 +1,82 @@
package com.example.demo.users.api;
import java.util.List;
import org.modelmapper.ModelMapper;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.core.configuration.Constants;
import com.example.demo.users.model.UserEntity;
import com.example.demo.users.service.UserService;
import jakarta.validation.Valid;
@RestController
@RequestMapping(Constants.API_URL + "/user")
public class UserController {
private final UserService userService;
private final ModelMapper modelMapper;
public UserController(UserService userService, ModelMapper modelMapper) {
this.userService = userService;
this.modelMapper = modelMapper;
}
private UserDto toDto(UserEntity entity) {
var model = modelMapper.map(entity, UserDto.class);
if (entity.getFriends() != null) {
for (UserEntity user : entity.getFriends()) {
model.addFriendId(user.getId());
}
}
return model;
}
private UserEntity toEntity(UserDto dto) {
return modelMapper.map(dto, UserEntity.class);
}
@GetMapping
public List<UserDto> getAll() {
return userService.getAll().stream().map(this::toDto).toList();
}
@GetMapping("/{id}")
public UserDto get(@PathVariable(name = "id") Long id) {
return toDto(userService.get(id));
}
@PostMapping
public UserDto create(@RequestBody @Valid UserDto dto) {
return toDto(userService.create(toEntity(dto)));
}
@PostMapping("/friends/{id}")
public UserDto addFriend(@PathVariable(name = "id") Long id, @RequestBody UserDto dto) {
return toDto(userService.addFriend(id, toEntity(dto)));
}
@DeleteMapping("/friends/{id}")
public UserDto removeFriend(@PathVariable(name = "id") Long id, @RequestBody UserDto dto) {
return toDto(userService.removeFriend(id, toEntity(dto)));
}
@PutMapping("/{id}")
public UserDto update(@PathVariable(name = "id") Long id, @RequestBody UserDto dto) {
return toDto(userService.update(id, toEntity(dto)));
}
@DeleteMapping("/{id}")
public UserDto delete(@PathVariable(name = "id") Long id) {
return toDto(userService.delete(id));
}
}

View File

@ -0,0 +1,65 @@
package com.example.demo.users.api;
import java.util.ArrayList;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
public class UserDto {
private Long id;
@NotNull
@Min(1)
private String nickname;
@NotBlank
private String email;
@NotBlank
private String password;
private List<Long> friendsId = new ArrayList<>();
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public List<Long> getFriendsId() {
return friendsId;
}
public void addFriendId(long Id) {
friendsId.add(Id);
}
}

View File

@ -0,0 +1,76 @@
package com.example.demo.users.model;
import java.util.ArrayList;
import java.util.Objects;
import java.util.List;
import com.example.demo.core.model.BaseEntity;
public class UserEntity extends BaseEntity {
private String nickname;
private String email;
private String password;
private List<UserEntity> friends = new ArrayList<>();
public UserEntity() {
super();
}
public UserEntity(Long id, String nickname, String email, String password, List<UserEntity> friends) {
super(id);
this.nickname = nickname;
this.email = email;
this.password = password;
this.friends = friends;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public List<UserEntity> getFriends() {
return friends;
}
public void setFriends(List<UserEntity> friends) {
this.friends = friends;
}
@Override
public int hashCode() {
return Objects.hash(id, nickname, email, password, friends);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null || getClass() != obj.getClass())
return false;
final UserEntity other = (UserEntity) obj;
return Objects.equals(other.getId(), id)
&& Objects.equals(other.getFriends(), friends)
&& Objects.equals(other.getNickname(), nickname)
&& Objects.equals(other.getEmail(), email)
&& Objects.equals(other.getPassword(), password);
}
}

View File

@ -0,0 +1,10 @@
package com.example.demo.users.repository;
import org.springframework.stereotype.Repository;
import com.example.demo.core.repository.MapRepository;
import com.example.demo.users.model.UserEntity;
@Repository
public class UserRepository extends MapRepository<UserEntity> {
}

View File

@ -0,0 +1,57 @@
package com.example.demo.users.service;
import java.util.List;
import java.util.Optional;
import org.springframework.stereotype.Service;
import com.example.demo.core.error.NotFoundException;
import com.example.demo.users.model.UserEntity;
import com.example.demo.users.repository.UserRepository;
@Service
public class UserService {
private final UserRepository repository;
public UserService(UserRepository repository) {
this.repository = repository;
}
public List<UserEntity> getAll() {
return repository.getAll();
}
public UserEntity get(Long id) {
return Optional.ofNullable(repository.get(id))
.orElseThrow(() -> new NotFoundException(id));
}
public UserEntity create(UserEntity entity) {
return repository.create(entity);
}
public UserEntity addFriend(Long id, UserEntity entity) {
final UserEntity existsEntity = get(id);
existsEntity.getFriends().add(entity);
return repository.update(existsEntity);
}
public UserEntity removeFriend(Long id, UserEntity entity) {
final UserEntity existsEntity = get(id);
existsEntity.getFriends().remove(entity);
return repository.update(existsEntity);
}
public UserEntity update(Long id, UserEntity entity) {
final UserEntity existsEntity = get(id);
existsEntity.setNickname(entity.getNickname());
existsEntity.setEmail(entity.getEmail());
existsEntity.setPassword(entity.getPassword());
return repository.update(existsEntity);
}
public UserEntity delete(Long id) {
final UserEntity existsEntity = get(id);
return repository.delete(existsEntity);
}
}

View File

@ -0,0 +1 @@

View File

@ -0,0 +1,92 @@
package com.example.demo;
import java.util.Date;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import com.example.demo.comments.model.CommentEntity;
import com.example.demo.comments.service.CommentService;
import com.example.demo.core.error.NotFoundException;
import com.example.demo.users.model.UserEntity;
import com.example.demo.posts.model.PostEntity;
import com.example.demo.users.service.UserService;
import com.example.demo.posts.service.PostService;;
@SpringBootTest
@TestMethodOrder(OrderAnnotation.class)
class CommentServiceTests {
@Autowired
private UserService userService;
@Autowired
private PostService postService;
@Autowired
private CommentService commentService;
@Test
void getTest() {
Assertions.assertThrows(NotFoundException.class, () -> commentService.get(0L));
}
@Test
@Order(1)
void createTest() {
var user1 = userService.create(new UserEntity(null, "sardq", "as2@asd", "asdsd", null));
var user2 = userService.create(new UserEntity(null, "eafqr", "aasd@asd", "1234r", null));
var user3 = userService.create(new UserEntity(null, "asf", "aaasfsfs@asd", "332a", null));
var post1 = postService.create(new PostEntity(null, user1, new Date(), "test",
Long.valueOf(0), Long.valueOf(0)));
var post2 = postService
.create(new PostEntity(null, user3, new Date(), "asfgczv", Long.valueOf(20),
Long.valueOf(15)));
var post3 = postService.create(new PostEntity(null, user2, new Date(), "asvbsfd", Long.valueOf(30),
Long.valueOf(3)));
commentService.create(new CommentEntity(null, user1, post2, new Date(), "my comment"));
commentService.create(new CommentEntity(null, user3, post1, new Date(), "my comment2"));
final var last = commentService
.create(new CommentEntity(null, user2, post3, new Date(), "my comment3"));
Assertions.assertEquals(3, commentService.getAll().size());
Assertions.assertEquals(last, commentService.get(3L));
}
@Test
@Order(2)
void updateTest() {
final String test = "TEST";
final CommentEntity entity = commentService.get(3L);
final String oldText = entity.getText();
var user1 = userService.create(new UserEntity(null, "sardq", "as2@asd", "asdsd", null));
var post1 = postService.create(new PostEntity(null, user1,
new Date(), "test",
Long.valueOf(0), Long.valueOf(0)));
final CommentEntity newEntity = commentService.update(3L,
new CommentEntity(1L, user1, post1, new Date(), test));
Assertions.assertEquals(3, commentService.getAll().size());
Assertions.assertEquals(newEntity, commentService.get(3L));
Assertions.assertEquals(test, newEntity.getText());
Assertions.assertNotEquals(oldText, newEntity.getText());
}
@Test
@Order(3)
void deleteTest() {
commentService.delete(3L);
Assertions.assertEquals(2, commentService.getAll().size());
final CommentEntity last = commentService.get(2L);
Assertions.assertEquals(2L, last.getId());
final var user1 = userService.create(new UserEntity(null, "sardq", "as2@asd", "asdsd", null));
final var post1 = postService.create(new PostEntity(null, user1,
new Date(), "test",
Long.valueOf(0), Long.valueOf(0)));
final CommentEntity newEntity = commentService.create(
new CommentEntity(null, user1, post1, new Date(), "jgdssd"));
Assertions.assertEquals(3, commentService.getAll().size());
Assertions.assertEquals(4L, newEntity.getId());
}
}

View File

@ -0,0 +1,77 @@
package com.example.demo;
import java.util.Date;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import com.example.demo.core.error.NotFoundException;
import com.example.demo.messages.model.MessageEntity;
import com.example.demo.messages.service.MessageService;
import com.example.demo.users.model.UserEntity;
import com.example.demo.users.service.UserService;
@SpringBootTest
@TestMethodOrder(OrderAnnotation.class)
class MessageServiceTests {
@Autowired
private UserService userService;
@Autowired
private MessageService messageService;
@Test
void getTest() {
Assertions.assertThrows(NotFoundException.class, () -> messageService.get(0L));
}
@Test
@Order(1)
void createTest() {
var user1 = userService.create(new UserEntity(null, "sardq", "as2@asd", "asdsd", null));
var user2 = userService.create(new UserEntity(null, "eafqr", "aasd@asd", "1234r", null));
var user3 = userService.create(new UserEntity(null, "asf", "aaasfsfs@asd", "332a", null));
messageService.create(new MessageEntity(null, user1, user2, new Date(), "test"));
messageService.create(new MessageEntity(null, user3, user2, new Date(), "asfgczv"));
final MessageEntity last = messageService
.create(new MessageEntity(null, user2, user1, new Date(), "asvbsfd"));
Assertions.assertEquals(3, messageService.getAll().size());
Assertions.assertEquals(last, messageService.get(3L));
}
@Test
@Order(2)
void updateTest() {
final String test = "TEST";
final MessageEntity entity = messageService.get(3L);
final String oldText = entity.getText();
final MessageEntity newEntity = messageService.update(3L,
new MessageEntity(1L,
new UserEntity(null, "safsaf", "aasd@asd", "qazq", null),
new UserEntity(null, "safnkkjaslf", "safsaf@asd", "2qhf", null),
new Date(), test));
Assertions.assertEquals(3, messageService.getAll().size());
Assertions.assertEquals(newEntity, messageService.get(3L));
Assertions.assertEquals(test, newEntity.getText());
Assertions.assertNotEquals(oldText, newEntity.getText());
}
@Test
@Order(3)
void deleteTest() {
messageService.delete(3L);
Assertions.assertEquals(2, messageService.getAll().size());
final MessageEntity last = messageService.get(2L);
Assertions.assertEquals(2L, last.getId());
var user1 = userService.create(new UserEntity(null, "sardq", "as2@asd", "asdsd", null));
var user2 = userService.create(new UserEntity(null, "sasfardq", "asfg@asd", "asfsaf", null));
final MessageEntity newEntity = messageService.create(
new MessageEntity(null, user1, user2, new Date(), "test"));
Assertions.assertEquals(3, messageService.getAll().size());
Assertions.assertEquals(4L, newEntity.getId());
}
}

View File

@ -0,0 +1,81 @@
package com.example.demo;
import java.util.Date;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import com.example.demo.core.error.NotFoundException;
import com.example.demo.users.model.UserEntity;
import com.example.demo.posts.model.PostEntity;
import com.example.demo.users.service.UserService;
import com.example.demo.posts.service.PostService;;
@SpringBootTest
@TestMethodOrder(OrderAnnotation.class)
class PostServiceTests {
@Autowired
private UserService userService;
@Autowired
private PostService postService;
@Test
void getTest() {
Assertions.assertThrows(NotFoundException.class, () -> postService.get(0L));
}
@Test
@Order(1)
void createTest() {
var user1 = userService.create(new UserEntity(null, "sardq", "as2@asd", "asdsd", null));
var user2 = userService.create(new UserEntity(null, "eafqr", "aasd@asd", "1234r", null));
var user3 = userService.create(new UserEntity(null, "asf", "aaasfsfs@asd", "332a", null));
postService.create(new PostEntity(null, user1,
new Date(), "test",
Long.valueOf(0), Long.valueOf(0)));
postService.create(new PostEntity(null, user3, new Date(), "asfgczv", Long.valueOf(20), Long.valueOf(15)));
final PostEntity last = postService
.create(new PostEntity(null, user2,
new Date(), "asvbsfd", Long.valueOf(30),
Long.valueOf(3)));
postService.addLike(1L);
postService.addView(1L);
Assertions.assertEquals(3, postService.getAll().size());
Assertions.assertEquals(last, postService.get(3L));
}
@Test
@Order(2)
void updateTest() {
final String test = "TEST";
final PostEntity entity = postService.get(3L);
final String oldText = entity.getText();
final PostEntity newEntity = postService.update(3L,
new PostEntity(1L, new UserEntity(1L, "safsaf", "aasd@asd", "qazq", null),
new Date(), test, Long.valueOf(30), Long.valueOf(3)));
Assertions.assertEquals(3, postService.getAll().size());
Assertions.assertEquals(newEntity, postService.get(3L));
Assertions.assertEquals(test, newEntity.getText());
Assertions.assertNotEquals(oldText, newEntity.getText());
}
@Test
@Order(3)
void deleteTest() {
postService.delete(3L);
Assertions.assertEquals(2, postService.getAll().size());
final PostEntity last = postService.get(2L);
postService.removeLiked(1L);
Assertions.assertEquals(2L, last.getId());
var user1 = userService.create(new UserEntity(null, "sardq", "as2@asd", "asdsd", null));
final PostEntity newEntity = postService.create(
new PostEntity(null, user1, new Date(), "test", Long.valueOf(0), Long.valueOf(0)));
Assertions.assertEquals(3, postService.getAll().size());
Assertions.assertEquals(4L, newEntity.getId());
}
}

View File

@ -0,0 +1,68 @@
package com.example.demo;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import com.example.demo.core.error.NotFoundException;
import com.example.demo.users.model.UserEntity;
import com.example.demo.users.service.UserService;
@SpringBootTest
@TestMethodOrder(OrderAnnotation.class)
class UserServiceTests {
@Autowired
private UserService userService;
@Test
void getTest() {
Assertions.assertThrows(NotFoundException.class, () -> userService.get(0L));
}
@Test
@Order(1)
void createTest() {
List<UserEntity> friends = new ArrayList<UserEntity>();
friends.add(new UserEntity(2L, "eafqr", "aasd@asd", "1234r", new ArrayList<UserEntity>()));
userService.create(new UserEntity(1L, "sardq", "as2@asd", "asdsd", friends));
userService.create(new UserEntity(2L, "eafqr", "aasd@asd", "1234r", new ArrayList<UserEntity>()));
final UserEntity last = userService.create(new UserEntity(3L, "fgwrewr", "sf123@asd", "zxvb",
new ArrayList<UserEntity>()));
userService.addFriend(1L, last);
Assertions.assertEquals(3, userService.getAll().size());
Assertions.assertEquals(last, userService.get(3L));
}
@Test
@Order(2)
void updateTest() {
final String test = "TEST";
final UserEntity entity = userService.get(3L);
final String oldName = entity.getNickname();
final UserEntity newEntity = userService.update(3L, new UserEntity(1L, test, "aasd@asd", "qazq", null));
Assertions.assertEquals(3, userService.getAll().size());
Assertions.assertEquals(newEntity, userService.get(3L));
Assertions.assertEquals(test, newEntity.getNickname());
Assertions.assertNotEquals(oldName, newEntity.getNickname());
}
@Test
@Order(3)
void deleteTest() {
userService.delete(3L);
Assertions.assertEquals(2, userService.getAll().size());
final UserEntity last = userService.get(2L);
userService.removeFriend(2L, last);
Assertions.assertEquals(2L, last.getId());
final UserEntity newEntity = userService.create(new UserEntity(null, "asfzxv", "aasd@asd", "qwtg", null));
Assertions.assertEquals(3, userService.getAll().size());
Assertions.assertEquals(4L, newEntity.getId());
}
}

36
3 lab/.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
3 lab/.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"
]
}

14
3 lab/.vscode/launch.json vendored Normal file
View File

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

21
3 lab/.vscode/settings.json vendored Normal file
View File

@ -0,0 +1,21 @@
{
"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,
}

43
3 lab/build.gradle Normal file
View File

@ -0,0 +1,43 @@
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.springdoc:springdoc-openapi-starter-webmvc-ui:2.3.0'
implementation 'org.modelmapper:modelmapper:3.2.0'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'com.h2database:h2:2.2.224'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
tasks.named('test') {
useJUnitPlatform()
}

BIN
3 lab/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
3 lab/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
3 lab/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

18
3 lab/readme.md Normal file
View File

@ -0,0 +1,18 @@
Swagger UI: \
http://localhost:8080/swagger-ui/index.html
H2 Console: \
http://localhost:8080/h2-console
JDBC URL: jdbc:h2:file:./data \
User Name: sa \
Password: password
Почитать:
- Односторонние и двусторонние связи https://www.baeldung.com/jpa-hibernate-associations
- Getters и Setters для двусторонних связей https://en.wikibooks.org/wiki/Java_Persistence/OneToMany#Getters_and_Setters
- Многие-ко-многим с доп. атрибутами https://thorben-janssen.com/hibernate-tip-many-to-many-association-with-additional-attributes/
- Многие-ко-многим с доп. атрибутами https://www.baeldung.com/jpa-many-to-many
- Каскадное удаление сущностей со связями многие-ко-многим https://www.baeldung.com/jpa-remove-entity-many-to-many
- Выбор типа коллекции для отношений вида ко-многим в JPA https://thorben-janssen.com/association-mappings-bag-list-set/

1
3 lab/settings.gradle Normal file
View File

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

View File

@ -0,0 +1,87 @@
package com.example.demo;
import java.sql.Time;
import java.util.ArrayList;
import java.util.Objects;
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 java.util.List;
import com.example.demo.comments.model.CommentEntity;
import com.example.demo.comments.service.CommentService;
import com.example.demo.messages.model.MessageEntity;
import com.example.demo.messages.service.MessageService;
import com.example.demo.posts.model.PostEntity;
import com.example.demo.posts.service.PostService;
import com.example.demo.users.model.UserEntity;
import com.example.demo.users.service.UserService;
@SpringBootApplication
public class DemoApplication implements CommandLineRunner {
private final Logger log = LoggerFactory.getLogger(DemoApplication.class);
private final UserService userService;
private final PostService postService;
private final CommentService commentService;
private final MessageService messageService;
public DemoApplication(UserService userService, PostService postService, CommentService commentService,
MessageService messageService) {
this.userService = userService;
this.postService = postService;
this.commentService = commentService;
this.messageService = messageService;
}
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
if (args.length > 0 && Objects.equals("--populate", args[0])) {
log.info("Create default items values");
final List<UserEntity> blank = new ArrayList<UserEntity>();
final var user1 = userService.create(new UserEntity("sardq", "aasd@asd", "asdsd", null));
final var user2 = userService.create(new UserEntity("sardasdq", "aasdsad@asd", "123", blank));
final List<UserEntity> friends = new ArrayList<>();
friends.add(user1);
friends.add(user2);
userService.addFriend(user1.getId(), user2);
final var user3 = userService.create(new UserEntity("sxzcvardq", "aaxsd@asd", "asfgd", friends));
final var user4 = userService.create(new UserEntity("sarbvljdq", "aacbxcsd@asd", "zxvb", blank));
log.info("Create default posts values");
final var post1 = postService.create(
new PostEntity(user1, new Time(System.currentTimeMillis()), "test", Long.valueOf(0),
Long.valueOf(0)));
final var post2 = postService.create(
new PostEntity(user3, new Time(System.currentTimeMillis()), "test", Long.valueOf(11),
Long.valueOf(2)));
final var post3 = postService.create(
new PostEntity(user4, new Time(System.currentTimeMillis()), "test", Long.valueOf(40),
Long.valueOf(15)));
log.info("Create default comments values");
commentService
.create(new CommentEntity(user1, post2, new Time(System.currentTimeMillis()), "my comment"));
commentService
.create(new CommentEntity(user3, post1, new Time(System.currentTimeMillis()), "my comment2"));
commentService
.create(new CommentEntity(user4, post3, new Time(System.currentTimeMillis()), "my comment3"));
log.info("Create default messages values");
messageService.create(new MessageEntity(user1, user2, new Time(System.currentTimeMillis()), "hello"));
messageService
.create(new MessageEntity(user1, user2, new Time(System.currentTimeMillis()), "how are you"));
messageService
.create(new MessageEntity(user2, user1, new Time(System.currentTimeMillis()), "I'm ok"));
}
}
}

View File

@ -0,0 +1,81 @@
package com.example.demo.comments.api;
import org.modelmapper.ModelMapper;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.comments.model.CommentEntity;
import com.example.demo.comments.service.CommentService;
import com.example.demo.core.convert;
import com.example.demo.core.api.PageDto;
import com.example.demo.core.api.PageDtoMapper;
import com.example.demo.core.configuration.Constants;
import com.example.demo.posts.service.PostService;
import com.example.demo.users.service.UserService;
import jakarta.validation.Valid;
@RestController
@RequestMapping(Constants.API_URL + "/comment")
public class CommentController {
private final UserService userService;
private final PostService postService;
private final CommentService commentService;
private final ModelMapper modelMapper;
public CommentController(CommentService commentService, UserService userService, PostService postService,
ModelMapper modelMapper) {
this.userService = userService;
this.commentService = commentService;
this.postService = postService;
this.modelMapper = modelMapper;
}
private CommentDto toDto(CommentEntity entity) {
var model = modelMapper.map(entity, CommentDto.class);
convert time = new convert();
model.setTime(time.dateToString(entity.getTime()));
return model;
}
private CommentEntity toEntity(CommentDto dto) {
final CommentEntity entity = modelMapper.map(dto, CommentEntity.class);
entity.setperson(userService.get(dto.getUserId()));
entity.setPost(postService.get(dto.getPostId()));
return entity;
}
@GetMapping
public PageDto<CommentDto> getAll(
@RequestParam(name = "page", defaultValue = "0") int page,
@RequestParam(name = "size", defaultValue = Constants.DEFAULT_PAGE_SIZE) int size) {
return PageDtoMapper.toDto(commentService.getAll(page, size), this::toDto);
}
@GetMapping("/{id}")
public CommentDto get(@PathVariable(name = "id") Long id) {
return toDto(commentService.get(id));
}
@PostMapping
public CommentDto create(@RequestBody @Valid CommentDto dto) {
return toDto(commentService.create(toEntity(dto)));
}
@PutMapping("/{id}")
public CommentDto update(@PathVariable(name = "id") Long id, @RequestBody CommentDto dto) {
return toDto(commentService.update(id, toEntity(dto)));
}
@DeleteMapping("/{id}")
public CommentDto delete(@PathVariable(name = "id") Long id) {
return toDto(commentService.delete(id));
}
}

View File

@ -0,0 +1,62 @@
package com.example.demo.comments.api;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
public class CommentDto {
private Long id;
@NotNull
@Min(1)
private Long userId;
@NotBlank
private String text;
@NotNull
@Min(1)
private Long postId;
@NotBlank
private String time;
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
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 getPostId() {
return postId;
}
public void setPostId(Long postId) {
this.postId = postId;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
}

View File

@ -0,0 +1,90 @@
package com.example.demo.comments.model;
import java.util.Date;
import java.util.Objects;
import com.example.demo.core.model.BaseEntity;
import com.example.demo.posts.model.PostEntity;
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 = "comments")
public class CommentEntity extends BaseEntity {
@ManyToOne
@JoinColumn(name = "personEntity", nullable = false)
private UserEntity person;
@ManyToOne
@JoinColumn(name = "postEntity", nullable = false)
private PostEntity post;
@Column(nullable = false)
private Date time;
@Column(length = 100)
private String text;
public CommentEntity() {
}
public CommentEntity(UserEntity person, PostEntity post, Date time, String text) {
this.person = person;
this.post = post;
this.time = time;
this.text = text;
}
public UserEntity getperson() {
return person;
}
public void setperson(UserEntity person) {
this.person = person;
}
public PostEntity getPost() {
return post;
}
public void setPost(PostEntity post) {
this.post = post;
}
public Date getTime() {
return time;
}
public void setTime(Date time) {
this.time = time;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
@Override
public int hashCode() {
return Objects.hash(id, person, post, text, time);
}
@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(), id)
&& Objects.equals(other.getperson(), person)
&& Objects.equals(other.getPost(), post)
&& Objects.equals(other.getText(), text)
&& Objects.equals(other.getTime(), time);
}
}

View File

@ -0,0 +1,14 @@
package com.example.demo.comments.repository;
import java.util.Optional;
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> {
Optional<CommentEntity> findById(Long Id);
}

View File

@ -0,0 +1,63 @@
package com.example.demo.comments.service;
import java.util.List;
import java.util.stream.StreamSupport;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.example.demo.comments.model.CommentEntity;
import com.example.demo.comments.repository.CommentRepository;
import com.example.demo.core.error.NotFoundException;
@Service
public class CommentService {
private final CommentRepository repository;
public CommentService(CommentRepository repository) {
this.repository = repository;
}
@Transactional(readOnly = true)
public List<CommentEntity> getAll() {
return StreamSupport.stream(repository.findAll().spliterator(), false).toList();
}
@Transactional(readOnly = true)
public Page<CommentEntity> getAll(int page, int size) {
return repository.findAll(PageRequest.of(page, size));
}
@Transactional(readOnly = true)
public CommentEntity get(Long id) {
return repository.findById(id)
.orElseThrow(() -> new NotFoundException(CommentEntity.class, id));
}
@Transactional
public CommentEntity create(CommentEntity entity) {
if (entity == null) {
throw new IllegalArgumentException("Entity is null");
}
repository.save(entity);
return repository.save(entity);
}
@Transactional
public CommentEntity update(Long id, CommentEntity entity) {
final CommentEntity existsEntity = get(id);
existsEntity.setText(entity.getText());
repository.save(existsEntity);
return existsEntity;
}
@Transactional
public CommentEntity delete(Long id) {
final CommentEntity existsEntity = get(id);
repository.delete(existsEntity);
return existsEntity;
}
}

View File

@ -0,0 +1,97 @@
package com.example.demo.core.api;
import java.util.ArrayList;
import java.util.List;
public class PageDto<D> {
private List<D> items = new ArrayList<>();
private int itemsCount;
private int currentPage;
private int currentSize;
private int totalPages;
private long totalItems;
private boolean isFirst;
private boolean isLast;
private boolean hasNext;
private boolean hasPrevious;
public List<D> getItems() {
return items;
}
public void setItems(List<D> items) {
this.items = items;
}
public int getItemsCount() {
return itemsCount;
}
public void setItemsCount(int itemsCount) {
this.itemsCount = itemsCount;
}
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
public int getCurrentSize() {
return currentSize;
}
public void setCurrentSize(int currentSize) {
this.currentSize = currentSize;
}
public int getTotalPages() {
return totalPages;
}
public void setTotalPages(int totalPages) {
this.totalPages = totalPages;
}
public long getTotalItems() {
return totalItems;
}
public void setTotalItems(long totalItems) {
this.totalItems = totalItems;
}
public boolean isFirst() {
return isFirst;
}
public void setFirst(boolean isFirst) {
this.isFirst = isFirst;
}
public boolean isLast() {
return isLast;
}
public void setLast(boolean isLast) {
this.isLast = isLast;
}
public boolean isHasNext() {
return hasNext;
}
public void setHasNext(boolean hasNext) {
this.hasNext = hasNext;
}
public boolean isHasPrevious() {
return hasPrevious;
}
public void setHasPrevious(boolean hasPrevious) {
this.hasPrevious = hasPrevious;
}
}

View File

@ -0,0 +1,25 @@
package com.example.demo.core.api;
import java.util.function.Function;
import org.springframework.data.domain.Page;
public class PageDtoMapper {
private PageDtoMapper() {
}
public static <D, E> PageDto<D> toDto(Page<E> page, Function<E, D> mapper) {
final PageDto<D> dto = new PageDto<>();
dto.setItems(page.getContent().stream().map(mapper::apply).toList());
dto.setItemsCount(page.getNumberOfElements());
dto.setCurrentPage(page.getNumber());
dto.setCurrentSize(page.getSize());
dto.setTotalPages(page.getTotalPages());
dto.setTotalItems(page.getTotalElements());
dto.setFirst(page.isFirst());
dto.setLast(page.isLast());
dto.setHasNext(page.hasNext());
dto.setHasPrevious(page.hasPrevious());
return dto;
}
}

View File

@ -0,0 +1,10 @@
package com.example.demo.core.configuration;
public class Constants {
public static final String API_URL = "/api/1.0";
public static final String SEQUENCE_NAME = "hibernate_sequence";
public static final String DEFAULT_PAGE_SIZE = "5";
private Constants() {
}
}

View File

@ -0,0 +1,13 @@
package com.example.demo.core.configuration;
import org.modelmapper.ModelMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MapperConfiguration {
@Bean
ModelMapper modelMapper() {
return new ModelMapper();
}
}

View File

@ -0,0 +1,15 @@
package com.example.demo.core.configuration;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.NonNull;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfiguration implements WebMvcConfigurer {
@Override
public void addCorsMappings(@NonNull CorsRegistry registry) {
registry.addMapping("/**")
.allowedMethods("GET", "POST", "PUT", "DELETE");
}
}

View File

@ -0,0 +1,17 @@
package com.example.demo.core;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class convert {
public Date stringToDate(String string) throws Exception {
DateFormat format = new SimpleDateFormat("HH:mm:ss");
return (Date) format.parse(string);
}
public String dateToString(Date date) {
DateFormat dateFormat = new SimpleDateFormat("dd.MM.YYYY hh:mm:ss");
return dateFormat.format(date);
}
}

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,32 @@
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() {
}
protected BaseEntity(Long id) {
this.id = id;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}

View File

@ -0,0 +1,79 @@
package com.example.demo.messages.api;
import org.modelmapper.ModelMapper;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.core.convert;
import com.example.demo.core.api.PageDto;
import com.example.demo.core.api.PageDtoMapper;
import com.example.demo.core.configuration.Constants;
import com.example.demo.messages.model.MessageEntity;
import com.example.demo.messages.service.MessageService;
import com.example.demo.users.service.UserService;
import jakarta.validation.Valid;
@RestController
@RequestMapping(Constants.API_URL + "/message")
public class MessageController {
private final UserService userService;
private final MessageService messageService;
private final ModelMapper modelMapper;
public MessageController(MessageService messageService, UserService userService, ModelMapper modelMapper) {
this.messageService = messageService;
this.userService = userService;
this.modelMapper = modelMapper;
}
private MessageDto toDto(MessageEntity entity) {
var model = modelMapper.map(entity, MessageDto.class);
convert time = new convert();
model.setTime(time.dateToString(entity.getTime()));
return model;
}
private MessageEntity toEntity(MessageDto dto) {
final MessageEntity entity = modelMapper.map(dto, MessageEntity.class);
entity.setFriend(userService.get(dto.getFriendId()));
entity.setPerson(userService.get(dto.getPersonId()));
return entity;
}
@GetMapping
public PageDto<MessageDto> getAll(
@RequestParam(name = "personId", defaultValue = "0") Long personId,
@RequestParam(name = "page", defaultValue = "0") int page,
@RequestParam(name = "size", defaultValue = Constants.DEFAULT_PAGE_SIZE) int size) {
return PageDtoMapper.toDto(messageService.getAll(personId, page, size), this::toDto);
}
@GetMapping("/{id}")
public MessageDto get(@PathVariable(name = "id") Long id) {
return toDto(messageService.get(id));
}
@PostMapping
public MessageDto create(@RequestBody @Valid MessageDto dto) {
return toDto(messageService.create(toEntity(dto)));
}
@PutMapping("/{id}")
public MessageDto update(@PathVariable(name = "id") Long id, @RequestBody MessageDto dto) {
return toDto(messageService.update(id, toEntity(dto)));
}
@DeleteMapping("/{id}")
public MessageDto delete(@PathVariable(name = "id") Long id) {
return toDto(messageService.delete(id));
}
}

View File

@ -0,0 +1,62 @@
package com.example.demo.messages.api;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
public class MessageDto {
private Long id;
@NotNull
@Min(1)
private Long friendId;
@NotNull
@Min(1)
private Long personId;
@NotBlank
private String text;
@NotBlank
private String time;
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getPersonId() {
return personId;
}
public void setPersonId(Long personId) {
this.personId = personId;
}
public Long getFriendId() {
return friendId;
}
public void setFriendId(Long friendId) {
this.friendId = friendId;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}

View File

@ -0,0 +1,91 @@
package com.example.demo.messages.model;
import java.util.Date;
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 = "messages")
public class MessageEntity extends BaseEntity {
@ManyToOne
@JoinColumn(name = "userEntity", nullable = false)
private UserEntity person;
@ManyToOne
@JoinColumn(name = "dialogFriend", nullable = false)
private UserEntity friend;
@Column(nullable = false)
private Date time;
@Column(length = 100)
private String text;
public MessageEntity() {
}
public MessageEntity(UserEntity person, UserEntity friend, Date time, String text) {
this.person = person;
this.friend = friend;
this.text = text;
this.time = time;
}
public UserEntity getFriend() {
return friend;
}
public void setFriend(UserEntity friend) {
this.friend = friend;
}
public UserEntity getPerson() {
return person;
}
public void setPerson(UserEntity person) {
this.person = person;
}
public Date getTime() {
return time;
}
public void setTime(Date time) {
this.time = time;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
@Override
public int hashCode() {
return Objects.hash(id, friend, person, time, text);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null || getClass() != obj.getClass())
return false;
final MessageEntity other = (MessageEntity) obj;
return Objects.equals(other.getId(), id)
&& Objects.equals(other.getPerson(), person)
&& Objects.equals(other.getFriend(), friend)
&& Objects.equals(other.getText(), text)
&& Objects.equals(other.getTime(), time);
}
}

View File

@ -0,0 +1,21 @@
package com.example.demo.messages.repository;
import java.util.List;
import java.util.Optional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.PagingAndSortingRepository;
import com.example.demo.messages.model.MessageEntity;
public interface MessageRepository
extends CrudRepository<MessageEntity, Long>, PagingAndSortingRepository<MessageEntity, Long> {
List<MessageEntity> findByPersonId(Long personId);
Page<MessageEntity> findByPersonId(Long personId, Pageable pageable);
Optional<MessageEntity> findById(Long Id);
}

View File

@ -0,0 +1,72 @@
package com.example.demo.messages.service;
import java.util.List;
import java.util.stream.StreamSupport;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import com.example.demo.core.error.NotFoundException;
import com.example.demo.messages.model.MessageEntity;
import com.example.demo.messages.repository.MessageRepository;
@Service
public class MessageService {
private final MessageRepository repository;
public MessageService(MessageRepository repository) {
this.repository = repository;
}
@Transactional(readOnly = true)
public List<MessageEntity> getAll(long personId) {
if (personId <= 0L) {
return StreamSupport.stream(repository.findAll().spliterator(), false).toList();
} else {
return repository.findByPersonId(personId);
}
}
@Transactional(readOnly = true)
public Page<MessageEntity> getAll(long personId, int page, int size) {
final Pageable pageRequest = PageRequest.of(page, size);
if (personId <= 0L) {
return repository.findAll(pageRequest);
}
return repository.findByPersonId(personId, pageRequest);
}
@Transactional
public MessageEntity get(Long id) {
return repository.findById(id)
.orElseThrow(() -> new NotFoundException(MessageEntity.class, id));
}
@Transactional
public MessageEntity create(MessageEntity entity) {
if (entity == null) {
throw new IllegalArgumentException("Entity is null");
}
repository.save(entity);
return repository.save(entity);
}
@Transactional
public MessageEntity update(Long id, MessageEntity entity) {
final MessageEntity existsEntity = get(id);
existsEntity.setText(entity.getText());
repository.save(existsEntity);
return existsEntity;
}
@Transactional
public MessageEntity delete(Long id) {
final MessageEntity existsEntity = get(id);
repository.delete(existsEntity);
return existsEntity;
}
}

View File

@ -0,0 +1,92 @@
package com.example.demo.posts.api;
import org.modelmapper.ModelMapper;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.core.convert;
import com.example.demo.core.api.PageDto;
import com.example.demo.core.api.PageDtoMapper;
import com.example.demo.core.configuration.Constants;
import com.example.demo.posts.model.PostEntity;
import com.example.demo.posts.service.PostService;
import com.example.demo.users.service.UserService;
import jakarta.validation.Valid;
@RestController
@RequestMapping(Constants.API_URL + "/post")
public class PostController {
private final UserService userService;
private final PostService postService;
private final ModelMapper modelMapper;
public PostController(PostService postService, UserService userService, ModelMapper modelMapper) {
this.postService = postService;
this.userService = userService;
this.modelMapper = modelMapper;
}
private PostDto toDto(PostEntity entity) {
var model = modelMapper.map(entity, PostDto.class);
convert time = new convert();
model.setTime(time.dateToString(entity.getTime()));
return model;
}
private PostEntity toEntity(PostDto dto) {
final PostEntity entity = modelMapper.map(dto, PostEntity.class);
entity.setPerson(userService.get(dto.getPersonId()));
return entity;
}
@GetMapping
public PageDto<PostDto> getAll(
@RequestParam(name = "page", defaultValue = "0") int page,
@RequestParam(name = "size", defaultValue = Constants.DEFAULT_PAGE_SIZE) int size) {
return PageDtoMapper.toDto(postService.getAll(page, size), this::toDto);
}
@GetMapping("/{id}")
public PostDto get(@PathVariable(name = "id") Long id) {
return toDto(postService.get(id));
}
@PostMapping
public PostDto create(@RequestBody @Valid PostDto dto) {
return toDto(postService.create(toEntity(dto)));
}
@PostMapping("/like/{id}")
public PostDto addLike(@PathVariable(name = "id") Long id) {
return toDto(postService.addLike(id));
}
@DeleteMapping("/like/{id}")
public PostDto removeLike(@PathVariable(name = "id") Long id) {
return toDto(postService.removeLiked(id));
}
@PostMapping("/view/{id}")
public PostDto addView(@PathVariable(name = "id") Long id) {
return toDto(postService.addView(id));
}
@PutMapping("/{id}")
public PostDto update(@PathVariable(name = "id") Long id, @RequestBody PostDto dto) {
return toDto(postService.update(id, toEntity(dto)));
}
@DeleteMapping("/{id}")
public PostDto delete(@PathVariable(name = "id") Long id) {
return toDto(postService.delete(id));
}
}

View File

@ -0,0 +1,76 @@
package com.example.demo.posts.api;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonProperty.Access;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
public class PostDto {
@JsonProperty(access = Access.READ_ONLY)
private Long id;
@NotNull
@Min(1)
private Long personId;
@NotBlank
private String time;
@NotBlank
private String text;
@NotNull
@Min(0)
private Long viewed;
@NotNull
@Min(0)
private Long liked;
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getPersonId() {
return personId;
}
public void setPersonId(Long personId) {
this.personId = personId;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public Long getViewed() {
return viewed;
}
public void setViewed(Long viewed) {
this.viewed = viewed;
}
public Long getLiked() {
return liked;
}
public void setLiked(Long liked) {
this.liked = liked;
}
}

View File

@ -0,0 +1,102 @@
package com.example.demo.posts.model;
import java.util.Date;
import java.util.Objects;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.Table;
import com.example.demo.core.model.BaseEntity;
import com.example.demo.users.model.UserEntity;
@Entity
@Table(name = "posts")
public class PostEntity extends BaseEntity {
@ManyToOne
@JoinColumn(name = "user_Id", nullable = false)
private UserEntity person;
@Column(nullable = false)
private Date time;
@Column(length = 100)
private String text;
@Column
private Long viewed;
@Column
private Long liked;
public PostEntity() {
super();
}
public PostEntity(UserEntity person, Date time, String text, Long viewed, Long liked) {
this.person = person;
this.text = text;
this.time = time;
this.viewed = viewed;
this.liked = liked;
}
public UserEntity getPerson() {
return person;
}
public void setPerson(UserEntity person) {
this.person = person;
}
public Date getTime() {
return time;
}
public void setTime(Date time) {
this.time = time;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public Long getViewed() {
return viewed;
}
public void setViewed(Long viewed) {
this.viewed = viewed;
}
public Long getLiked() {
return liked;
}
public void setLiked(Long liked) {
this.liked = liked;
}
@Override
public int hashCode() {
return Objects.hash(id, person, time, text, viewed, liked);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null || getClass() != obj.getClass())
return false;
final PostEntity other = (PostEntity) obj;
return Objects.equals(other.getId(), id)
&& Objects.equals(other.getPerson(), person)
&& Objects.equals(other.getText(), text)
&& Objects.equals(other.getTime(), time)
&& Objects.equals(other.getLiked(), liked)
&& Objects.equals(other.getViewed(), viewed);
}
}

View File

@ -0,0 +1,14 @@
package com.example.demo.posts.repository;
import java.util.Optional;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.PagingAndSortingRepository;
import com.example.demo.posts.model.PostEntity;
public interface PostRepository
extends CrudRepository<PostEntity, Long>, PagingAndSortingRepository<PostEntity, Long> {
Optional<PostEntity> findById(Long Id);
}

View File

@ -0,0 +1,86 @@
package com.example.demo.posts.service;
import java.util.List;
import java.util.stream.StreamSupport;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.example.demo.core.error.NotFoundException;
import com.example.demo.posts.model.PostEntity;
import com.example.demo.posts.repository.PostRepository;
@Service
public class PostService {
private final PostRepository repository;
public PostService(PostRepository repository) {
this.repository = repository;
}
@Transactional(readOnly = true)
public List<PostEntity> getAll() {
return StreamSupport.stream(repository.findAll().spliterator(), false).toList();
}
@Transactional(readOnly = true)
public Page<PostEntity> getAll(int page, int size) {
return repository.findAll(PageRequest.of(page, size));
}
@Transactional(readOnly = true)
public PostEntity get(Long id) {
return repository.findById(id)
.orElseThrow(() -> new NotFoundException(PostEntity.class, id));
}
@Transactional
public PostEntity create(PostEntity entity) {
if (entity == null) {
throw new IllegalArgumentException("Entity is null");
}
repository.save(entity);
return repository.save(entity);
}
@Transactional
public PostEntity addLike(Long id) {
final PostEntity existsEntity = get(id);
existsEntity.setLiked((existsEntity.getLiked() + 1));
repository.save(existsEntity);
return existsEntity;
}
@Transactional
public PostEntity removeLiked(Long id) {
final PostEntity existsEntity = get(id);
existsEntity.setLiked((existsEntity.getLiked() - 1));
repository.save(existsEntity);
return existsEntity;
}
@Transactional
public PostEntity addView(Long id) {
final PostEntity existsEntity = get(id);
existsEntity.setViewed((existsEntity.getViewed() + 1));
repository.save(existsEntity);
return existsEntity;
}
@Transactional
public PostEntity update(Long id, PostEntity entity) {
final PostEntity existsEntity = get(id);
existsEntity.setText(entity.getText());
repository.save(existsEntity);
return existsEntity;
}
@Transactional
public PostEntity delete(Long id) {
final PostEntity existsEntity = get(id);
repository.delete(existsEntity);
return existsEntity;
}
}

View File

@ -0,0 +1,94 @@
package com.example.demo.users.api;
import java.util.List;
import org.modelmapper.ModelMapper;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.core.configuration.Constants;
import com.example.demo.users.model.UserEntity;
import com.example.demo.users.model.UserTop;
import com.example.demo.users.service.UserService;
import jakarta.validation.Valid;
@RestController
@RequestMapping(Constants.API_URL + "/user")
public class UserController {
private final UserService userService;
private final ModelMapper modelMapper;
public UserController(UserService userService, ModelMapper modelMapper) {
this.userService = userService;
this.modelMapper = modelMapper;
}
private UserDto toDto(UserEntity entity) {
var model = modelMapper.map(entity, UserDto.class);
if (entity.getFriends() != null) {
for (UserEntity user : entity.getFriends()) {
model.addFriendId(user.getId());
}
}
return model;
}
public UserTopDto toTopDto(UserTop user) {
return modelMapper.map(user, UserTopDto.class);
}
private UserEntity toEntity(UserDto dto) {
return modelMapper.map(dto, UserEntity.class);
}
@GetMapping
public List<UserDto> getAll() {
return userService.getAll().stream().map(this::toDto).toList();
}
@GetMapping("/{id}")
public UserDto get(@PathVariable(name = "id") Long id) {
return toDto(userService.get(id));
}
@PostMapping
public UserDto create(@RequestBody @Valid UserDto dto) {
return toDto(userService.create(toEntity(dto)));
}
@PostMapping("/friends/{id}")
public UserDto addFriend(@PathVariable(name = "id") Long id, @RequestBody UserDto dto) {
return toDto(userService.addFriend(id, toEntity(dto)));
}
@DeleteMapping("/friends/{id}")
public UserDto removeFriend(@PathVariable(name = "id") Long id, @RequestBody UserDto dto) {
return toDto(userService.removeFriend(id, toEntity(dto)));
}
@PutMapping("/{id}")
public UserDto update(@PathVariable(name = "id") Long id, @RequestBody UserDto dto) {
return toDto(userService.update(id, toEntity(dto)));
}
@DeleteMapping("/{id}")
public UserDto delete(@PathVariable(name = "id") Long id) {
return toDto(userService.delete(id));
}
@GetMapping("/topFriends")
public List<UserTopDto> getMethod() {
return userService.getTop(0, 5).getContent().stream()
.map(this::toTopDto)
.toList();
}
}

View File

@ -0,0 +1,68 @@
package com.example.demo.users.api;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonProperty.Access;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
public class UserDto {
@JsonProperty(access = Access.READ_ONLY)
private Long id;
@NotBlank
@Size(min = 3, max = 20)
private String nickname;
@NotBlank
@Size(min = 3, max = 20)
private String email;
@NotBlank
@Size(min = 3, max = 20)
private String password;
private List<Long> friendsId = new ArrayList<>();
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public List<Long> getFriendsId() {
return friendsId;
}
public void addFriendId(long Id) {
friendsId.add(Id);
}
}

View File

@ -0,0 +1,26 @@
package com.example.demo.users.api;
public class UserTopDto {
private String user;
private int count;
public UserTopDto() {
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
}

View File

@ -0,0 +1,92 @@
package com.example.demo.users.model;
import java.util.ArrayList;
import java.util.Objects;
import java.util.List;
import com.example.demo.core.model.BaseEntity;
import jakarta.persistence.CascadeType;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.JoinTable;
import jakarta.persistence.ManyToMany;
import jakarta.persistence.Table;
@Entity
@Table(name = "users")
public class UserEntity extends BaseEntity {
@Column(nullable = false, length = 20)
private String nickname;
@Column(nullable = false, unique = true, length = 20)
private String email;
@Column(nullable = false, length = 20)
private String password;
@ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.REFRESH)
@JoinTable(name = "user_friendship", joinColumns = @JoinColumn(name = "first_user_id", referencedColumnName = "Id", nullable = false), inverseJoinColumns = @JoinColumn(name = "second_user_id", referencedColumnName = "Id", nullable = false))
private List<UserEntity> friends = new ArrayList<UserEntity>();
public UserEntity() {
}
public UserEntity(String nickname, String email, String password, List<UserEntity> friends) {
this.nickname = nickname;
this.email = email;
this.password = password;
this.friends = friends;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public List<UserEntity> getFriends() {
return friends;
}
public void setFriends(List<UserEntity> friends) {
this.friends = friends;
}
@Override
public int hashCode() {
return Objects.hash(id, nickname, email, password, friends);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null || getClass() != obj.getClass())
return false;
final UserEntity other = (UserEntity) obj;
return Objects.equals(other.getId(), id)
&& Objects.equals(other.getFriends(), friends)
&& Objects.equals(other.getNickname(), nickname)
&& Objects.equals(other.getEmail(), email)
&& Objects.equals(other.getPassword(), password);
}
}

Some files were not shown because too many files have changed in this diff Show More