kochkareva_elizaveta_lab_3 is ready

This commit is contained in:
Kochkareva 2024-01-19 11:38:02 +04:00
parent 60ef5724cd
commit c96f7cf563
38 changed files with 1852 additions and 0 deletions

View File

@ -0,0 +1,280 @@
# Лабораторная работа 3.
### Задание
**Цель**: изучение современных технологий контейнеризации.
**Задачи**:
- Установить средство контейнеризации docker.
- Изучить применение и принципы docker.
- Изучить утилиту docker-compose и структуру файла docker-compose.yml.
- Развернуть не менее 3х различных сервисов при помощи docker-compose.
- Оформить отчёт в формате Markdown и создать Pull Request в git-репозитории.
### Как запустить лабораторную работу
В директории с файлом характеристик docker-compose.yaml выполнить команду:
```
docker-compose -f docker-compose.yaml up
```
### Описание лабораторной работы
#### Создание базы данных
Каждый сервис реализует CRUD-операции, поэтому были выбраны следующие сущности, соответствующие теме диплома: упражнение и тренировка. Эти сущности связаны отношением один ко многим. Созданные таблицы базы данных:
```sql
-- Создание таблицы тренировок
CREATE TABLE t_training (
id SERIAL PRIMARY KEY,
name VARCHAR(255) NOT NULL,
description VARCHAR(255) NOT NULL
);
-- Создание таблицы упражнений
CREATE TABLE t_exercise (
id SERIAL PRIMARY KEY,
name VARCHAR(255) NOT NULL,
description VARCHAR(255) NOT NULL,
id_training INTEGER,
FOREIGN KEY (id_training) REFERENCES t_training(id)
);
```
Также в файле `docker-compose.yaml` создадим соответствующий сервис:
```dockerfile
#database
postgresql:
#configuration
image: postgres:latest
ports:
- 5432:5432
environment:
POSTGRES_PASSWORD: admin
POSTGRES_USER: admin
POSTGRES_DB: traininarium
volumes:
- ./database.sql:/docker-entrypoint-initdb.d/database.sql
restart: always
networks:
- mynetwork
```
- `image: postgres:latest` указывает, что мы хотим использовать последнюю версию образа `PostgreSQL`.
- `ports: - 5432:5432` пробрасывает порт 5432 контейнера (стандартный порт PostgreSQL) на порт 5432 хоста, чтобы можно было подключаться к базе данных с внешнего устройства.
- `environment` определяет переменные окружения, которые будут использоваться контейнером. В данном случае, устанавливаются значения для переменных `POSTGRES_PASSWORD`, `POSTGRES_USER` и `POSTGRES_DB`.
- `volumes` указывает путь к файлу `database.sql` в текущей директории, который будет использоваться для инициализации базы данных при запуске контейнера.
- `restart: always` гарантирует, что контейнер будет перезапущен автоматически, если он остановится или перезагрузится.
- `networks` определяет сеть, к которой будет присоединен контейнер. В данном случае, контейнер будет присоединен к сети с именем `mynetwork`.
В итоге будет создан контейнер с базой данных `PostgreSQL`, настроенной с указанными переменными окружения, проброшенным портом и файлом `database.sql` для инициализации базы данных.
#### Создание микросервиса *Упражнения*
После реализации необходимых элементов микросервиса, таких как: controller, model, modelDTO, repository и service, создадим конфигурационный файл Dockerfile, в котором пропишем следующее:
```dockerfile
FROM openjdk:17-jdk
WORKDIR /app
COPY ./exercise-app/build/libs/exercise-app-0.0.1-SNAPSHOT.jar /app/exercise-app-0.0.1-SNAPSHOT.jar
EXPOSE 8081
CMD ["java", "-jar", "exercise-app-0.0.1-SNAPSHOT.jar"]
```
В данном файле мы указываем базовый образ, который будет использован для создания контейнера (*OpenJDK* версии 17 с установленным *JDK*); устанавливаем рабочую директорию внутри контейнера, где будут размещены файлы приложения; указываем, что приложение внутри контейнера будет слушать на порту 8081 и определяем команду, которая будет выполнена при запуске контейнера, а именно запуск приложения *Java* из файла `exercise-app-0.0.1-SNAPSHOT.jar` внутри контейнера.
Также в файле `docker-compose.yaml` создадим соответствующий сервис:
```dockerfile
exercise-service:
build:
context: .
dockerfile: ./exercise-app/Dockerfile
ports:
- 8081:8081
environment:
DATASOURCE_URL: jdbc:postgresql://postgresql:5432/traininarium
DATASOURCE_USERNAME: admin
DATASOURCE_PASSWORD: admin
restart: always
#wait build database
depends_on:
- postgresql
networks:
- mynetwork
```
- `exercise-service` является именем сервиса, который будет создан и запущен в контейнере.
- `context: .` указывает, что контекстом для сборки Docker-образа является текущая директория.
- `dockerfile: ./exercise-app/Dockerfile` указывает путь к `Dockerfile`, который будет использоваться для сборки образа.
- `ports` определяет проброс портов между хостом и контейнером.
`8081:8081` указывает, что порт 8081 на хосте будет проброшен на порт 8081 внутри контейнера.
- `environment` определяет переменные окружения, которые будут доступны внутри контейнера.
`DATASOURCE_URL: jdbc:postgresql://postgresql:5432/traininarium` определяет URL для подключения к базе данных `PostgreSQL`.
`DATASOURCE_USERNAME: admin` определяет имя пользователя для подключения к базе данных.
`DATASOURCE_PASSWORD: admin` определяет пароль для подключения к базе данных.
- `restart: always` указывает, что контейнер будет автоматически перезапущен в случае его остановки.
depends_on определяет зависимость данного сервиса от другого сервиса.
- `postgresql` указывает, что данный сервис зависит от сервиса с именем `postgresql`.
- `mynetwork` указывает, что контейнер будет присоединен к сети с именем `mynetwork`.
#### Создание микросервиса *Тренировки*
Аналогично реализуем controller, model, modelDTO, repository и service для микросервиса *Тренировки*, но дополняя кодом отправки запроса к сервису *Упражнений*. Пример запроса к сервису *Упражнений*:
```java
public List<TrainingDto> findAllTraining() throws Exception {
RestTemplate restTemplate = new RestTemplate();
HttpEntity<String> entity = new HttpEntity<>(new HttpHeaders());
List<TrainingDto> trainingDtos = new ArrayList<>();
for (Training training : trainingRepository.findAll()) {
TrainingDto trainingDto = new TrainingDto();
trainingDto.setId(training.getId());
trainingDto.setName(training.getName());
trainingDto.setDescription(training.getDescription());
ResponseEntity<String> response = restTemplate.exchange(
"http://" + exercise_service_host + "/exercise/training/" + trainingDto.getId(), HttpMethod.GET, entity, String.class);
if (response.getStatusCode().is2xxSuccessful()) {
String responseBody = response.getBody();
ObjectMapper objectMapper = new ObjectMapper();
List<ExerciseDto> exerciseDtos;
try {
exerciseDtos = objectMapper.readValue(responseBody, ArrayList.class);
trainingDto.setExercises(exerciseDtos);
} catch (JsonProcessingException e) {
throw new Exception("Не удалось десериализовать тело запроса в объект");
}
} else {
throw new Exception("Ошибка получения объекта");
}
trainingDtos.add(trainingDto);
}
return trainingDtos;
}
```
Теперь создадим конфигурационный файл Dockerfile, в котором пропишем следующее:
```dockerfile
FROM openjdk:17-jdk
WORKDIR /app
COPY ./training-app/build/libs/training-app-0.0.1-SNAPSHOT.jar /app/training-app-0.0.1-SNAPSHOT.jar
EXPOSE 8082
CMD ["java", "-jar", "training-app-0.0.1-SNAPSHOT.jar"]
```
В данном файле мы указываем базовый образ, который будет использован для создания контейнера (*OpenJDK* версии 17 с установленным *JDK*); устанавливаем рабочую директорию внутри контейнера, где будут размещены файлы приложения; указываем, что приложение внутри контейнера будет слушать на порту 8082; копируем файл `training-app-0.0.1-SNAPSHOT.jar` из локальной директории `./training-app/build/libs/` внутрь контейнера в папку `/app` и определяем команду, которая будет выполнена при запуске контейнера, а именно запуск приложения Java из файла `training-app-0.0.1-SNAPSHOT.jar` внутри контейнера.
Также в файле `docker-compose.yaml` создадим соответствующий сервис:
```dockerfile
training-service:
build:
context: .
dockerfile: ./training-app/Dockerfile
ports:
- 8082:8082
environment:
EXERCISE_SERVICE_HOST: exercise-service:8081
DATASOURCE_URL: jdbc:postgresql://postgresql:5432/traininarium
DATASOURCE_USERNAME: admin
DATASOURCE_PASSWORD: admin
restart: always
#wait build database
depends_on:
- postgresql
networks:
- mynetwork
```
- `training-service` является именем сервиса, который будет создан и запущен в контейнере.
- `context: .` указывает, что контекстом для сборки Docker-образа является текущая директория.
- `dockerfile: ./training-app/Dockerfile` указывает путь к `Dockerfile`, который будет использоваться для сборки образа.
- `8082:8082` указывает, что порт 8082 на хосте будет проброшен на порт 8082 внутри контейнера.
- `environment` определяет переменные окружения, которые будут доступны внутри контейнера.
`EXERCISE_SERVICE_HOST: exercise-service:8081` определяет хост и порт для подключения к сервису `exercise-service`.
`DATASOURCE_URL: jdbc:postgresql://postgresql:5432/traininarium` определяет URL для подключения к базе данных `PostgreSQL`.
`DATASOURCE_USERNAME: admin` определяет имя пользователя для подключения к базе данных.
`DATASOURCE_PASSWORD: admin` определяет пароль для подключения к базе данных.
- `restart: always` указывает, что контейнер будет автоматически перезапущен в случае его остановки.
- `depends_on` определяет зависимость данного сервиса от другого сервиса, данный сервис зависит от сервиса с именем `postgresql`.
- `mynetwork` указывает, что контейнер будет присоединен к сети с именем `mynetwork`.
#### Реализация gateway при помощи *nginx*
Для того, чтобы использовать *Nginx* для обработки HTTP-запросов и маршрутизации их к соответствующим сервисам, создадим файл конфигурации *Nginx*:
```
events {
worker_connections 1024;
}
http {
upstream exercise-service {
server exercise-service:8081;
}
upstream training-service {
server training-service:8082;
}
server {
listen 80;
listen [::]:80;
server_name localhost;
location /exercise-service/ {
proxy_pass http://exercise-service/;
}
location /training-service/ {
proxy_pass http://training-service/;
}
}
}
```
- `events` определяет настройки событий для сервера *Nginx*.
- `worker_connections 1024` указывает максимальное количество одновременных соединений, которые могут быть обработаны сервером.
- `http` определяет настройки HTTP-сервера *Nginx*.
- `upstream` определяет группу серверов, которые могут обрабатывать запросы.
`exercise-service` определяет группу серверов с именем `exercise-service`, в которой находится только один сервер `exercise-service:8081`.
`training-service` определяет группу серверов с именем `training-service`, в которой находится только один сервер `training-service:8082`.
- `server` определяет настройки для конкретного виртуального сервера.
- `listen 80` указывает на порт, на котором сервер будет слушать входящие HTTP-запросы.
- `listen [::]:80` указывает на IPv6-адрес и порт, на котором сервер будет слушать входящие HTTP-запросы.
- `server_name localhost` указывает имя сервера.
- `location /exercise-service/` определяет местоположение для обработки запросов, которые начинаются с `/exercise-service/`.
`proxy_pass http://exercise-service/` указывает, что все запросы, начинающиеся с `/exercise-service/`, должны быть перенаправлены на группу серверов `exercise-service`.
- `location /training-service/` определяет местоположение для обработки запросов, которые начинаются с `/training-service/`.
`proxy_pass http://training-service/` указывает, что все запросы, начинающиеся с `/training-service/`, должны быть перенаправлены на группу серверов `training-service`.
Таким образом, при запуске сервера *Nginx* с использованием этого конфигурационного файла, сервер будет слушать входящие HTTP-запросы на порту 80 и маршрутизировать запросы, начинающиеся с `/exercise-service/`, на группу серверов `exercise-service`, а запросы, начинающиеся с `/training-service/`, на группу серверов `training-service`.
Далее в файле `docker-compose.yaml` создадим соответствующий сервис:
```dockerfile
nginx:
#configuration
image: nginx:latest
ports:
- 80:80
volumes:
- ./nginx.conf:/etc/nginx/nginx.conf
restart: always
depends_on:
- training-service
- exercise-service
networks:
- mynetwork
```
- `nginx` - это название сервиса, который будет запущен в контейнере.
- `image: nginx:latest` указывает на использование последней версии образа *Nginx* из *Docker Hub*.
- `80:80` пробрасывает порт 80 контейнера на порт 80 хостовой машины.
- `volumes` определяет привязку тома между контейнером и хостовой машиной.
- `./nginx.conf:/etc/nginx/nginx.conf` привязывает файл `nginx.conf` из текущего рабочего каталога хостовой машины к файлу `nginx.conf` внутри контейнера *Nginx*. Это позволяет настроить *Nginx* с помощью внешнего файла конфигурации.
- `restart: always` указывает, что контейнер должен быть автоматически перезапущен при его остановке или падении.
- `depends_on` указывает на зависимость этого сервиса от других сервисов.
- `training-service` указывает, что контейнер Nginx должен быть запущен после контейнера `training-service`.
- `exercise-service` указывает, что контейнер Nginx должен быть запущен после контейнера `exercise-service`.
- `networks` определяет сети, к которым будет присоединен контейнер.
- `mynetwork` добавляет контейнер в сеть с именем `mynetwork`.
### Видео
https://disk.yandex.ru/i/OYPw_Tzl0QrzIw

View File

@ -0,0 +1,14 @@
-- Создание таблицы тренировок
CREATE TABLE t_training (
id SERIAL PRIMARY KEY,
name VARCHAR(255) NOT NULL,
description VARCHAR(255) NOT NULL
);
-- Создание таблицы упражнений
CREATE TABLE t_exercise (
id SERIAL PRIMARY KEY,
name VARCHAR(255) NOT NULL,
description VARCHAR(255) NOT NULL,
id_training INTEGER,
FOREIGN KEY (id_training) REFERENCES t_training(id)
);

View File

@ -0,0 +1,73 @@
version: '3'
networks:
mynetwork:
driver: bridge
#all necessary containers(services)
services:
#database
postgresql:
#configuration
image: postgres:latest
ports:
- 5432:5432
environment:
POSTGRES_PASSWORD: admin
POSTGRES_USER: admin
POSTGRES_DB: traininarium
volumes:
- ./database.sql:/docker-entrypoint-initdb.d/database.sql
restart: always
networks:
- mynetwork
exercise-service:
build:
context: .
dockerfile: ./exercise-app/Dockerfile
ports:
- 8081:8081
environment:
DATASOURCE_URL: jdbc:postgresql://postgresql:5432/traininarium
DATASOURCE_USERNAME: admin
DATASOURCE_PASSWORD: admin
restart: always
#wait build database
depends_on:
- postgresql
networks:
- mynetwork
training-service:
build:
context: .
dockerfile: ./training-app/Dockerfile
ports:
- 8082:8082
environment:
EXERCISE_SERVICE_HOST: exercise-service:8081
DATASOURCE_URL: jdbc:postgresql://postgresql:5432/traininarium
DATASOURCE_USERNAME: admin
DATASOURCE_PASSWORD: admin
restart: always
#wait build database
depends_on:
- postgresql
networks:
- mynetwork
nginx:
#configuration
image: nginx:latest
ports:
- 80:80
volumes:
- ./nginx.conf:/etc/nginx/nginx.conf
restart: always
depends_on:
- training-service
- exercise-service
networks:
- mynetwork

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

@ -0,0 +1,7 @@
FROM openjdk:17-jdk
WORKDIR /app
COPY ./exercise-app/build/libs/exercise-app-0.0.1-SNAPSHOT.jar /app/exercise-app-0.0.1-SNAPSHOT.jar
EXPOSE 8081
CMD ["java", "-jar", "exercise-app-0.0.1-SNAPSHOT.jar"]

View File

@ -0,0 +1,42 @@
plugins {
id 'java'
id 'org.springframework.boot' version '3.1.5'
id 'io.spring.dependency-management' version '1.1.3'
}
group = 'com.services'
version = '0.0.1-SNAPSHOT'
java {
sourceCompatibility = '17'
}
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-validation'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-devtools'
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.0.3'
compileOnly 'org.projectlombok:lombok'
runtimeOnly 'org.postgresql:postgresql'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
tasks.named('bootBuildImage') {
builder = 'paketobuildpacks/builder-jammy-base:latest'
}
tasks.named('test') {
useJUnitPlatform()
}

View File

@ -0,0 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.4-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

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" "$@"

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

View File

@ -0,0 +1 @@
rootProject.name = 'exercise-app'

View File

@ -0,0 +1,13 @@
package com.services.exerciseapp;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ExerciseAppApplication {
public static void main(String[] args) {
SpringApplication.run(ExerciseAppApplication.class, args);
}
}

View File

@ -0,0 +1,49 @@
package com.services.exerciseapp.controller;
import com.services.exerciseapp.model.Exercise;
import com.services.exerciseapp.modelDto.ExerciseDto;
import com.services.exerciseapp.service.ExerciseService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/exercise")
public class ExerciseController {
private final ExerciseService exerciseService;
public ExerciseController(ExerciseService exerciseService) {
this.exerciseService = exerciseService;
}
@GetMapping("/")
public List<Exercise> getExercises(){
return exerciseService.findAllExercise();
}
@GetMapping("/{id}")
public Exercise getExercise(@PathVariable int id){
return exerciseService.findById(id);
}
@GetMapping("/training/{id}")
public List<Exercise> getTrainingExercises(@PathVariable int id){
return exerciseService.findTrainingExercises(id);
}
@PostMapping("/")
public Exercise createExercise(@RequestBody ExerciseDto exerciseDto){
return exerciseService.addExercise(exerciseDto);
}
@PutMapping("/")
public Exercise updateExercise(@RequestBody ExerciseDto exerciseDto){
return exerciseService.updateExercise(exerciseDto);
}
@DeleteMapping("/{id}")
public void deleteExercise(@PathVariable int id){
exerciseService.deleteExercise(id);
}
}

View File

@ -0,0 +1,50 @@
package com.services.exerciseapp.model;
import jakarta.persistence.*;
import lombok.Data;
import lombok.experimental.Accessors;
@Entity
@Table(name = "t_exercise")
@Data
@Accessors(chain = true)
public class Exercise {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
private String description;
private Integer id_training;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getId_training() {
return id_training;
}
public void setId_training(Integer id_training) {
this.id_training = id_training;
}
}

View File

@ -0,0 +1,43 @@
package com.services.exerciseapp.modelDto;
import jakarta.annotation.Nullable;
public class ExerciseDto {
private int id;
private String name;
private String description;
@Nullable
private Integer id_training;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getId_training() {
return id_training;
}
public void setId_training(Integer id_training) {
this.id_training = id_training;
}
}

View File

@ -0,0 +1,7 @@
package com.services.exerciseapp.repository;
import com.services.exerciseapp.model.Exercise;
import org.springframework.data.jpa.repository.JpaRepository;
public interface ExerciseRepository extends JpaRepository<Exercise, Integer> {
}

View File

@ -0,0 +1,57 @@
package com.services.exerciseapp.service;
import com.services.exerciseapp.model.Exercise;
import com.services.exerciseapp.modelDto.ExerciseDto;
import com.services.exerciseapp.repository.ExerciseRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class ExerciseService {
private final ExerciseRepository exerciseRepository;
public ExerciseService(ExerciseRepository exerciseRepository) {
this.exerciseRepository = exerciseRepository;
}
public List<Exercise> findAllExercise(){
return exerciseRepository.findAll();
}
public Exercise findById(int id){
return exerciseRepository.findById(id).orElseThrow();
}
public List<Exercise> findTrainingExercises(int training_id){
return exerciseRepository.findAll().stream()
.filter(exercise -> exercise.getId_training() != null)
.filter(exercise -> exercise.getId_training() == training_id)
.toList();
}
public Exercise addExercise(ExerciseDto exerciseDto) {
Exercise exercise = new Exercise();
exercise.setName(exerciseDto.getName());
exercise.setDescription(exerciseDto.getDescription());
if (exerciseDto.getId_training() != null) {
exercise.setId_training(exerciseDto.getId_training());
}
return exerciseRepository.save(exercise);
}
public Exercise updateExercise(ExerciseDto exerciseDto){
Exercise exercise = exerciseRepository.findById(exerciseDto.getId()).orElseThrow();
exercise.setName(exerciseDto.getName());
exercise.setDescription(exerciseDto.getDescription());
if (exerciseDto.getId_training() != null) {
exercise.setId_training(exerciseDto.getId_training());
}
return exerciseRepository.save(exercise);
}
public void deleteExercise(int id){
exerciseRepository.delete(exerciseRepository.findById(id).orElseThrow());
}
}

View File

@ -0,0 +1,7 @@
server:
port: "8081"
spring:
datasource:
url: ${DATASOURCE_URL:jdbc:postgresql://localhost:5432/traininarium}
username: ${DATASOURCE_USERNAME:admin}
password: ${DATASOURCE_PASSWORD:admin}

View File

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

Binary file not shown.

View File

@ -0,0 +1,28 @@
events {
worker_connections 1024;
}
http {
upstream exercise-service {
server exercise-service:8081;
}
upstream training-service {
server training-service:8082;
}
server {
listen 80;
listen [::]:80;
server_name localhost;
location /exercise-service/ {
proxy_pass http://exercise-service/;
}
location /training-service/ {
proxy_pass http://training-service/;
}
}
}

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

@ -0,0 +1,7 @@
FROM openjdk:17-jdk
WORKDIR /app
COPY ./training-app/build/libs/training-app-0.0.1-SNAPSHOT.jar /app/training-app-0.0.1-SNAPSHOT.jar
EXPOSE 8082
CMD ["java", "-jar", "training-app-0.0.1-SNAPSHOT.jar"]

View File

@ -0,0 +1,42 @@
plugins {
id 'java'
id 'org.springframework.boot' version '3.1.5'
id 'io.spring.dependency-management' version '1.1.3'
}
group = 'com.services'
version = '0.0.1-SNAPSHOT'
java {
sourceCompatibility = '17'
}
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-validation'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-devtools'
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.0.3'
compileOnly 'org.projectlombok:lombok'
runtimeOnly 'org.postgresql:postgresql'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
tasks.named('bootBuildImage') {
builder = 'paketobuildpacks/builder-jammy-base:latest'
}
tasks.named('test') {
useJUnitPlatform()
}

View File

@ -0,0 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.4-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

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" "$@"

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

View File

@ -0,0 +1 @@
rootProject.name = 'training-app'

View File

@ -0,0 +1,13 @@
package com.services.trainingapp;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class TrainingAppApplication {
public static void main(String[] args) {
SpringApplication.run(TrainingAppApplication.class, args);
}
}

View File

@ -0,0 +1,49 @@
package com.services.trainingapp.controller;
import com.services.trainingapp.model.Training;
import com.services.trainingapp.modelDto.TrainingDto;
import com.services.trainingapp.service.TrainingService;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/training")
public class TrainingController {
private final TrainingService trainingService;
public TrainingController(TrainingService trainingService) {
this.trainingService = trainingService;
}
@GetMapping("/")
public List<TrainingDto> getTrainings() throws Exception {
return trainingService.findAllTraining();
}
@GetMapping("/{id}")
public TrainingDto getTraining(@PathVariable int id) throws Exception {
return trainingService.findById(id);
}
@PostMapping("/")
public Training createTraining(@RequestBody TrainingDto trainingDto){
return trainingService.addTraining(trainingDto);
}
@PutMapping("/")
public Training updateTraining(@RequestBody TrainingDto trainingDto){
return trainingService.updateTraining(trainingDto);
}
@DeleteMapping("/{id}")
public void deleteTraining(@PathVariable int id){
trainingService.deleteTraining(id);
}
@PatchMapping("/{id_exercise}/{id_training}")
public void addExerciseToTraining(@PathVariable int id_exercise,
@PathVariable int id_training) throws Exception {
trainingService.addExerciseToTraining(id_exercise, id_training);
}
}

View File

@ -0,0 +1,41 @@
package com.services.trainingapp.model;
import jakarta.persistence.*;
import lombok.Data;
import lombok.experimental.Accessors;
@Entity
@Table(name = "t_training")
@Data
@Accessors(chain = true)
public class Training {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
private String description;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}

View File

@ -0,0 +1,44 @@
package com.services.trainingapp.modelDto;
import jakarta.annotation.Nullable;
public class ExerciseDto {
private int id;
private String name;
private String description;
@Nullable
private Integer id_training;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Nullable
public Integer getId_training() {
return id_training;
}
public void setId_training(@Nullable Integer id_training) {
this.id_training = id_training;
}
}

View File

@ -0,0 +1,42 @@
package com.services.trainingapp.modelDto;
import java.util.List;
public class TrainingDto {
private int id;
private String name;
private String description;
private List<ExerciseDto> exercises;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public List<ExerciseDto> getExercises() {
return exercises;
}
public void setExercises(List<ExerciseDto> exercises) {
this.exercises = exercises;
}
}

View File

@ -0,0 +1,7 @@
package com.services.trainingapp.repository;
import com.services.trainingapp.model.Training;
import org.springframework.data.jpa.repository.JpaRepository;
public interface TrainingRepository extends JpaRepository<Training, Integer> {
}

View File

@ -0,0 +1,130 @@
package com.services.trainingapp.service;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.services.trainingapp.model.Training;
import com.services.trainingapp.modelDto.ExerciseDto;
import com.services.trainingapp.modelDto.TrainingDto;
import com.services.trainingapp.repository.TrainingRepository;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.util.ArrayList;
import java.util.List;
@Service
public class TrainingService {
private final TrainingRepository trainingRepository;
@Value("${exercise-service.host}")
private String exercise_service_host;
public TrainingService(TrainingRepository trainingRepository) {
this.trainingRepository = trainingRepository;
}
public List<TrainingDto> findAllTraining() throws Exception {
RestTemplate restTemplate = new RestTemplate();
HttpEntity<String> entity = new HttpEntity<>(new HttpHeaders());
List<TrainingDto> trainingDtos = new ArrayList<>();
for (Training training : trainingRepository.findAll()) {
TrainingDto trainingDto = new TrainingDto();
trainingDto.setId(training.getId());
trainingDto.setName(training.getName());
trainingDto.setDescription(training.getDescription());
ResponseEntity<String> response = restTemplate.exchange(
"http://" + exercise_service_host + "/exercise/training/" + trainingDto.getId(), HttpMethod.GET, entity, String.class);
if (response.getStatusCode().is2xxSuccessful()) {
String responseBody = response.getBody();
ObjectMapper objectMapper = new ObjectMapper();
List<ExerciseDto> exerciseDtos;
try {
exerciseDtos = objectMapper.readValue(responseBody, ArrayList.class);
trainingDto.setExercises(exerciseDtos);
} catch (JsonProcessingException e) {
throw new Exception("Не удалось десериализовать тело запроса в объект");
}
} else {
throw new Exception("Ошибка получения объекта");
}
trainingDtos.add(trainingDto);
}
return trainingDtos;
}
public TrainingDto findById(int id) throws Exception {
RestTemplate restTemplate = new RestTemplate();
HttpEntity<String> entity = new HttpEntity<>(new HttpHeaders());
TrainingDto trainingDto = new TrainingDto();
Training training = trainingRepository.findById(id).orElseThrow();
trainingDto.setId(training.getId());
trainingDto.setName(training.getName());
trainingDto.setDescription(training.getDescription());
ResponseEntity<String> response = restTemplate.exchange(
"http://" + exercise_service_host + "/exercise/training/" + trainingDto.getId(), HttpMethod.GET, entity, String.class);
if (response.getStatusCode().is2xxSuccessful()) {
String responseBody = response.getBody();
ObjectMapper objectMapper = new ObjectMapper();
List<ExerciseDto> exerciseDtos;
try {
exerciseDtos = objectMapper.readValue(responseBody, ArrayList.class);
trainingDto.setExercises(exerciseDtos);
} catch (JsonProcessingException e) {
throw new Exception("Не удалось десериализовать тело запроса в объект");
}
} else {
throw new Exception("Ошибка получения объекта");
}
return trainingDto;
}
public Training addTraining(TrainingDto trainingDto) {
Training training = new Training();
training.setName(trainingDto.getName());
training.setDescription(trainingDto.getDescription());
return trainingRepository.save(training);
}
public Training updateTraining(TrainingDto trainingDto){
Training training = trainingRepository.findById(trainingDto.getId()).orElseThrow();
training.setName(trainingDto.getName());
training.setDescription(trainingDto.getDescription());
return trainingRepository.save(training);
}
public void deleteTraining(int id){
trainingRepository.delete(trainingRepository.findById(id).orElseThrow());
}
public void addExerciseToTraining(int exercise_id, int training_id) throws Exception {
RestTemplate restTemplate = new RestTemplate();
HttpEntity<String> entity = new HttpEntity<>(new HttpHeaders());
ResponseEntity<String> response = restTemplate.exchange(
"http://" + exercise_service_host + "/exercise/" + exercise_id, HttpMethod.GET, entity, String.class
);
if (response.getStatusCode().is2xxSuccessful()) {
String responseBody = response.getBody();
ObjectMapper objectMapper = new ObjectMapper();
ExerciseDto exerciseDto;
try {
exerciseDto = objectMapper.readValue(responseBody, ExerciseDto.class);
} catch (JsonProcessingException e) {
throw new Exception("Не удалось десериализовать тело запроса в объект");
}
exerciseDto.setId_training(training_id);
restTemplate.exchange("http://" + exercise_service_host + "/exercise/", HttpMethod.PUT, new HttpEntity<>(exerciseDto), String.class);
} else {
throw new Exception("Ошибка получения объекта");
}
}
}

View File

@ -0,0 +1,9 @@
exercise-service:
host: ${EXERCISE_SERVICE_HOST:localhost:8080}
server:
port: "8082"
spring:
datasource:
url: ${DATASOURCE_URL:jdbc:postgresql://localhost:5432/traininarium}
username: ${DATASOURCE_USERNAME:admin}
password: ${DATASOURCE_PASSWORD:admin}

View File

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