diff --git a/2021-11/spring-27-integration-example/src/main/java/ru/otus/spring/integration/App.java b/2021-11/spring-27-integration-example/src/main/java/ru/otus/spring/integration/App.java index 4aaa6f39..fe2ccde0 100644 --- a/2021-11/spring-27-integration-example/src/main/java/ru/otus/spring/integration/App.java +++ b/2021-11/spring-27-integration-example/src/main/java/ru/otus/spring/integration/App.java @@ -1,6 +1,8 @@ package ru.otus.spring.integration; +import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.support.AbstractApplicationContext; import ru.otus.spring.integration.service.OrderService; @@ -9,7 +11,7 @@ import ru.otus.spring.integration.service.OrderService; public class App { public static void main( String[] args ) throws Exception { - AbstractApplicationContext ctx = new AnnotationConfigApplicationContext( App.class ); + ConfigurableApplicationContext ctx = SpringApplication.run(App.class, args); OrderService orderService = ctx.getBean(OrderService.class); orderService.startOrdersLoop(); diff --git a/2021-11/spring-30/requests.http b/2021-11/spring-30/requests.http index c5158170..c2364679 100644 --- a/2021-11/spring-30/requests.http +++ b/2021-11/spring-30/requests.http @@ -45,18 +45,67 @@ GET http://localhost:8080/actuator/metrics/process.cpu.usage ### Используемая JVM память GET http://localhost:8080/actuator/metrics/jvm.memory.used -### А вот это метрики +### Получение данных о запросах +# Дополнительно можно настроить SLA, персентили и т.д. +# причём для отдельных запросов +GET http://localhost:8080/actuator/metrics/http.server.requests +### А вот все метрики для Promehteus GET http://localhost:8080/actuator/prometheus -### Нажми меня) -GET http://localhost:8080/counter +### Смотрим начальное значение counter.example +GET http://localhost:8080/actuator/metrics/counter.example -### Нажми меня) +### Увеличиваем counter.example +POST http://localhost:8080/counter -GET http://localhost:8080/gauge +### Действительно, counter поменялся +GET http://localhost:8080/actuator/metrics/counter.example -### А вот эт REST +### Смотрим начальное значение gauge.example +GET http://localhost:8080/actuator/metrics/gauge.example + +### Добавляем событие в связанный список +POST http://localhost:8080/gauge + +### При запросе Gauge пересчитывается +GET http://localhost:8080/actuator/metrics/gauge.example + + +### Смотрим начальное значение distribution.example +GET http://localhost:8080/actuator/metrics/distribution.example + +### Добавляем случайную величину в распределение +POST http://localhost:8080/distribution + +### Смотрим изменение распределения distribution.example +GET http://localhost:8080/actuator/metrics/distribution.example + + +### Смотрим начальное значение timer.example +GET http://localhost:8080/actuator/metrics/timer.example + +### Изменяем значние таймера +POST http://localhost:8080/timer + +### Смотрим как изменился timer.example +GET http://localhost:8080/actuator/metrics/timer.example + + +### До вызова аннотированного метода - таймер не создаётся +GET http://localhost:8080/actuator/metrics/long.timer.example + +### Создаём и изменяем таймер +POST http://localhost:8080/long-timer + +### Смотрим как выглядит long.timer.example +GET http://localhost:8080/actuator/metrics/long.timer.example + + +### Spring Data REST - Single entity GET http://localhost:8080/person/40 + +### Spring Data REST - Collection +GET http://localhost:8080/person diff --git a/2021-11/spring-30/spring-30-solution/pom.xml b/2021-11/spring-30/spring-30-solution/pom.xml index c908f25a..d4d1d44d 100644 --- a/2021-11/spring-30/spring-30-solution/pom.xml +++ b/2021-11/spring-30/spring-30-solution/pom.xml @@ -39,6 +39,10 @@ org.springframework.boot spring-boot-starter-actuator + + io.micrometer + micrometer-registry-prometheus + org.springframework.data @@ -51,6 +55,14 @@ org.springframework.boot spring-boot-maven-plugin + + + + + build-info + + + diff --git a/2021-11/spring-30/spring-30-solution/src/main/java/ru/otus/spring/microservice/rest/MetricsCounter.java b/2021-11/spring-30/spring-30-solution/src/main/java/ru/otus/spring/microservice/rest/MetricsCounter.java index ff9a4ffc..4ac6ff2e 100644 --- a/2021-11/spring-30/spring-30-solution/src/main/java/ru/otus/spring/microservice/rest/MetricsCounter.java +++ b/2021-11/spring-30/spring-30-solution/src/main/java/ru/otus/spring/microservice/rest/MetricsCounter.java @@ -1,25 +1,103 @@ package ru.otus.spring.microservice.rest; -import io.micrometer.core.instrument.MeterRegistry; +import io.micrometer.core.annotation.Timed; +import io.micrometer.core.instrument.*; +import io.micrometer.core.instrument.binder.BaseUnits; import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RestController; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + @RestController public class MetricsCounter { private final MeterRegistry registry; + private final List objects = new ArrayList<>(); + // Часто сохранять ссылку на созданный Meter удобнее + private final DistributionSummary distribution; + private final Timer timer; public MetricsCounter(MeterRegistry registry) { this.registry = registry; + + // Создание Counter - монотонно возрастающий счётчик + // Counter - можно менять вручную + // В принципе, Counter можно и не регистрировать заранее + Counter.builder("counter.example") + .baseUnit(BaseUnits.EVENTS) + .description("The number of method calls") + .register(registry); + + // Gauge - просто одномерное значение + // Изменяется, только, когда мы его наблюдаем + // Обычно это - какая-то функция от состояния объекта + Gauge.builder("gauge.example", objects, Collection::size) + .baseUnit(BaseUnits.OBJECTS) + .description("The number of events from the array") + .register(registry); + + // Distribution - распределение какой-то величины + // Можно ещё добавить персентиль(и) + distribution = DistributionSummary.builder("distribution.example") + .baseUnit("milliliters") + .description("Milliliters of the teacher tears") + // По умолчанию - только одно значение + .distributionStatisticBufferLength(1000) + .register(registry); + + // Timer - популярный вариант DistributionSummary + // В нём есть удобные методы для работы + // А также можно добавить SLA и гистограмму + timer = Timer.builder("timer.example") + .description("Time of the method execution") + .publishPercentiles(0.50, 0.90, 0.95, 1.00) + .publishPercentileHistogram() + .register(registry); } - @GetMapping("/counter") + @PostMapping("/counter") public void counter() { + // Увеличивает counter registry.counter("counter.example").increment(); } - @GetMapping("/gauge") + @PostMapping("/gauge") public void gauge() { - registry.gauge("gauge.example", Math.random()); + // Косвенно увеличиваем gauge + objects.add(new Object()); + } + + @PostMapping("/distribution") + public void distribution() { + distribution.record(Math.random()); + } + + @PostMapping("/timer") + public void timer() throws InterruptedException { + // Старт таймера + Timer.Sample sample = Timer.start(); + + // Делаем какие-то долгие действия + Thread.sleep((long) (Math.random() * 500)); + + // Окончание замера и запись результата + // Да, это наносекундное разрешение + sample.stop(timer); + } + + // Да, эта аннотация не просто создаст таймер + // Но и будет засекать время специальным аспектом + // longTask - это LongTaskTimer, таймер с миллисекундным разрешением + @Timed( + value = "long.timer.example", + longTask = true, + description = "Annotated timer example" + ) + @PostMapping("/long-timer") + public void longTimer() throws InterruptedException { + Thread.sleep((long) (Math.random() * 5000)); } } diff --git a/2021-11/spring-30/spring-30-solution/src/main/resources/application.yml b/2021-11/spring-30/spring-30-solution/src/main/resources/application.yml index d8d7afdf..5d4870c4 100644 --- a/2021-11/spring-30/spring-30-solution/src/main/resources/application.yml +++ b/2021-11/spring-30/spring-30-solution/src/main/resources/application.yml @@ -7,15 +7,20 @@ management: health: show-details: always info: + # Включает информацию о сборке (spring-boot-maven-plugin) + build: + enabled: true # Включает информацию о приложении из application.yml env: enabled: true - # Включает информацию о git, собранную плагином + # Включает информацию о git (git-commit-id-plugin) git: mode: "full" +# Собственно, сама информация info: app: + # Пример фильтрации свойств Maven version: @project.version@ author: otus description: This is an example description diff --git a/2021-11/spring-32/classwork1/solution.txt b/2021-11/spring-32/classwork1/solution.txt new file mode 100644 index 00000000..d48e28e0 --- /dev/null +++ b/2021-11/spring-32/classwork1/solution.txt @@ -0,0 +1,8 @@ +docker image ls +docker pull hello-world +docker image ls +docker image rm hello-world +docker ps +docker run hello-world +docker ps +docker run -d hello-world diff --git a/2021-11/spring-32/classwork2/solution/Dockerfile b/2021-11/spring-32/classwork2/solution/Dockerfile new file mode 100644 index 00000000..c51e4bde --- /dev/null +++ b/2021-11/spring-32/classwork2/solution/Dockerfile @@ -0,0 +1,4 @@ +FROM nginx:1.11-alpine +COPY index.html /usr/share/nginx/html/index.html +EXPOSE 80 +CMD ["nginx", "-g", "daemon off;"] diff --git a/2021-11/spring-32/classwork2/solution/index.html b/2021-11/spring-32/classwork2/solution/index.html new file mode 100644 index 00000000..f3e333e8 --- /dev/null +++ b/2021-11/spring-32/classwork2/solution/index.html @@ -0,0 +1 @@ +

Hello World

diff --git a/2021-11/spring-32/classwork2/solution/solution.txt b/2021-11/spring-32/classwork2/solution/solution.txt new file mode 100644 index 00000000..972f490b --- /dev/null +++ b/2021-11/spring-32/classwork2/solution/solution.txt @@ -0,0 +1,11 @@ +docker build -t my-nginx-image:latest . +docker image ls +docker run my-nginx-image:latest +docker ps +docker run -d -p 80:80 my-nginx-image:latest +docker run -d -p 81:80 my-nginx-image:latest +docker ps +docker rm ..... +docker stop .... +docker rm .... +docker rm -f .... diff --git a/2021-11/spring-32/classwork3/Dockerfile b/2021-11/spring-32/classwork3/Dockerfile new file mode 100644 index 00000000..c51e4bde --- /dev/null +++ b/2021-11/spring-32/classwork3/Dockerfile @@ -0,0 +1,4 @@ +FROM nginx:1.11-alpine +COPY index.html /usr/share/nginx/html/index.html +EXPOSE 80 +CMD ["nginx", "-g", "daemon off;"] diff --git a/2021-11/spring-32/classwork3/index.html b/2021-11/spring-32/classwork3/index.html new file mode 100644 index 00000000..f3e333e8 --- /dev/null +++ b/2021-11/spring-32/classwork3/index.html @@ -0,0 +1 @@ +

Hello World

diff --git a/2021-11/spring-32/classwork3/solution/commands.txt b/2021-11/spring-32/classwork3/solution/commands.txt new file mode 100644 index 00000000..83ed0d06 --- /dev/null +++ b/2021-11/spring-32/classwork3/solution/commands.txt @@ -0,0 +1 @@ +docker-compose up diff --git a/2021-11/spring-32/classwork3/solution/docker-compose.yml b/2021-11/spring-32/classwork3/solution/docker-compose.yml new file mode 100644 index 00000000..56b3cae5 --- /dev/null +++ b/2021-11/spring-32/classwork3/solution/docker-compose.yml @@ -0,0 +1,10 @@ +version: '3' +services: + one: + build: .. + ports: + - "80:80" + two: + image: "my-nginx-image" + ports: + - "81:80" diff --git a/2021-11/spring-32/database-example/commands.txt b/2021-11/spring-32/database-example/commands.txt new file mode 100644 index 00000000..45c57d25 --- /dev/null +++ b/2021-11/spring-32/database-example/commands.txt @@ -0,0 +1 @@ +docker run --detach --name=test-mysql --env="MYSQL_ROOT_PASSWORD=mypassword" --publish 6603:3306 mysql diff --git a/2021-11/spring-32/docker-compose-example/.gitignore b/2021-11/spring-32/docker-compose-example/.gitignore new file mode 100644 index 00000000..a2a3040a --- /dev/null +++ b/2021-11/spring-32/docker-compose-example/.gitignore @@ -0,0 +1,31 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/** +!**/src/test/** + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ + +### VS Code ### +.vscode/ diff --git a/2021-11/spring-32/docker-compose-example/.mvn/wrapper/MavenWrapperDownloader.java b/2021-11/spring-32/docker-compose-example/.mvn/wrapper/MavenWrapperDownloader.java new file mode 100644 index 00000000..e76d1f32 --- /dev/null +++ b/2021-11/spring-32/docker-compose-example/.mvn/wrapper/MavenWrapperDownloader.java @@ -0,0 +1,117 @@ +/* + * Copyright 2007-present the original author or 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. + */ +import java.net.*; +import java.io.*; +import java.nio.channels.*; +import java.util.Properties; + +public class MavenWrapperDownloader { + + private static final String WRAPPER_VERSION = "0.5.6"; + /** + * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. + */ + private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/" + + WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar"; + + /** + * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to + * use instead of the default one. + */ + private static final String MAVEN_WRAPPER_PROPERTIES_PATH = + ".mvn/wrapper/maven-wrapper.properties"; + + /** + * Path where the maven-wrapper.jar will be saved to. + */ + private static final String MAVEN_WRAPPER_JAR_PATH = + ".mvn/wrapper/maven-wrapper.jar"; + + /** + * Name of the property which should be used to override the default download url for the wrapper. + */ + private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; + + public static void main(String args[]) { + System.out.println("- Downloader started"); + File baseDirectory = new File(args[0]); + System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); + + // If the maven-wrapper.properties exists, read it and check if it contains a custom + // wrapperUrl parameter. + File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); + String url = DEFAULT_DOWNLOAD_URL; + if(mavenWrapperPropertyFile.exists()) { + FileInputStream mavenWrapperPropertyFileInputStream = null; + try { + mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); + Properties mavenWrapperProperties = new Properties(); + mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); + url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); + } catch (IOException e) { + System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); + } finally { + try { + if(mavenWrapperPropertyFileInputStream != null) { + mavenWrapperPropertyFileInputStream.close(); + } + } catch (IOException e) { + // Ignore ... + } + } + } + System.out.println("- Downloading from: " + url); + + File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); + if(!outputFile.getParentFile().exists()) { + if(!outputFile.getParentFile().mkdirs()) { + System.out.println( + "- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'"); + } + } + System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); + try { + downloadFileFromURL(url, outputFile); + System.out.println("Done"); + System.exit(0); + } catch (Throwable e) { + System.out.println("- Error downloading"); + e.printStackTrace(); + System.exit(1); + } + } + + private static void downloadFileFromURL(String urlString, File destination) throws Exception { + if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) { + String username = System.getenv("MVNW_USERNAME"); + char[] password = System.getenv("MVNW_PASSWORD").toCharArray(); + Authenticator.setDefault(new Authenticator() { + @Override + protected PasswordAuthentication getPasswordAuthentication() { + return new PasswordAuthentication(username, password); + } + }); + } + URL website = new URL(urlString); + ReadableByteChannel rbc; + rbc = Channels.newChannel(website.openStream()); + FileOutputStream fos = new FileOutputStream(destination); + fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); + fos.close(); + rbc.close(); + } + +} diff --git a/2021-11/spring-32/docker-compose-example/.mvn/wrapper/maven-wrapper.jar b/2021-11/spring-32/docker-compose-example/.mvn/wrapper/maven-wrapper.jar new file mode 100644 index 00000000..2cc7d4a5 Binary files /dev/null and b/2021-11/spring-32/docker-compose-example/.mvn/wrapper/maven-wrapper.jar differ diff --git a/2021-11/spring-32/docker-compose-example/.mvn/wrapper/maven-wrapper.properties b/2021-11/spring-32/docker-compose-example/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 00000000..642d572c --- /dev/null +++ b/2021-11/spring-32/docker-compose-example/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,2 @@ +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip +wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar diff --git a/2021-11/spring-32/docker-compose-example/Dockerfile b/2021-11/spring-32/docker-compose-example/Dockerfile new file mode 100644 index 00000000..daaf009e --- /dev/null +++ b/2021-11/spring-32/docker-compose-example/Dockerfile @@ -0,0 +1,4 @@ +FROM openjdk:11-jre-slim +COPY /target/docker-compose-example.jar /app/app.jar +EXPOSE 8080 +ENTRYPOINT ["java", "-jar", "/app/app.jar"] diff --git a/2021-11/spring-32/docker-compose-example/docker-compose.yml b/2021-11/spring-32/docker-compose-example/docker-compose.yml new file mode 100644 index 00000000..2bfc1a00 --- /dev/null +++ b/2021-11/spring-32/docker-compose-example/docker-compose.yml @@ -0,0 +1,30 @@ +version: '3' +services: + app: + build: + context: . + dockerfile: Dockerfile + privileged: true + ports: + - "8080:8080" + # Эти свойства перегружают соответствующие в application.yml + environment: + - SPRING_DATASOURCE_DRIVER_CLASS_NAME=org.postgresql.Driver + - SPRING_DATASOURCE_URL=jdbc:postgresql://postgres:5432/db + - SPRING_DATASOURCE_USERNAME=postgres + - SPRING_DATASOURCE_PASSWORD=postgres + networks: + - nw + postgres: + # В идеале должна быть ещё и версия image + image: "postgres" + ports: + - "5432:5432" + environment: + - POSTGRES_USER=postgres + - POSTGRES_PASSWORD=postgres + - POSTGRES_DB=db + networks: + - nw +networks: + nw: diff --git a/2021-11/spring-32/docker-compose-example/mvnw b/2021-11/spring-32/docker-compose-example/mvnw new file mode 100644 index 00000000..a16b5431 --- /dev/null +++ b/2021-11/spring-32/docker-compose-example/mvnw @@ -0,0 +1,310 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Maven Start Up Batch script +# +# Required ENV vars: +# ------------------ +# JAVA_HOME - location of a JDK home dir +# +# Optional ENV vars +# ----------------- +# M2_HOME - location of maven2's installed home dir +# MAVEN_OPTS - parameters passed to the Java VM when running Maven +# e.g. to debug Maven itself, use +# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +# MAVEN_SKIP_RC - flag to disable loading of mavenrc files +# ---------------------------------------------------------------------------- + +if [ -z "$MAVEN_SKIP_RC" ] ; then + + if [ -f /etc/mavenrc ] ; then + . /etc/mavenrc + fi + + if [ -f "$HOME/.mavenrc" ] ; then + . "$HOME/.mavenrc" + fi + +fi + +# OS specific support. $var _must_ be set to either true or false. +cygwin=false; +darwin=false; +mingw=false +case "`uname`" in + CYGWIN*) cygwin=true ;; + MINGW*) mingw=true;; + Darwin*) darwin=true + # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home + # See https://developer.apple.com/library/mac/qa/qa1170/_index.html + if [ -z "$JAVA_HOME" ]; then + if [ -x "/usr/libexec/java_home" ]; then + export JAVA_HOME="`/usr/libexec/java_home`" + else + export JAVA_HOME="/Library/Java/Home" + fi + fi + ;; +esac + +if [ -z "$JAVA_HOME" ] ; then + if [ -r /etc/gentoo-release ] ; then + JAVA_HOME=`java-config --jre-home` + fi +fi + +if [ -z "$M2_HOME" ] ; then + ## resolve links - $0 may be a link to maven's home + PRG="$0" + + # need this for relative symlinks + while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG="`dirname "$PRG"`/$link" + fi + done + + saveddir=`pwd` + + M2_HOME=`dirname "$PRG"`/.. + + # make it fully qualified + M2_HOME=`cd "$M2_HOME" && pwd` + + cd "$saveddir" + # echo Using m2 at $M2_HOME +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin ; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --unix "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --unix "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --unix "$CLASSPATH"` +fi + +# For Mingw, ensure paths are in UNIX format before anything is touched +if $mingw ; then + [ -n "$M2_HOME" ] && + M2_HOME="`(cd "$M2_HOME"; pwd)`" + [ -n "$JAVA_HOME" ] && + JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" +fi + +if [ -z "$JAVA_HOME" ]; then + javaExecutable="`which javac`" + if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then + # readlink(1) is not available as standard on Solaris 10. + readLink=`which readlink` + if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then + if $darwin ; then + javaHome="`dirname \"$javaExecutable\"`" + javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" + else + javaExecutable="`readlink -f \"$javaExecutable\"`" + fi + javaHome="`dirname \"$javaExecutable\"`" + javaHome=`expr "$javaHome" : '\(.*\)/bin'` + JAVA_HOME="$javaHome" + export JAVA_HOME + fi + fi +fi + +if [ -z "$JAVACMD" ] ; then + 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 + else + JAVACMD="`which java`" + fi +fi + +if [ ! -x "$JAVACMD" ] ; then + echo "Error: JAVA_HOME is not defined correctly." >&2 + echo " We cannot execute $JAVACMD" >&2 + exit 1 +fi + +if [ -z "$JAVA_HOME" ] ; then + echo "Warning: JAVA_HOME environment variable is not set." +fi + +CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher + +# traverses directory structure from process work directory to filesystem root +# first directory with .mvn subdirectory is considered project base directory +find_maven_basedir() { + + if [ -z "$1" ] + then + echo "Path not specified to find_maven_basedir" + return 1 + fi + + basedir="$1" + wdir="$1" + while [ "$wdir" != '/' ] ; do + if [ -d "$wdir"/.mvn ] ; then + basedir=$wdir + break + fi + # workaround for JBEAP-8937 (on Solaris 10/Sparc) + if [ -d "${wdir}" ]; then + wdir=`cd "$wdir/.."; pwd` + fi + # end of workaround + done + echo "${basedir}" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + echo "$(tr -s '\n' ' ' < "$1")" + fi +} + +BASE_DIR=`find_maven_basedir "$(pwd)"` +if [ -z "$BASE_DIR" ]; then + exit 1; +fi + +########################################################################################## +# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +# This allows using the maven wrapper in projects that prohibit checking in binary data. +########################################################################################## +if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found .mvn/wrapper/maven-wrapper.jar" + fi +else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." + fi + if [ -n "$MVNW_REPOURL" ]; then + jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + else + jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + fi + while IFS="=" read key value; do + case "$key" in (wrapperUrl) jarUrl="$value"; break ;; + esac + done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" + if [ "$MVNW_VERBOSE" = true ]; then + echo "Downloading from: $jarUrl" + fi + wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" + if $cygwin; then + wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` + fi + + if command -v wget > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found wget ... using wget" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + wget "$jarUrl" -O "$wrapperJarPath" + else + wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" + fi + elif command -v curl > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found curl ... using curl" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + curl -o "$wrapperJarPath" "$jarUrl" -f + else + curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f + fi + + else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Falling back to using Java to download" + fi + javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" + # For Cygwin, switch paths to Windows format before running javac + if $cygwin; then + javaClass=`cygpath --path --windows "$javaClass"` + fi + if [ -e "$javaClass" ]; then + if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Compiling MavenWrapperDownloader.java ..." + fi + # Compiling the Java class + ("$JAVA_HOME/bin/javac" "$javaClass") + fi + if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + # Running the downloader + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Running MavenWrapperDownloader.java ..." + fi + ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") + fi + fi + fi +fi +########################################################################################## +# End of extension +########################################################################################## + +export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} +if [ "$MVNW_VERBOSE" = true ]; then + echo $MAVEN_PROJECTBASEDIR +fi +MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" + +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --path --windows "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --windows "$CLASSPATH"` + [ -n "$MAVEN_PROJECTBASEDIR" ] && + MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` +fi + +# Provide a "standardized" way to retrieve the CLI args that will +# work with both Windows and non-Windows executions. +MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" +export MAVEN_CMD_LINE_ARGS + +WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +exec "$JAVACMD" \ + $MAVEN_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/2021-11/spring-32/docker-compose-example/mvnw.cmd b/2021-11/spring-32/docker-compose-example/mvnw.cmd new file mode 100644 index 00000000..c8d43372 --- /dev/null +++ b/2021-11/spring-32/docker-compose-example/mvnw.cmd @@ -0,0 +1,182 @@ +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. 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, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Maven Start Up Batch script +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM M2_HOME - location of maven2's installed home dir +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM set title of command window +title %0 +@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" +if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +@REM ==== END VALIDATION ==== + +:init + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" +set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + +FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( + IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B +) + +@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +@REM This allows using the maven wrapper in projects that prohibit checking in binary data. +if exist %WRAPPER_JAR% ( + if "%MVNW_VERBOSE%" == "true" ( + echo Found %WRAPPER_JAR% + ) +) else ( + if not "%MVNW_REPOURL%" == "" ( + SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + ) + if "%MVNW_VERBOSE%" == "true" ( + echo Couldn't find %WRAPPER_JAR%, downloading it ... + echo Downloading from: %DOWNLOAD_URL% + ) + + powershell -Command "&{"^ + "$webclient = new-object System.Net.WebClient;"^ + "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ + "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ + "}"^ + "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ + "}" + if "%MVNW_VERBOSE%" == "true" ( + echo Finished downloading %WRAPPER_JAR% + ) +) +@REM End of extension + +@REM Provide a "standardized" way to retrieve the CLI args that will +@REM work with both Windows and non-Windows executions. +set MAVEN_CMD_LINE_ARGS=%* + +%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" +if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" +:skipRcPost + +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%" == "on" pause + +if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% + +exit /B %ERROR_CODE% diff --git a/2021-11/spring-32/docker-compose-example/pom.xml b/2021-11/spring-32/docker-compose-example/pom.xml new file mode 100644 index 00000000..ff5f9c56 --- /dev/null +++ b/2021-11/spring-32/docker-compose-example/pom.xml @@ -0,0 +1,69 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.5.1 + + + ru.otus.spring + docker-compose-example + 0.0.1-SNAPSHOT + docker-compose-example + Demo project for Spring Boot + + + 11 + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + org.postgresql + postgresql + runtime + + + org.projectlombok + lombok + true + + + test + com.h2database + h2 + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + docker-compose-example + + diff --git a/2021-11/spring-32/docker-compose-example/src/main/java/ru/otus/spring/docker/DockerComposeExampleApplication.java b/2021-11/spring-32/docker-compose-example/src/main/java/ru/otus/spring/docker/DockerComposeExampleApplication.java new file mode 100644 index 00000000..76f60e7d --- /dev/null +++ b/2021-11/spring-32/docker-compose-example/src/main/java/ru/otus/spring/docker/DockerComposeExampleApplication.java @@ -0,0 +1,22 @@ +package ru.otus.spring.docker; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.ApplicationContext; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +import ru.otus.spring.docker.model.Person; +import ru.otus.spring.docker.repository.PersonRepository; + +@SpringBootApplication +@EnableJpaRepositories +public class DockerComposeExampleApplication { + + public static void main(String[] args) { + //Код для примера, делать так конечно нельзя :) + ApplicationContext context = SpringApplication.run(DockerComposeExampleApplication.class, args); + PersonRepository repository = context.getBean(PersonRepository.class); + repository.save(new Person("Ivan", "Ivanov")); + System.out.println(repository.findAll()); + } + +} diff --git a/2021-11/spring-32/docker-compose-example/src/main/java/ru/otus/spring/docker/model/Person.java b/2021-11/spring-32/docker-compose-example/src/main/java/ru/otus/spring/docker/model/Person.java new file mode 100644 index 00000000..9c55909b --- /dev/null +++ b/2021-11/spring-32/docker-compose-example/src/main/java/ru/otus/spring/docker/model/Person.java @@ -0,0 +1,28 @@ +package ru.otus.spring.docker.model; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Data +@Entity +@AllArgsConstructor +@NoArgsConstructor +public class Person { + + @GeneratedValue(strategy = GenerationType.AUTO) + @Id + private Integer id; + private String name; + private String lastName; + + public Person(String name, String lastName) { + this.name = name; + this.lastName = lastName; + } +} diff --git a/2021-11/spring-32/docker-compose-example/src/main/java/ru/otus/spring/docker/repository/PersonRepository.java b/2021-11/spring-32/docker-compose-example/src/main/java/ru/otus/spring/docker/repository/PersonRepository.java new file mode 100644 index 00000000..11262d78 --- /dev/null +++ b/2021-11/spring-32/docker-compose-example/src/main/java/ru/otus/spring/docker/repository/PersonRepository.java @@ -0,0 +1,7 @@ +package ru.otus.spring.docker.repository; + +import org.springframework.data.jpa.repository.JpaRepository; +import ru.otus.spring.docker.model.Person; + +public interface PersonRepository extends JpaRepository { +} diff --git a/2021-11/spring-32/docker-compose-example/src/main/java/ru/otus/spring/docker/rest/PersonController.java b/2021-11/spring-32/docker-compose-example/src/main/java/ru/otus/spring/docker/rest/PersonController.java new file mode 100644 index 00000000..4cfc6436 --- /dev/null +++ b/2021-11/spring-32/docker-compose-example/src/main/java/ru/otus/spring/docker/rest/PersonController.java @@ -0,0 +1,21 @@ +package ru.otus.spring.docker.rest; + +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; +import ru.otus.spring.docker.model.Person; +import ru.otus.spring.docker.repository.PersonRepository; + +import java.util.List; + +@RestController +@RequiredArgsConstructor +public class PersonController { + + private final PersonRepository repository; + + @GetMapping("/api/persons") + public List getAllPersons() { + return this.repository.findAll(); + } +} diff --git a/2021-11/spring-32/docker-compose-example/src/main/resources/application.yml b/2021-11/spring-32/docker-compose-example/src/main/resources/application.yml new file mode 100644 index 00000000..adb9be61 --- /dev/null +++ b/2021-11/spring-32/docker-compose-example/src/main/resources/application.yml @@ -0,0 +1,9 @@ +spring: + datasource: + # Эти свойства будут перегружены свойствами в docker-compose.yml + driver-class-name: org.postgresql.Driver + url: jdbc:postgresql://localhost:5432/db + username: postgres + password: postgres + jpa: + generate-ddl: true diff --git a/2021-11/spring-32/docker-compose-example/src/main/resources/static/index.html b/2021-11/spring-32/docker-compose-example/src/main/resources/static/index.html new file mode 100644 index 00000000..a80ea187 --- /dev/null +++ b/2021-11/spring-32/docker-compose-example/src/main/resources/static/index.html @@ -0,0 +1,12 @@ + + + + + Главная страницв + + +

Главная страница

+

Список всех лиц доступен по ссылке.

+

Перезапустив приложение можно добавить ещё в БД.

+ + diff --git a/2021-11/spring-32/docker-compose-example/src/test/java/ru/otus/spring/docker/DockerComposeExampleApplicationTests.java b/2021-11/spring-32/docker-compose-example/src/test/java/ru/otus/spring/docker/DockerComposeExampleApplicationTests.java new file mode 100644 index 00000000..93fe13c4 --- /dev/null +++ b/2021-11/spring-32/docker-compose-example/src/test/java/ru/otus/spring/docker/DockerComposeExampleApplicationTests.java @@ -0,0 +1,15 @@ +package ru.otus.spring.docker; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +@AutoConfigureTestDatabase +class DockerComposeExampleApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/2021-11/spring-32/stacks-example/commands.txt b/2021-11/spring-32/stacks-example/commands.txt new file mode 100644 index 00000000..7fea8c32 --- /dev/null +++ b/2021-11/spring-32/stacks-example/commands.txt @@ -0,0 +1,4 @@ +docker stack deploy -c docker-compose.yml 123 +docker stack ls +docker stack ps ..... +docker stack services .... diff --git a/2021-11/spring-32/stacks-example/docker-compose.yml b/2021-11/spring-32/stacks-example/docker-compose.yml new file mode 100644 index 00000000..e80f8c28 --- /dev/null +++ b/2021-11/spring-32/stacks-example/docker-compose.yml @@ -0,0 +1,93 @@ +version: "3" +services: + + redis: + image: redis:alpine + networks: + - frontend + deploy: + replicas: 1 + update_config: + parallelism: 2 + delay: 10s + restart_policy: + condition: on-failure + db: + image: postgres:9.4 + environment: + POSTGRES_USER: "postgres" + POSTGRES_PASSWORD: "postgres" + volumes: + - db-data:/var/lib/postgresql/data + networks: + - backend + deploy: + placement: + constraints: [node.role == manager] + vote: + image: dockersamples/examplevotingapp_vote:before + ports: + - 5000:80 + networks: + - frontend + depends_on: + - redis + deploy: + replicas: 2 + update_config: + parallelism: 2 + restart_policy: + condition: on-failure + result: + image: dockersamples/examplevotingapp_result:before + ports: + - 5001:80 + networks: + - backend + depends_on: + - db + deploy: + replicas: 1 + update_config: + parallelism: 2 + delay: 10s + restart_policy: + condition: on-failure + + worker: + image: dockersamples/examplevotingapp_worker + networks: + - frontend + - backend + depends_on: + - db + - redis + deploy: + mode: replicated + replicas: 1 + labels: [APP=VOTING] + restart_policy: + condition: on-failure + delay: 10s + max_attempts: 3 + window: 120s + placement: + constraints: [node.role == manager] + + visualizer: + image: dockersamples/visualizer:stable + ports: + - "8080:8080" + stop_grace_period: 1m30s + volumes: + - "/var/run/docker.sock:/var/run/docker.sock" + deploy: + placement: + constraints: [node.role == manager] + +networks: + frontend: + backend: + +volumes: + db-data: diff --git a/2021-11/spring-38/manual-hateoas/pom.xml b/2021-11/spring-38/manual-hateoas/pom.xml new file mode 100644 index 00000000..5b24b7df --- /dev/null +++ b/2021-11/spring-38/manual-hateoas/pom.xml @@ -0,0 +1,45 @@ + + + 4.0.0 + + ru.otus + manual-hateoas + 1.0 + + + org.springframework.boot + spring-boot-starter-parent + 2.6.6 + + + + + 11 + 11 + + + + + org.springframework.boot + spring-boot-starter-web + + + + com.h2database + h2 + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + org.springframework.boot + spring-boot-starter-hateoas + + + + + diff --git a/2021-11/spring-38/manual-hateoas/src/main/java/ru/otus/spring/microservice/App.java b/2021-11/spring-38/manual-hateoas/src/main/java/ru/otus/spring/microservice/App.java new file mode 100644 index 00000000..045da3f5 --- /dev/null +++ b/2021-11/spring-38/manual-hateoas/src/main/java/ru/otus/spring/microservice/App.java @@ -0,0 +1,27 @@ +package ru.otus.spring.microservice; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import ru.otus.spring.microservice.domain.Person; +import ru.otus.spring.microservice.repostory.PersonRepository; + +import javax.annotation.PostConstruct; + +@SpringBootApplication +public class App { + + @Autowired + private PersonRepository repository; + + public static void main(String[] args) { + SpringApplication.run(App.class); + } + + @PostConstruct + public void init() { + for(int i = 0 ; i < 18; ++i) { + repository.save(new Person("Пёрсона №" + i)); + } + } +} diff --git a/2021-11/spring-38/manual-hateoas/src/main/java/ru/otus/spring/microservice/domain/Person.java b/2021-11/spring-38/manual-hateoas/src/main/java/ru/otus/spring/microservice/domain/Person.java new file mode 100644 index 00000000..e3d66986 --- /dev/null +++ b/2021-11/spring-38/manual-hateoas/src/main/java/ru/otus/spring/microservice/domain/Person.java @@ -0,0 +1,37 @@ +package ru.otus.spring.microservice.domain; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; + +@Entity +public class Person { + + @Id + @GeneratedValue + private int id; + private String name; + + public Person() { + } + + public Person(String name) { + this.name = name; + } + + 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; + } +} diff --git a/2021-11/spring-38/manual-hateoas/src/main/java/ru/otus/spring/microservice/repostory/PersonRepository.java b/2021-11/spring-38/manual-hateoas/src/main/java/ru/otus/spring/microservice/repostory/PersonRepository.java new file mode 100644 index 00000000..5dc34cd8 --- /dev/null +++ b/2021-11/spring-38/manual-hateoas/src/main/java/ru/otus/spring/microservice/repostory/PersonRepository.java @@ -0,0 +1,7 @@ +package ru.otus.spring.microservice.repostory; + +import org.springframework.data.jpa.repository.JpaRepository; +import ru.otus.spring.microservice.domain.Person; + +public interface PersonRepository extends JpaRepository { +} diff --git a/2021-11/spring-38/manual-hateoas/src/main/java/ru/otus/spring/microservice/rest/EntrypointRestController.java b/2021-11/spring-38/manual-hateoas/src/main/java/ru/otus/spring/microservice/rest/EntrypointRestController.java new file mode 100644 index 00000000..c66a9ed2 --- /dev/null +++ b/2021-11/spring-38/manual-hateoas/src/main/java/ru/otus/spring/microservice/rest/EntrypointRestController.java @@ -0,0 +1,19 @@ +package ru.otus.spring.microservice.rest; + + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo; +import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.methodOn; + +@RestController +public class EntrypointRestController { + @GetMapping("api/entrypoint") + public ResponseEntity getApiEntrypoint() { + var link = linkTo(methodOn(PersonsRestController.class).findAllPersons()).withRel("all"); + return new ResponseEntity<>(link, HttpStatus.OK); + } +} diff --git a/2021-11/spring-38/manual-hateoas/src/main/java/ru/otus/spring/microservice/rest/PersonsRestController.java b/2021-11/spring-38/manual-hateoas/src/main/java/ru/otus/spring/microservice/rest/PersonsRestController.java new file mode 100644 index 00000000..64c16b8a --- /dev/null +++ b/2021-11/spring-38/manual-hateoas/src/main/java/ru/otus/spring/microservice/rest/PersonsRestController.java @@ -0,0 +1,67 @@ +package ru.otus.spring.microservice.rest; + + +import org.springframework.hateoas.RepresentationModel; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RestController; +import ru.otus.spring.microservice.domain.Person; +import ru.otus.spring.microservice.repostory.PersonRepository; + +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; + +import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo; +import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.methodOn; + +@RestController +public class PersonsRestController { + + private final PersonRepository repository; + + public PersonsRestController(PersonRepository repository) { + this.repository = repository; + } + + @GetMapping("api/persons") + public ResponseEntity findAllPersons() { + List persons = repository.findAll(); + List resources = persons.stream().map(this::person2Resource) + .collect(Collectors.toList()); + return new ResponseEntity<>(resources, HttpStatus.OK); + } + + @GetMapping("api/persons/{id}") + public ResponseEntity findById(@PathVariable("id") int id) { + Optional person = repository.findById(id); + return new ResponseEntity<>(person2Resource(person.orElseThrow()), HttpStatus.OK); + } + + private PersonResource person2Resource(Person person) { + var resource = new PersonResource(person); + resource.add(linkTo(methodOn(PersonsRestController.class).findById(person.getId())).withSelfRel()); + resource.add(linkTo(methodOn(PersonsRestController.class).findAllPersons()).withRel("all")); + return resource; + } + + private static class PersonResource extends RepresentationModel { + + private final Person person; + + public PersonResource(Person person) { + this.person = person; + } + + public int getId() { + return person.getId(); + } + + public String getName() { + return person.getName(); + } + } + +} diff --git a/2021-11/spring-38/manual-hateoas/src/main/resources/application.yml b/2021-11/spring-38/manual-hateoas/src/main/resources/application.yml new file mode 100644 index 00000000..e69de29b diff --git a/2021-11/spring-38/manual-hateoas/src/main/resources/static/index.html b/2021-11/spring-38/manual-hateoas/src/main/resources/static/index.html new file mode 100644 index 00000000..445b2e5c --- /dev/null +++ b/2021-11/spring-38/manual-hateoas/src/main/resources/static/index.html @@ -0,0 +1,67 @@ + + + + + Пёрсоны + + + +
+ + \ No newline at end of file diff --git a/2021-11/spring-38/plain-api/pom.xml b/2021-11/spring-38/plain-api/pom.xml new file mode 100644 index 00000000..4fbfd9ad --- /dev/null +++ b/2021-11/spring-38/plain-api/pom.xml @@ -0,0 +1,40 @@ + + + 4.0.0 + + ru.otus + plain-api + 1.0 + + + org.springframework.boot + spring-boot-starter-parent + 2.6.6 + + + + + 11 + 11 + + + + + org.springframework.boot + spring-boot-starter-web + + + + com.h2database + h2 + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + + diff --git a/2021-11/spring-38/plain-api/src/main/java/ru/otus/spring/microservice/App.java b/2021-11/spring-38/plain-api/src/main/java/ru/otus/spring/microservice/App.java new file mode 100644 index 00000000..045da3f5 --- /dev/null +++ b/2021-11/spring-38/plain-api/src/main/java/ru/otus/spring/microservice/App.java @@ -0,0 +1,27 @@ +package ru.otus.spring.microservice; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import ru.otus.spring.microservice.domain.Person; +import ru.otus.spring.microservice.repostory.PersonRepository; + +import javax.annotation.PostConstruct; + +@SpringBootApplication +public class App { + + @Autowired + private PersonRepository repository; + + public static void main(String[] args) { + SpringApplication.run(App.class); + } + + @PostConstruct + public void init() { + for(int i = 0 ; i < 18; ++i) { + repository.save(new Person("Пёрсона №" + i)); + } + } +} diff --git a/2021-11/spring-38/plain-api/src/main/java/ru/otus/spring/microservice/domain/Person.java b/2021-11/spring-38/plain-api/src/main/java/ru/otus/spring/microservice/domain/Person.java new file mode 100644 index 00000000..553a8a7d --- /dev/null +++ b/2021-11/spring-38/plain-api/src/main/java/ru/otus/spring/microservice/domain/Person.java @@ -0,0 +1,39 @@ +package ru.otus.spring.microservice.domain; + +import com.fasterxml.jackson.annotation.JsonProperty; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; + +@Entity +public class Person { + + @Id + @GeneratedValue + private int id; + private String name; + + public Person() { + } + + public Person(String name) { + this.name = name; + } + + 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; + } +} diff --git a/2021-11/spring-38/plain-api/src/main/java/ru/otus/spring/microservice/repostory/PersonRepository.java b/2021-11/spring-38/plain-api/src/main/java/ru/otus/spring/microservice/repostory/PersonRepository.java new file mode 100644 index 00000000..5dc34cd8 --- /dev/null +++ b/2021-11/spring-38/plain-api/src/main/java/ru/otus/spring/microservice/repostory/PersonRepository.java @@ -0,0 +1,7 @@ +package ru.otus.spring.microservice.repostory; + +import org.springframework.data.jpa.repository.JpaRepository; +import ru.otus.spring.microservice.domain.Person; + +public interface PersonRepository extends JpaRepository { +} diff --git a/2021-11/spring-38/plain-api/src/main/java/ru/otus/spring/microservice/rest/PersonsRestController.java b/2021-11/spring-38/plain-api/src/main/java/ru/otus/spring/microservice/rest/PersonsRestController.java new file mode 100644 index 00000000..8a7d647e --- /dev/null +++ b/2021-11/spring-38/plain-api/src/main/java/ru/otus/spring/microservice/rest/PersonsRestController.java @@ -0,0 +1,34 @@ +package ru.otus.spring.microservice.rest; + + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RestController; +import ru.otus.spring.microservice.domain.Person; +import ru.otus.spring.microservice.repostory.PersonRepository; + +import java.util.List; + +@RestController +public class PersonsRestController { + + private final PersonRepository repository; + + public PersonsRestController(PersonRepository repository) { + this.repository = repository; + } + + @GetMapping("api/persons") + public ResponseEntity findAllPersons() { + List persons = repository.findAll(); + return new ResponseEntity<>(persons, HttpStatus.OK); + } + + @GetMapping("api/persons/{id}") + public ResponseEntity findById(@PathVariable("id") int id) { + Person person = repository.findById(id).orElseThrow(); + return new ResponseEntity<>(person, HttpStatus.OK); + } +} diff --git a/2021-11/spring-38/plain-api/src/main/resources/application.yml b/2021-11/spring-38/plain-api/src/main/resources/application.yml new file mode 100644 index 00000000..e69de29b diff --git a/2021-11/spring-38/plain-api/src/main/resources/static/index.html b/2021-11/spring-38/plain-api/src/main/resources/static/index.html new file mode 100644 index 00000000..7f48ccbe --- /dev/null +++ b/2021-11/spring-38/plain-api/src/main/resources/static/index.html @@ -0,0 +1,62 @@ + + + + + Пёрсоны + + + +
+ + \ No newline at end of file diff --git a/2021-11/spring-38/pom.xml b/2021-11/spring-38/pom.xml new file mode 100644 index 00000000..a4ee7368 --- /dev/null +++ b/2021-11/spring-38/pom.xml @@ -0,0 +1,18 @@ + + + 4.0.0 + + ru.otus + spring-data-rest-demo + 1.0 + + pom + + + plain-api + manual-hateoas + spring-data-rest + + diff --git a/2021-11/spring-38/spring-data-rest/pom.xml b/2021-11/spring-38/spring-data-rest/pom.xml new file mode 100644 index 00000000..ae57eeb6 --- /dev/null +++ b/2021-11/spring-38/spring-data-rest/pom.xml @@ -0,0 +1,51 @@ + + + 4.0.0 + + ru.otus + spring-data-rest + 1.0 + + + org.springframework.boot + spring-boot-starter-parent + 2.6.6 + + + + + 11 + 11 + + + + + org.springframework.boot + spring-boot-starter-web + + + + com.h2database + h2 + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + org.springframework.boot + spring-boot-starter-data-rest + + + + org.springframework.data + spring-data-rest-hal-explorer + + + + + diff --git a/2021-11/spring-38/spring-data-rest/src/main/java/ru/otus/spring/microservice/App.java b/2021-11/spring-38/spring-data-rest/src/main/java/ru/otus/spring/microservice/App.java new file mode 100644 index 00000000..045da3f5 --- /dev/null +++ b/2021-11/spring-38/spring-data-rest/src/main/java/ru/otus/spring/microservice/App.java @@ -0,0 +1,27 @@ +package ru.otus.spring.microservice; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import ru.otus.spring.microservice.domain.Person; +import ru.otus.spring.microservice.repostory.PersonRepository; + +import javax.annotation.PostConstruct; + +@SpringBootApplication +public class App { + + @Autowired + private PersonRepository repository; + + public static void main(String[] args) { + SpringApplication.run(App.class); + } + + @PostConstruct + public void init() { + for(int i = 0 ; i < 18; ++i) { + repository.save(new Person("Пёрсона №" + i)); + } + } +} diff --git a/2021-11/spring-38/spring-data-rest/src/main/java/ru/otus/spring/microservice/config/RestConfig.java b/2021-11/spring-38/spring-data-rest/src/main/java/ru/otus/spring/microservice/config/RestConfig.java new file mode 100644 index 00000000..ebaf6704 --- /dev/null +++ b/2021-11/spring-38/spring-data-rest/src/main/java/ru/otus/spring/microservice/config/RestConfig.java @@ -0,0 +1,20 @@ +package ru.otus.spring.microservice.config; + +import org.springframework.context.annotation.Configuration; +import org.springframework.data.rest.core.config.RepositoryRestConfiguration; +import org.springframework.data.rest.webmvc.config.RepositoryRestConfigurer; +import org.springframework.web.servlet.config.annotation.CorsRegistry; +import ru.otus.spring.microservice.projections.PersonLowerNameProjection; +import ru.otus.spring.microservice.projections.PersonUpperNameProjection; + +//@Configuration +public class RestConfig implements RepositoryRestConfigurer { + + @Override + public void configureRepositoryRestConfiguration(RepositoryRestConfiguration repositoryRestConfiguration, + CorsRegistry cors) { + repositoryRestConfiguration.getProjectionConfiguration() + .addProjection(PersonUpperNameProjection.class) + .addProjection(PersonLowerNameProjection.class); + } +} diff --git a/2021-11/spring-38/spring-data-rest/src/main/java/ru/otus/spring/microservice/domain/Person.java b/2021-11/spring-38/spring-data-rest/src/main/java/ru/otus/spring/microservice/domain/Person.java new file mode 100644 index 00000000..aa4738a0 --- /dev/null +++ b/2021-11/spring-38/spring-data-rest/src/main/java/ru/otus/spring/microservice/domain/Person.java @@ -0,0 +1,41 @@ +package ru.otus.spring.microservice.domain; + +import ru.otus.spring.microservice.listeners.PersonEntityEventListener; + +import javax.persistence.Entity; +import javax.persistence.EntityListeners; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; + +@Entity +@EntityListeners(PersonEntityEventListener.class) +public class Person { + + @Id + @GeneratedValue + private int id; + private String name; + + public Person() { + } + + public Person(String name) { + this.name = name; + } + + 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; + } +} diff --git a/2021-11/spring-38/spring-data-rest/src/main/java/ru/otus/spring/microservice/listeners/PersonEntityEventListener.java b/2021-11/spring-38/spring-data-rest/src/main/java/ru/otus/spring/microservice/listeners/PersonEntityEventListener.java new file mode 100644 index 00000000..b0a2cf52 --- /dev/null +++ b/2021-11/spring-38/spring-data-rest/src/main/java/ru/otus/spring/microservice/listeners/PersonEntityEventListener.java @@ -0,0 +1,12 @@ +package ru.otus.spring.microservice.listeners; + +import ru.otus.spring.microservice.domain.Person; + +import javax.persistence.PrePersist; + +public class PersonEntityEventListener { + @PrePersist + public void prePersist(Person p) { + p.setName(p.getName() + " (Человек и пароход)"); + } +} diff --git a/2021-11/spring-38/spring-data-rest/src/main/java/ru/otus/spring/microservice/projections/PersonLowerNameProjection.java b/2021-11/spring-38/spring-data-rest/src/main/java/ru/otus/spring/microservice/projections/PersonLowerNameProjection.java new file mode 100644 index 00000000..8f96c384 --- /dev/null +++ b/2021-11/spring-38/spring-data-rest/src/main/java/ru/otus/spring/microservice/projections/PersonLowerNameProjection.java @@ -0,0 +1,14 @@ +package ru.otus.spring.microservice.projections; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.data.rest.core.config.Projection; +import ru.otus.spring.microservice.domain.Person; + +@Projection(name = "withlowername", types = Person.class) +public interface PersonLowerNameProjection { + + String getName(); + + @Value("#{target.name.toLowerCase()}") + String getNameLowerCase(); +} diff --git a/2021-11/spring-38/spring-data-rest/src/main/java/ru/otus/spring/microservice/projections/PersonUpperNameProjection.java b/2021-11/spring-38/spring-data-rest/src/main/java/ru/otus/spring/microservice/projections/PersonUpperNameProjection.java new file mode 100644 index 00000000..96ddffc5 --- /dev/null +++ b/2021-11/spring-38/spring-data-rest/src/main/java/ru/otus/spring/microservice/projections/PersonUpperNameProjection.java @@ -0,0 +1,14 @@ +package ru.otus.spring.microservice.projections; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.data.rest.core.config.Projection; +import ru.otus.spring.microservice.domain.Person; + +@Projection(name = "withuppername", types = Person.class) +public interface PersonUpperNameProjection { + + String getName(); + + @Value("#{target.name.toUpperCase()}") + String getNameUpperCase(); +} diff --git a/2021-11/spring-38/spring-data-rest/src/main/java/ru/otus/spring/microservice/repostory/PersonRepository.java b/2021-11/spring-38/spring-data-rest/src/main/java/ru/otus/spring/microservice/repostory/PersonRepository.java new file mode 100644 index 00000000..b76263b6 --- /dev/null +++ b/2021-11/spring-38/spring-data-rest/src/main/java/ru/otus/spring/microservice/repostory/PersonRepository.java @@ -0,0 +1,11 @@ +package ru.otus.spring.microservice.repostory; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.rest.core.annotation.RepositoryRestResource; +import ru.otus.spring.microservice.domain.Person; + +import java.util.List; + +@RepositoryRestResource(path = "persons", collectionResourceRel = "persons") +public interface PersonRepository extends JpaRepository { +} diff --git a/2021-11/spring-38/spring-data-rest/src/main/resources/application.yml b/2021-11/spring-38/spring-data-rest/src/main/resources/application.yml new file mode 100644 index 00000000..ec9139b0 --- /dev/null +++ b/2021-11/spring-38/spring-data-rest/src/main/resources/application.yml @@ -0,0 +1,4 @@ +spring: + data: + rest: + basePath: /api \ No newline at end of file diff --git a/2021-11/spring-38/spring-data-rest/src/main/resources/static/index.html b/2021-11/spring-38/spring-data-rest/src/main/resources/static/index.html new file mode 100644 index 00000000..86e8a0c2 --- /dev/null +++ b/2021-11/spring-38/spring-data-rest/src/main/resources/static/index.html @@ -0,0 +1,89 @@ + + + + + Пёрсоны + + + +
+
+
+
+ + +
+ + \ No newline at end of file diff --git a/2022-02/spring-11-data-jpa/.gitignore b/2022-02/spring-11-data-jpa/.gitignore new file mode 100644 index 00000000..e62c33c2 --- /dev/null +++ b/2022-02/spring-11-data-jpa/.gitignore @@ -0,0 +1,4 @@ +.idea/ +*.iml + +target/ diff --git a/2022-02/spring-11-data-jpa/demo/.gitignore b/2022-02/spring-11-data-jpa/demo/.gitignore new file mode 100644 index 00000000..e62c33c2 --- /dev/null +++ b/2022-02/spring-11-data-jpa/demo/.gitignore @@ -0,0 +1,4 @@ +.idea/ +*.iml + +target/ diff --git a/2022-02/spring-11-data-jpa/demo/pom.xml b/2022-02/spring-11-data-jpa/demo/pom.xml new file mode 100644 index 00000000..48523ba6 --- /dev/null +++ b/2022-02/spring-11-data-jpa/demo/pom.xml @@ -0,0 +1,55 @@ + + + 4.0.0 + + ru.otus + demo + 1.0-SNAPSHOT + + + org.springframework.boot + spring-boot-starter-parent + 2.4.5 + + + + 11 + 11 + + + + + org.springframework.boot + spring-boot-starter + + + org.springframework.boot + spring-boot-starter-data-jpa + + + com.h2database + h2 + + + org.springframework.boot + spring-boot-starter-test + test + + + org.projectlombok + lombok + true + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + diff --git a/2022-02/spring-11-data-jpa/demo/src/main/java/ru/otus/springdata/Main.java b/2022-02/spring-11-data-jpa/demo/src/main/java/ru/otus/springdata/Main.java new file mode 100644 index 00000000..bd056210 --- /dev/null +++ b/2022-02/spring-11-data-jpa/demo/src/main/java/ru/otus/springdata/Main.java @@ -0,0 +1,75 @@ +package ru.otus.springdata; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.data.domain.Example; +import org.springframework.data.domain.ExampleMatcher; +import org.springframework.data.jpa.domain.Specification; +import ru.otus.springdata.domain.Email; +import ru.otus.springdata.domain.Person; +import ru.otus.springdata.repository.EmailRepository; +import ru.otus.springdata.repository.PersonRepository; + +import java.util.Objects; +import java.util.stream.Collectors; + +import static ru.otus.springdata.repository.PersonSpecification.emailAddressLike; +import static ru.otus.springdata.repository.PersonSpecification.nameLike; + +@SpringBootApplication +public class Main { + + public static void main(String[] args) { + ConfigurableApplicationContext context = SpringApplication.run(Main.class); + + PersonRepository personRepository = context.getBean(PersonRepository.class); + EmailRepository emailRepository = context.getBean(EmailRepository.class); + + var pushkin = new Person("Александр Сергеевич Пушкин", new Email("alex.pushkin@mail.ru")); + var block = new Person("Александр Александрович Блок", new Email("alex.block@mail.ru")); + var lermontov = new Person("Михаил Юрьевич Лермонтов", new Email("michail.lermontov@bk.ru")); + var gorbachev = new Person("Михаил Сергеевич Горбачев", new Email("gorbachev@mail.ru")); + var bulgakov = new Person("Михаил Афанасьевич Булгаков", new Email("bulgakov@mail.ru")); + + emailRepository.save(pushkin.getEmail()); + emailRepository.save(block.getEmail()); + emailRepository.save(lermontov.getEmail()); + emailRepository.save(gorbachev.getEmail()); + emailRepository.save(bulgakov.getEmail()); + + personRepository.save(pushkin); + personRepository.save(block); + personRepository.save(lermontov); + personRepository.save(gorbachev); + personRepository.save(bulgakov); + + System.out.println("\n\nИщем почту Горбачева по его id"); + emailRepository.findByPersonId(gorbachev.getId()) + .ifPresent(System.out::println); + + + System.out.println("\n\nС помощью Example ищем всех пёрсонов с именем \"Михаил\" и почтой на \"mail.ru\""); + ExampleMatcher ignoringExampleMatcher = ExampleMatcher.matchingAll() + .withMatcher("email.address", ExampleMatcher.GenericPropertyMatchers.contains().ignoreCase()) + .withMatcher("name", ExampleMatcher.GenericPropertyMatchers.contains().ignoreCase()) + .withIgnorePaths("id", "email.id"); + + Example example = Example.of(new Person("Михаил", new Email(0, "mail.ru")), ignoringExampleMatcher); + + System.out.println(personRepository.findAll(example).stream().map(Objects::toString) + .collect(Collectors.joining("\n"))); + + + System.out.println("\n\nС помощью Specification ищем всех пёрсонов с именем \"Александр\" или с почтой на \"bk.ru\""); + + Specification specification = Specification.where(nameLike("Александр")) + .or(emailAddressLike("bk.ru")); + + System.out.println(personRepository.findAll(specification).stream().map(Objects::toString) + .collect(Collectors.joining("\n"))); + + System.out.println("\n\n"); + + } +} diff --git a/2022-02/spring-11-data-jpa/demo/src/main/java/ru/otus/springdata/domain/Email.java b/2022-02/spring-11-data-jpa/demo/src/main/java/ru/otus/springdata/domain/Email.java new file mode 100644 index 00000000..e3b8d344 --- /dev/null +++ b/2022-02/spring-11-data-jpa/demo/src/main/java/ru/otus/springdata/domain/Email.java @@ -0,0 +1,27 @@ +package ru.otus.springdata.domain; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Data +@NoArgsConstructor +@AllArgsConstructor +@Entity +public class Email { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private long id; + + private String address; + + public Email(String address) { + this.address = address; + } +} diff --git a/2022-02/spring-11-data-jpa/demo/src/main/java/ru/otus/springdata/domain/Person.java b/2022-02/spring-11-data-jpa/demo/src/main/java/ru/otus/springdata/domain/Person.java new file mode 100644 index 00000000..e24e42aa --- /dev/null +++ b/2022-02/spring-11-data-jpa/demo/src/main/java/ru/otus/springdata/domain/Person.java @@ -0,0 +1,30 @@ +package ru.otus.springdata.domain; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.persistence.*; + +@Data +@NoArgsConstructor +@AllArgsConstructor +@Entity +public class Person { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private long id; + + private String name; + + @OneToOne(orphanRemoval = true) + @JoinColumn(name = "email_id") + private Email email; + + public Person(String name, Email email) { + this.name = name; + this.email = email; + } + +} diff --git a/2022-02/spring-11-data-jpa/demo/src/main/java/ru/otus/springdata/repository/EmailRepository.java b/2022-02/spring-11-data-jpa/demo/src/main/java/ru/otus/springdata/repository/EmailRepository.java new file mode 100644 index 00000000..a76a43ff --- /dev/null +++ b/2022-02/spring-11-data-jpa/demo/src/main/java/ru/otus/springdata/repository/EmailRepository.java @@ -0,0 +1,21 @@ +package ru.otus.springdata.repository; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; +import org.springframework.transaction.annotation.Transactional; +import ru.otus.springdata.domain.Email; + +import java.util.Optional; + +public interface EmailRepository extends JpaRepository, EmailRepositoryCustom { + + @Query("select e from Email e where e.address = :address") + Optional findByEmailAddress(@Param("address") String email); + + @Modifying + @Transactional + @Query("update Email e set e.address = :address where e.id = :id") + void updateEmailById(@Param("id") long id, @Param("address") String address); +} diff --git a/2022-02/spring-11-data-jpa/demo/src/main/java/ru/otus/springdata/repository/EmailRepositoryCustom.java b/2022-02/spring-11-data-jpa/demo/src/main/java/ru/otus/springdata/repository/EmailRepositoryCustom.java new file mode 100644 index 00000000..db7112e1 --- /dev/null +++ b/2022-02/spring-11-data-jpa/demo/src/main/java/ru/otus/springdata/repository/EmailRepositoryCustom.java @@ -0,0 +1,9 @@ +package ru.otus.springdata.repository; + +import ru.otus.springdata.domain.Email; + +import java.util.Optional; + +public interface EmailRepositoryCustom { + Optional findByPersonId(long personId); +} diff --git a/2022-02/spring-11-data-jpa/demo/src/main/java/ru/otus/springdata/repository/EmailRepositoryCustomImpl.java b/2022-02/spring-11-data-jpa/demo/src/main/java/ru/otus/springdata/repository/EmailRepositoryCustomImpl.java new file mode 100644 index 00000000..18f9ac33 --- /dev/null +++ b/2022-02/spring-11-data-jpa/demo/src/main/java/ru/otus/springdata/repository/EmailRepositoryCustomImpl.java @@ -0,0 +1,20 @@ +package ru.otus.springdata.repository; + +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Repository; +import ru.otus.springdata.domain.Email; +import ru.otus.springdata.domain.Person; + +import java.util.Optional; + +@Repository +@RequiredArgsConstructor +public class EmailRepositoryCustomImpl implements EmailRepositoryCustom { + + private final PersonRepository personRepository; + + @Override + public Optional findByPersonId(long personId) { + return personRepository.findById(personId).map(Person::getEmail); + } +} diff --git a/2022-02/spring-11-data-jpa/demo/src/main/java/ru/otus/springdata/repository/PersonRepository.java b/2022-02/spring-11-data-jpa/demo/src/main/java/ru/otus/springdata/repository/PersonRepository.java new file mode 100644 index 00000000..7bb5c825 --- /dev/null +++ b/2022-02/spring-11-data-jpa/demo/src/main/java/ru/otus/springdata/repository/PersonRepository.java @@ -0,0 +1,20 @@ +package ru.otus.springdata.repository; + +import org.springframework.data.jpa.repository.EntityGraph; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.JpaSpecificationExecutor; +import org.springframework.data.repository.CrudRepository; +import ru.otus.springdata.domain.Person; + +import java.util.List; +import java.util.Optional; + +public interface PersonRepository extends JpaRepository, JpaSpecificationExecutor { + + @EntityGraph(attributePaths = "email") + List findAll(); + + Optional findByName(String s); + + Optional findByEmailAddress(String email); +} diff --git a/2022-02/spring-11-data-jpa/demo/src/main/java/ru/otus/springdata/repository/PersonSpecification.java b/2022-02/spring-11-data-jpa/demo/src/main/java/ru/otus/springdata/repository/PersonSpecification.java new file mode 100644 index 00000000..3f8c67b3 --- /dev/null +++ b/2022-02/spring-11-data-jpa/demo/src/main/java/ru/otus/springdata/repository/PersonSpecification.java @@ -0,0 +1,21 @@ +package ru.otus.springdata.repository; + +import org.springframework.data.jpa.domain.Specification; +import ru.otus.springdata.domain.Person; + +public class PersonSpecification { + + public static Specification nameLike(String name) { + if (name == null) { + return null; + } + return (root, query, cb) -> cb.like(root.get("name"), "%" + name + "%"); + } + + public static Specification emailAddressLike(String address) { + if (address == null) { + return null; + } + return (root, query, cb) -> cb.like(root.join("email").get("address"), "%" + address + "%"); + } +} diff --git a/2022-02/spring-11-data-jpa/demo/src/main/resources/application.yml b/2022-02/spring-11-data-jpa/demo/src/main/resources/application.yml new file mode 100644 index 00000000..bd5b0f98 --- /dev/null +++ b/2022-02/spring-11-data-jpa/demo/src/main/resources/application.yml @@ -0,0 +1,20 @@ +spring: + datasource: + url: jdbc:h2:mem:testdb + initialization-mode: never + + jpa: + generate-ddl: true + hibernate: + ddl-auto: create + + properties: + hibernate: + format_sql: false + + show-sql: true + + +logging: + level: + ROOT: ERROR \ No newline at end of file diff --git a/2022-02/spring-11-data-jpa/exercise/.gitignore b/2022-02/spring-11-data-jpa/exercise/.gitignore new file mode 100644 index 00000000..e62c33c2 --- /dev/null +++ b/2022-02/spring-11-data-jpa/exercise/.gitignore @@ -0,0 +1,4 @@ +.idea/ +*.iml + +target/ diff --git a/2022-02/spring-11-data-jpa/exercise/pom.xml b/2022-02/spring-11-data-jpa/exercise/pom.xml new file mode 100644 index 00000000..172b613d --- /dev/null +++ b/2022-02/spring-11-data-jpa/exercise/pom.xml @@ -0,0 +1,50 @@ + + + 4.0.0 + + ru.otus + exercise + 1.0-SNAPSHOT + + + org.springframework.boot + spring-boot-starter-parent + 2.4.5 + + + + 11 + 11 + + + + + org.springframework.boot + spring-boot-starter + + + org.springframework.boot + spring-boot-starter-data-jpa + + + com.h2database + h2 + + + org.projectlombok + lombok + true + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + diff --git a/2022-02/spring-11-data-jpa/exercise/src/main/java/ru/otus/springdata/Main.java b/2022-02/spring-11-data-jpa/exercise/src/main/java/ru/otus/springdata/Main.java new file mode 100644 index 00000000..dbbe3598 --- /dev/null +++ b/2022-02/spring-11-data-jpa/exercise/src/main/java/ru/otus/springdata/Main.java @@ -0,0 +1,23 @@ +package ru.otus.springdata; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.ConfigurableApplicationContext; + + + +@SpringBootApplication +public class Main { + + public static void main(String[] args) { + ConfigurableApplicationContext context = SpringApplication.run(Main.class); + //PersonRepository personRepository = context.getBean(PersonRepository.class); + //EmailRepository emailRepository = context.getBean(EmailRepository.class); + + // personRepository.save(new Person("Александр Сергеевич Пушкин")); + // personRepository.save(new Person("Михаил Юрьевич Лермонтов")); + // personRepository.save(new Person("Михаил Сергеевич Горбачев")); + } + + +} diff --git a/2022-02/spring-11-data-jpa/exercise/src/main/java/ru/otus/springdata/domain/Email.java b/2022-02/spring-11-data-jpa/exercise/src/main/java/ru/otus/springdata/domain/Email.java new file mode 100644 index 00000000..5cb61fa0 --- /dev/null +++ b/2022-02/spring-11-data-jpa/exercise/src/main/java/ru/otus/springdata/domain/Email.java @@ -0,0 +1,21 @@ +package ru.otus.springdata.domain; + + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@NoArgsConstructor +@AllArgsConstructor +public class Email { + + private long id; + + private String address; + + public Email(String address) { + this.address = address; + } + +} diff --git a/2022-02/spring-11-data-jpa/exercise/src/main/java/ru/otus/springdata/domain/Person.java b/2022-02/spring-11-data-jpa/exercise/src/main/java/ru/otus/springdata/domain/Person.java new file mode 100644 index 00000000..cc8e6d0a --- /dev/null +++ b/2022-02/spring-11-data-jpa/exercise/src/main/java/ru/otus/springdata/domain/Person.java @@ -0,0 +1,26 @@ +package ru.otus.springdata.domain; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Data +@NoArgsConstructor +@AllArgsConstructor +@Entity +public class Person { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private long id; + + private String name; + + public Person(String name) { + this.name = name; + } +} diff --git a/2022-02/spring-11-data-jpa/exercise/src/main/java/ru/otus/springdata/repository/EmailRepository.java b/2022-02/spring-11-data-jpa/exercise/src/main/java/ru/otus/springdata/repository/EmailRepository.java new file mode 100644 index 00000000..7a446b95 --- /dev/null +++ b/2022-02/spring-11-data-jpa/exercise/src/main/java/ru/otus/springdata/repository/EmailRepository.java @@ -0,0 +1,4 @@ +package ru.otus.springdata.repository; + +public interface EmailRepository { +} diff --git a/2022-02/spring-11-data-jpa/exercise/src/main/java/ru/otus/springdata/repository/PersonRepository.java b/2022-02/spring-11-data-jpa/exercise/src/main/java/ru/otus/springdata/repository/PersonRepository.java new file mode 100644 index 00000000..f8e5fc8a --- /dev/null +++ b/2022-02/spring-11-data-jpa/exercise/src/main/java/ru/otus/springdata/repository/PersonRepository.java @@ -0,0 +1,4 @@ +package ru.otus.springdata.repository; + +public interface PersonRepository { +} diff --git a/2022-02/spring-11-data-jpa/exercise/src/main/resources/application.yml b/2022-02/spring-11-data-jpa/exercise/src/main/resources/application.yml new file mode 100644 index 00000000..bd5b0f98 --- /dev/null +++ b/2022-02/spring-11-data-jpa/exercise/src/main/resources/application.yml @@ -0,0 +1,20 @@ +spring: + datasource: + url: jdbc:h2:mem:testdb + initialization-mode: never + + jpa: + generate-ddl: true + hibernate: + ddl-auto: create + + properties: + hibernate: + format_sql: false + + show-sql: true + + +logging: + level: + ROOT: ERROR \ No newline at end of file diff --git a/2022-02/spring-11-data-jpa/pom.xml b/2022-02/spring-11-data-jpa/pom.xml new file mode 100644 index 00000000..922fc48a --- /dev/null +++ b/2022-02/spring-11-data-jpa/pom.xml @@ -0,0 +1,21 @@ + + + 4.0.0 + + ru.otus + spring-11-data-jpa + 1.0 + + pom + + + exercise + solution-01 + solution-02 + solution-03 + solution-04 + demo + + diff --git a/2022-02/spring-11-data-jpa/solution-01/.gitignore b/2022-02/spring-11-data-jpa/solution-01/.gitignore new file mode 100644 index 00000000..e62c33c2 --- /dev/null +++ b/2022-02/spring-11-data-jpa/solution-01/.gitignore @@ -0,0 +1,4 @@ +.idea/ +*.iml + +target/ diff --git a/2022-02/spring-11-data-jpa/solution-01/pom.xml b/2022-02/spring-11-data-jpa/solution-01/pom.xml new file mode 100644 index 00000000..355f4335 --- /dev/null +++ b/2022-02/spring-11-data-jpa/solution-01/pom.xml @@ -0,0 +1,55 @@ + + + 4.0.0 + + ru.otus + solution-01 + 1.0-SNAPSHOT + + + org.springframework.boot + spring-boot-starter-parent + 2.4.5 + + + + 11 + 11 + + + + + org.springframework.boot + spring-boot-starter + + + org.springframework.boot + spring-boot-starter-data-jpa + + + com.h2database + h2 + + + org.springframework.boot + spring-boot-starter-test + test + + + org.projectlombok + lombok + true + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + diff --git a/2022-02/spring-11-data-jpa/solution-01/src/main/java/ru/otus/springdata/Main.java b/2022-02/spring-11-data-jpa/solution-01/src/main/java/ru/otus/springdata/Main.java new file mode 100644 index 00000000..4961485f --- /dev/null +++ b/2022-02/spring-11-data-jpa/solution-01/src/main/java/ru/otus/springdata/Main.java @@ -0,0 +1,37 @@ +package ru.otus.springdata; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.ConfigurableApplicationContext; +import ru.otus.springdata.domain.Person; +import ru.otus.springdata.repository.PersonRepository; + +import java.util.Objects; +import java.util.stream.Collectors; + +@SpringBootApplication +public class Main { + + public static void main(String[] args) { + ConfigurableApplicationContext context = SpringApplication.run(Main.class); + + PersonRepository personRepository = context.getBean(PersonRepository.class); + + + personRepository.save(new Person("Александр Сергеевич Пушкин")); + personRepository.save(new Person("Михаил Юрьевич Лермонтов")); + personRepository.save(new Person("Михаил Сергеевич Горбачев")); + + System.out.println("\n\nИщем всех пёрсонов"); + System.out.println(personRepository.findAll().stream().map(Objects::toString) + .collect(Collectors.joining("\n"))); + + System.out.println("\n\nИщем Пушкина"); + personRepository.findByName("Александр Сергеевич Пушкин") + .ifPresent(System.out::println); + + + System.out.println("\n\n"); + + } +} diff --git a/2022-02/spring-11-data-jpa/solution-01/src/main/java/ru/otus/springdata/domain/Email.java b/2022-02/spring-11-data-jpa/solution-01/src/main/java/ru/otus/springdata/domain/Email.java new file mode 100644 index 00000000..3f0bd00c --- /dev/null +++ b/2022-02/spring-11-data-jpa/solution-01/src/main/java/ru/otus/springdata/domain/Email.java @@ -0,0 +1,24 @@ +package ru.otus.springdata.domain; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Data +@NoArgsConstructor +@AllArgsConstructor +public class Email { + + private long id; + + private String address; + + public Email(String address) { + this.address = address; + } +} diff --git a/2022-02/spring-11-data-jpa/solution-01/src/main/java/ru/otus/springdata/domain/Person.java b/2022-02/spring-11-data-jpa/solution-01/src/main/java/ru/otus/springdata/domain/Person.java new file mode 100644 index 00000000..96d92b91 --- /dev/null +++ b/2022-02/spring-11-data-jpa/solution-01/src/main/java/ru/otus/springdata/domain/Person.java @@ -0,0 +1,25 @@ +package ru.otus.springdata.domain; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.persistence.*; + +@Data +@NoArgsConstructor +@AllArgsConstructor +@Entity +public class Person { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private long id; + + private String name; + + public Person(String name) { + this.name = name; + } + +} diff --git a/2022-02/spring-11-data-jpa/solution-01/src/main/java/ru/otus/springdata/repository/EmailRepository.java b/2022-02/spring-11-data-jpa/solution-01/src/main/java/ru/otus/springdata/repository/EmailRepository.java new file mode 100644 index 00000000..788feda5 --- /dev/null +++ b/2022-02/spring-11-data-jpa/solution-01/src/main/java/ru/otus/springdata/repository/EmailRepository.java @@ -0,0 +1,12 @@ +package ru.otus.springdata.repository; + +import org.springframework.data.jpa.repository.JpaRepository; +import ru.otus.springdata.domain.Email; + +import java.util.List; + +public interface EmailRepository extends JpaRepository { + + @Override + List findAll(); +} diff --git a/2022-02/spring-11-data-jpa/solution-01/src/main/java/ru/otus/springdata/repository/PersonRepository.java b/2022-02/spring-11-data-jpa/solution-01/src/main/java/ru/otus/springdata/repository/PersonRepository.java new file mode 100644 index 00000000..012ded26 --- /dev/null +++ b/2022-02/spring-11-data-jpa/solution-01/src/main/java/ru/otus/springdata/repository/PersonRepository.java @@ -0,0 +1,15 @@ +package ru.otus.springdata.repository; + +import org.springframework.data.repository.CrudRepository; +import ru.otus.springdata.domain.Person; + +import java.util.List; +import java.util.Optional; + +public interface PersonRepository extends CrudRepository { + + @Override + List findAll(); + + Optional findByName(String s); +} diff --git a/2022-02/spring-11-data-jpa/solution-01/src/main/resources/application.yml b/2022-02/spring-11-data-jpa/solution-01/src/main/resources/application.yml new file mode 100644 index 00000000..bd5b0f98 --- /dev/null +++ b/2022-02/spring-11-data-jpa/solution-01/src/main/resources/application.yml @@ -0,0 +1,20 @@ +spring: + datasource: + url: jdbc:h2:mem:testdb + initialization-mode: never + + jpa: + generate-ddl: true + hibernate: + ddl-auto: create + + properties: + hibernate: + format_sql: false + + show-sql: true + + +logging: + level: + ROOT: ERROR \ No newline at end of file diff --git a/2022-02/spring-11-data-jpa/solution-02/.gitignore b/2022-02/spring-11-data-jpa/solution-02/.gitignore new file mode 100644 index 00000000..e62c33c2 --- /dev/null +++ b/2022-02/spring-11-data-jpa/solution-02/.gitignore @@ -0,0 +1,4 @@ +.idea/ +*.iml + +target/ diff --git a/2022-02/spring-11-data-jpa/solution-02/pom.xml b/2022-02/spring-11-data-jpa/solution-02/pom.xml new file mode 100644 index 00000000..c6dd4ab8 --- /dev/null +++ b/2022-02/spring-11-data-jpa/solution-02/pom.xml @@ -0,0 +1,55 @@ + + + 4.0.0 + + ru.otus + solution-02 + 1.0-SNAPSHOT + + + org.springframework.boot + spring-boot-starter-parent + 2.4.5 + + + + 11 + 11 + + + + + org.springframework.boot + spring-boot-starter + + + org.springframework.boot + spring-boot-starter-data-jpa + + + com.h2database + h2 + + + org.springframework.boot + spring-boot-starter-test + test + + + org.projectlombok + lombok + true + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + diff --git a/2022-02/spring-11-data-jpa/solution-02/src/main/java/ru/otus/springdata/Main.java b/2022-02/spring-11-data-jpa/solution-02/src/main/java/ru/otus/springdata/Main.java new file mode 100644 index 00000000..d25a29d2 --- /dev/null +++ b/2022-02/spring-11-data-jpa/solution-02/src/main/java/ru/otus/springdata/Main.java @@ -0,0 +1,53 @@ +package ru.otus.springdata; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.ConfigurableApplicationContext; +import ru.otus.springdata.domain.Email; +import ru.otus.springdata.domain.Person; +import ru.otus.springdata.repository.EmailRepository; +import ru.otus.springdata.repository.PersonRepository; + +import java.util.Objects; +import java.util.stream.Collectors; + +@SpringBootApplication +public class Main { + + public static void main(String[] args) { + + ConfigurableApplicationContext context = SpringApplication.run(Main.class); + PersonRepository personRepository = context.getBean(PersonRepository.class); + EmailRepository emailRepository = context.getBean(EmailRepository.class); + + var pushkinEmail = new Email("alex.pushkin@mail.ru"); + var lermontovEmail = new Email("michail.lermontov@mail.ru"); + var gorbachevEmail = new Email("gorbachev@mail.ru"); + + var pushkin = new Person("Александр Сергеевич Пушкин"); + var lermontov = new Person("Михаил Юрьевич Лермонтов"); + var gorbachev = new Person("Михаил Сергеевич Горбачев"); + + emailRepository.save(pushkinEmail); + emailRepository.save(lermontovEmail); + emailRepository.save(gorbachevEmail); + + personRepository.save(pushkin); + personRepository.save(lermontov); + personRepository.save(gorbachev); + + System.out.println("\n\nИщем всех пёрсонов"); + System.out.println(personRepository.findAll().stream().map(Objects::toString) + .collect(Collectors.joining("\n"))); + + System.out.println("\n\nИщем Пушкина"); + personRepository.findByName("Александр Сергеевич Пушкин") + .ifPresent(System.out::println); + + System.out.println("\n\nИщем все почты"); + System.out.println(emailRepository.findAll().stream().map(Objects::toString) + .collect(Collectors.joining("\n"))); + + System.out.println("\n\n"); + } +} diff --git a/2022-02/spring-11-data-jpa/solution-02/src/main/java/ru/otus/springdata/domain/Email.java b/2022-02/spring-11-data-jpa/solution-02/src/main/java/ru/otus/springdata/domain/Email.java new file mode 100644 index 00000000..e3b8d344 --- /dev/null +++ b/2022-02/spring-11-data-jpa/solution-02/src/main/java/ru/otus/springdata/domain/Email.java @@ -0,0 +1,27 @@ +package ru.otus.springdata.domain; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Data +@NoArgsConstructor +@AllArgsConstructor +@Entity +public class Email { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private long id; + + private String address; + + public Email(String address) { + this.address = address; + } +} diff --git a/2022-02/spring-11-data-jpa/solution-02/src/main/java/ru/otus/springdata/domain/Person.java b/2022-02/spring-11-data-jpa/solution-02/src/main/java/ru/otus/springdata/domain/Person.java new file mode 100644 index 00000000..96d92b91 --- /dev/null +++ b/2022-02/spring-11-data-jpa/solution-02/src/main/java/ru/otus/springdata/domain/Person.java @@ -0,0 +1,25 @@ +package ru.otus.springdata.domain; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.persistence.*; + +@Data +@NoArgsConstructor +@AllArgsConstructor +@Entity +public class Person { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private long id; + + private String name; + + public Person(String name) { + this.name = name; + } + +} diff --git a/2022-02/spring-11-data-jpa/solution-02/src/main/java/ru/otus/springdata/repository/EmailRepository.java b/2022-02/spring-11-data-jpa/solution-02/src/main/java/ru/otus/springdata/repository/EmailRepository.java new file mode 100644 index 00000000..3d5c3152 --- /dev/null +++ b/2022-02/spring-11-data-jpa/solution-02/src/main/java/ru/otus/springdata/repository/EmailRepository.java @@ -0,0 +1,13 @@ +package ru.otus.springdata.repository; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; +import org.springframework.transaction.annotation.Transactional; +import ru.otus.springdata.domain.Email; + +import java.util.Optional; + +public interface EmailRepository extends JpaRepository{ +} diff --git a/2022-02/spring-11-data-jpa/solution-02/src/main/java/ru/otus/springdata/repository/PersonRepository.java b/2022-02/spring-11-data-jpa/solution-02/src/main/java/ru/otus/springdata/repository/PersonRepository.java new file mode 100644 index 00000000..cd5bb3f0 --- /dev/null +++ b/2022-02/spring-11-data-jpa/solution-02/src/main/java/ru/otus/springdata/repository/PersonRepository.java @@ -0,0 +1,14 @@ +package ru.otus.springdata.repository; + +import org.springframework.data.repository.CrudRepository; +import ru.otus.springdata.domain.Person; + +import java.util.List; +import java.util.Optional; + +public interface PersonRepository extends CrudRepository { + + List findAll(); + + Optional findByName(String s); +} diff --git a/2022-02/spring-11-data-jpa/solution-02/src/main/resources/application.yml b/2022-02/spring-11-data-jpa/solution-02/src/main/resources/application.yml new file mode 100644 index 00000000..bd5b0f98 --- /dev/null +++ b/2022-02/spring-11-data-jpa/solution-02/src/main/resources/application.yml @@ -0,0 +1,20 @@ +spring: + datasource: + url: jdbc:h2:mem:testdb + initialization-mode: never + + jpa: + generate-ddl: true + hibernate: + ddl-auto: create + + properties: + hibernate: + format_sql: false + + show-sql: true + + +logging: + level: + ROOT: ERROR \ No newline at end of file diff --git a/2022-02/spring-11-data-jpa/solution-03/.gitignore b/2022-02/spring-11-data-jpa/solution-03/.gitignore new file mode 100644 index 00000000..e62c33c2 --- /dev/null +++ b/2022-02/spring-11-data-jpa/solution-03/.gitignore @@ -0,0 +1,4 @@ +.idea/ +*.iml + +target/ diff --git a/2022-02/spring-11-data-jpa/solution-03/pom.xml b/2022-02/spring-11-data-jpa/solution-03/pom.xml new file mode 100644 index 00000000..4fff22c3 --- /dev/null +++ b/2022-02/spring-11-data-jpa/solution-03/pom.xml @@ -0,0 +1,55 @@ + + + 4.0.0 + + ru.otus + solution-03 + 1.0-SNAPSHOT + + + org.springframework.boot + spring-boot-starter-parent + 2.4.5 + + + + 11 + 11 + + + + + org.springframework.boot + spring-boot-starter + + + org.springframework.boot + spring-boot-starter-data-jpa + + + com.h2database + h2 + + + org.springframework.boot + spring-boot-starter-test + test + + + org.projectlombok + lombok + true + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + diff --git a/2022-02/spring-11-data-jpa/solution-03/src/main/java/ru/otus/springdata/Main.java b/2022-02/spring-11-data-jpa/solution-03/src/main/java/ru/otus/springdata/Main.java new file mode 100644 index 00000000..a02e3e25 --- /dev/null +++ b/2022-02/spring-11-data-jpa/solution-03/src/main/java/ru/otus/springdata/Main.java @@ -0,0 +1,55 @@ +package ru.otus.springdata; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.data.domain.Example; +import org.springframework.data.domain.ExampleMatcher; +import ru.otus.springdata.domain.Email; +import ru.otus.springdata.domain.Person; +import ru.otus.springdata.repository.EmailRepository; +import ru.otus.springdata.repository.PersonRepository; + +import java.util.Objects; +import java.util.stream.Collectors; + +@SpringBootApplication +public class Main { + + public static void main(String[] args) { + ConfigurableApplicationContext context = SpringApplication.run(Main.class); + + PersonRepository personRepository = context.getBean(PersonRepository.class); + EmailRepository emailRepository = context.getBean(EmailRepository.class); + + var pushkin = new Person("Александр Сергеевич Пушкин", new Email("alex.pushkin@mail.ru")); + var lermontov = new Person("Михаил Юрьевич Лермонтов", new Email("michail.lermontov@mail.ru")); + var gorbachev = new Person("Михаил Сергеевич Горбачев", new Email("gorbachev@mail.ru")); + + emailRepository.save(pushkin.getEmail()); + emailRepository.save(lermontov.getEmail()); + emailRepository.save(gorbachev.getEmail()); + + personRepository.save(pushkin); + personRepository.save(lermontov); + personRepository.save(gorbachev); + + System.out.println("\n\nИщем всех пёрсонов"); + System.out.println(personRepository.findAll().stream().map(Objects::toString) + .collect(Collectors.joining("\n"))); + + System.out.println("\n\nИщем Пушкина"); + personRepository.findByName("Александр Сергеевич Пушкин") + .ifPresent(System.out::println); + + System.out.println("\n\nИщем все почты"); + System.out.println(emailRepository.findAll().stream().map(Objects::toString) + .collect(Collectors.joining("\n"))); + + System.out.println("\n\nИщем Пушкина по его почте"); + personRepository.findByEmailAddress("alex.pushkin@mail.ru") + .ifPresent(System.out::println); + + System.out.println("\n\n"); + } +} diff --git a/2022-02/spring-11-data-jpa/solution-03/src/main/java/ru/otus/springdata/domain/Email.java b/2022-02/spring-11-data-jpa/solution-03/src/main/java/ru/otus/springdata/domain/Email.java new file mode 100644 index 00000000..e3b8d344 --- /dev/null +++ b/2022-02/spring-11-data-jpa/solution-03/src/main/java/ru/otus/springdata/domain/Email.java @@ -0,0 +1,27 @@ +package ru.otus.springdata.domain; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Data +@NoArgsConstructor +@AllArgsConstructor +@Entity +public class Email { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private long id; + + private String address; + + public Email(String address) { + this.address = address; + } +} diff --git a/2022-02/spring-11-data-jpa/solution-03/src/main/java/ru/otus/springdata/domain/Person.java b/2022-02/spring-11-data-jpa/solution-03/src/main/java/ru/otus/springdata/domain/Person.java new file mode 100644 index 00000000..e24e42aa --- /dev/null +++ b/2022-02/spring-11-data-jpa/solution-03/src/main/java/ru/otus/springdata/domain/Person.java @@ -0,0 +1,30 @@ +package ru.otus.springdata.domain; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.persistence.*; + +@Data +@NoArgsConstructor +@AllArgsConstructor +@Entity +public class Person { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private long id; + + private String name; + + @OneToOne(orphanRemoval = true) + @JoinColumn(name = "email_id") + private Email email; + + public Person(String name, Email email) { + this.name = name; + this.email = email; + } + +} diff --git a/2022-02/spring-11-data-jpa/solution-03/src/main/java/ru/otus/springdata/repository/EmailRepository.java b/2022-02/spring-11-data-jpa/solution-03/src/main/java/ru/otus/springdata/repository/EmailRepository.java new file mode 100644 index 00000000..16f1d0c9 --- /dev/null +++ b/2022-02/spring-11-data-jpa/solution-03/src/main/java/ru/otus/springdata/repository/EmailRepository.java @@ -0,0 +1,13 @@ +package ru.otus.springdata.repository; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; +import org.springframework.transaction.annotation.Transactional; +import ru.otus.springdata.domain.Email; + +import java.util.Optional; + +public interface EmailRepository extends JpaRepository { +} diff --git a/2022-02/spring-11-data-jpa/solution-03/src/main/java/ru/otus/springdata/repository/PersonRepository.java b/2022-02/spring-11-data-jpa/solution-03/src/main/java/ru/otus/springdata/repository/PersonRepository.java new file mode 100644 index 00000000..a6aa8dd3 --- /dev/null +++ b/2022-02/spring-11-data-jpa/solution-03/src/main/java/ru/otus/springdata/repository/PersonRepository.java @@ -0,0 +1,18 @@ +package ru.otus.springdata.repository; + +import org.springframework.data.jpa.repository.EntityGraph; +import org.springframework.data.repository.CrudRepository; +import ru.otus.springdata.domain.Person; + +import java.util.List; +import java.util.Optional; + +public interface PersonRepository extends CrudRepository { + + @EntityGraph(attributePaths = "email") + List findAll(); + + Optional findByName(String s); + + Optional findByEmailAddress(String email); +} diff --git a/2022-02/spring-11-data-jpa/solution-03/src/main/resources/application.yml b/2022-02/spring-11-data-jpa/solution-03/src/main/resources/application.yml new file mode 100644 index 00000000..bd5b0f98 --- /dev/null +++ b/2022-02/spring-11-data-jpa/solution-03/src/main/resources/application.yml @@ -0,0 +1,20 @@ +spring: + datasource: + url: jdbc:h2:mem:testdb + initialization-mode: never + + jpa: + generate-ddl: true + hibernate: + ddl-auto: create + + properties: + hibernate: + format_sql: false + + show-sql: true + + +logging: + level: + ROOT: ERROR \ No newline at end of file diff --git a/2022-02/spring-11-data-jpa/solution-04/.gitignore b/2022-02/spring-11-data-jpa/solution-04/.gitignore new file mode 100644 index 00000000..e62c33c2 --- /dev/null +++ b/2022-02/spring-11-data-jpa/solution-04/.gitignore @@ -0,0 +1,4 @@ +.idea/ +*.iml + +target/ diff --git a/2022-02/spring-11-data-jpa/solution-04/pom.xml b/2022-02/spring-11-data-jpa/solution-04/pom.xml new file mode 100644 index 00000000..6f0a221c --- /dev/null +++ b/2022-02/spring-11-data-jpa/solution-04/pom.xml @@ -0,0 +1,55 @@ + + + 4.0.0 + + ru.otus + solution-04 + 1.0-SNAPSHOT + + + org.springframework.boot + spring-boot-starter-parent + 2.4.5 + + + + 11 + 11 + + + + + org.springframework.boot + spring-boot-starter + + + org.springframework.boot + spring-boot-starter-data-jpa + + + com.h2database + h2 + + + org.springframework.boot + spring-boot-starter-test + test + + + org.projectlombok + lombok + true + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + diff --git a/2022-02/spring-11-data-jpa/solution-04/src/main/java/ru/otus/springdata/Main.java b/2022-02/spring-11-data-jpa/solution-04/src/main/java/ru/otus/springdata/Main.java new file mode 100644 index 00000000..4574b783 --- /dev/null +++ b/2022-02/spring-11-data-jpa/solution-04/src/main/java/ru/otus/springdata/Main.java @@ -0,0 +1,64 @@ +package ru.otus.springdata; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.data.domain.Example; +import org.springframework.data.domain.ExampleMatcher; +import ru.otus.springdata.domain.Email; +import ru.otus.springdata.domain.Person; +import ru.otus.springdata.repository.EmailRepository; +import ru.otus.springdata.repository.PersonRepository; + +import java.util.Objects; +import java.util.stream.Collectors; + +@SpringBootApplication +public class Main { + + public static void main(String[] args) { + ConfigurableApplicationContext context = SpringApplication.run(Main.class); + + PersonRepository personRepository = context.getBean(PersonRepository.class); + EmailRepository emailRepository = context.getBean(EmailRepository.class); + + var pushkin = new Person("Александр Сергеевич Пушкин", new Email("alex.pushkin@mail.ru")); + var lermontov = new Person("Михаил Юрьевич Лермонтов", new Email("michail.lermontov@mail.ru")); + var gorbachev = new Person("Михаил Сергеевич Горбачев", new Email("gorbachev@mail.ru")); + + emailRepository.save(pushkin.getEmail()); + emailRepository.save(lermontov.getEmail()); + emailRepository.save(gorbachev.getEmail()); + + personRepository.save(pushkin); + personRepository.save(lermontov); + personRepository.save(gorbachev); + + System.out.println("\n\nИщем всех пёрсонов"); + System.out.println(personRepository.findAll().stream().map(Objects::toString) + .collect(Collectors.joining("\n"))); + + System.out.println("\n\nИщем Пушкина"); + personRepository.findByName("Александр Сергеевич Пушкин") + .ifPresent(System.out::println); + + System.out.println("\n\nИщем все почты"); + System.out.println(emailRepository.findAll().stream().map(Objects::toString) + .collect(Collectors.joining("\n"))); + + System.out.println("\n\nИщем Пушкина по его почте"); + personRepository.findByEmailAddress("alex.pushkin@mail.ru") + .ifPresent(System.out::println); + + System.out.println("\n\nОбновляем почту Лермонтову"); + System.out.println("До обновления: " + lermontov.getEmail()); + emailRepository.updateEmailById(lermontov.getId(), "michail1984@lermontov.ru"); + + System.out.println("\n\nИщем почту Лермонтова по новому адресу"); + emailRepository.findByEmailAddress("michail1984@lermontov.ru") + .ifPresent(e -> System.out.println("После обновления: " + e)); + + System.out.println("\n\n"); + + } +} diff --git a/2022-02/spring-11-data-jpa/solution-04/src/main/java/ru/otus/springdata/domain/Email.java b/2022-02/spring-11-data-jpa/solution-04/src/main/java/ru/otus/springdata/domain/Email.java new file mode 100644 index 00000000..e3b8d344 --- /dev/null +++ b/2022-02/spring-11-data-jpa/solution-04/src/main/java/ru/otus/springdata/domain/Email.java @@ -0,0 +1,27 @@ +package ru.otus.springdata.domain; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Data +@NoArgsConstructor +@AllArgsConstructor +@Entity +public class Email { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private long id; + + private String address; + + public Email(String address) { + this.address = address; + } +} diff --git a/2022-02/spring-11-data-jpa/solution-04/src/main/java/ru/otus/springdata/domain/Person.java b/2022-02/spring-11-data-jpa/solution-04/src/main/java/ru/otus/springdata/domain/Person.java new file mode 100644 index 00000000..e24e42aa --- /dev/null +++ b/2022-02/spring-11-data-jpa/solution-04/src/main/java/ru/otus/springdata/domain/Person.java @@ -0,0 +1,30 @@ +package ru.otus.springdata.domain; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.persistence.*; + +@Data +@NoArgsConstructor +@AllArgsConstructor +@Entity +public class Person { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private long id; + + private String name; + + @OneToOne(orphanRemoval = true) + @JoinColumn(name = "email_id") + private Email email; + + public Person(String name, Email email) { + this.name = name; + this.email = email; + } + +} diff --git a/2022-02/spring-11-data-jpa/solution-04/src/main/java/ru/otus/springdata/repository/EmailRepository.java b/2022-02/spring-11-data-jpa/solution-04/src/main/java/ru/otus/springdata/repository/EmailRepository.java new file mode 100644 index 00000000..66b4da80 --- /dev/null +++ b/2022-02/spring-11-data-jpa/solution-04/src/main/java/ru/otus/springdata/repository/EmailRepository.java @@ -0,0 +1,21 @@ +package ru.otus.springdata.repository; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; +import org.springframework.transaction.annotation.Transactional; +import ru.otus.springdata.domain.Email; + +import java.util.Optional; + +public interface EmailRepository extends JpaRepository { + + @Query("select e from Email e where e.address = :address") + Optional findByEmailAddress(@Param("address") String email); + + @Modifying + @Transactional + @Query("update Email e set e.address = :address where e.id = :id") + void updateEmailById(@Param("id") long id, @Param("address") String address); +} diff --git a/2022-02/spring-11-data-jpa/solution-04/src/main/java/ru/otus/springdata/repository/PersonRepository.java b/2022-02/spring-11-data-jpa/solution-04/src/main/java/ru/otus/springdata/repository/PersonRepository.java new file mode 100644 index 00000000..a6aa8dd3 --- /dev/null +++ b/2022-02/spring-11-data-jpa/solution-04/src/main/java/ru/otus/springdata/repository/PersonRepository.java @@ -0,0 +1,18 @@ +package ru.otus.springdata.repository; + +import org.springframework.data.jpa.repository.EntityGraph; +import org.springframework.data.repository.CrudRepository; +import ru.otus.springdata.domain.Person; + +import java.util.List; +import java.util.Optional; + +public interface PersonRepository extends CrudRepository { + + @EntityGraph(attributePaths = "email") + List findAll(); + + Optional findByName(String s); + + Optional findByEmailAddress(String email); +} diff --git a/2022-02/spring-11-data-jpa/solution-04/src/main/resources/application.yml b/2022-02/spring-11-data-jpa/solution-04/src/main/resources/application.yml new file mode 100644 index 00000000..bd5b0f98 --- /dev/null +++ b/2022-02/spring-11-data-jpa/solution-04/src/main/resources/application.yml @@ -0,0 +1,20 @@ +spring: + datasource: + url: jdbc:h2:mem:testdb + initialization-mode: never + + jpa: + generate-ddl: true + hibernate: + ddl-auto: create + + properties: + hibernate: + format_sql: false + + show-sql: true + + +logging: + level: + ROOT: ERROR \ No newline at end of file diff --git a/2022-02/spring-13/spring-data-keyvalue-class-work/pom.xml b/2022-02/spring-13/spring-data-keyvalue-class-work/pom.xml new file mode 100644 index 00000000..b2fbb1c3 --- /dev/null +++ b/2022-02/spring-13/spring-data-keyvalue-class-work/pom.xml @@ -0,0 +1,17 @@ + + + 4.0.0 + + ru.otus + spring-data-keyvalue-class-work + 1.0 + + pom + + + spring-data-keyvalue-exercise + spring-data-keyvalue-solution + + diff --git a/2022-02/spring-13/spring-data-keyvalue-class-work/spring-data-keyvalue-exercise/pom.xml b/2022-02/spring-13/spring-data-keyvalue-class-work/spring-data-keyvalue-exercise/pom.xml new file mode 100644 index 00000000..180b1a60 --- /dev/null +++ b/2022-02/spring-13/spring-data-keyvalue-class-work/spring-data-keyvalue-exercise/pom.xml @@ -0,0 +1,43 @@ + + + 4.0.0 + + ru.otus + spring-data-keyvalue-exercise + 1.0-SNAPSHOT + + + org.springframework.boot + spring-boot-starter-parent + 2.2.1.RELEASE + + + + + 11 + 11 + + + + + org.springframework.boot + spring-boot-starter + + + + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + diff --git a/2022-02/spring-13/spring-data-keyvalue-class-work/spring-data-keyvalue-exercise/src/main/java/ru/otus/spring/Main.java b/2022-02/spring-13/spring-data-keyvalue-class-work/spring-data-keyvalue-exercise/src/main/java/ru/otus/spring/Main.java new file mode 100644 index 00000000..d0d34e97 --- /dev/null +++ b/2022-02/spring-13/spring-data-keyvalue-class-work/spring-data-keyvalue-exercise/src/main/java/ru/otus/spring/Main.java @@ -0,0 +1,29 @@ +package ru.otus.spring; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.data.map.repository.config.EnableMapRepositories; +import ru.otus.spring.domain.Person; +import ru.otus.spring.repostory.PersonRepository; + +import javax.annotation.PostConstruct; + +@SpringBootApplication +public class Main { + + public static void main(String[] args) { + SpringApplication.run(Main.class); + } + + @SuppressWarnings("SpringJavaAutowiredFieldsWarningInspection") + @Autowired + private PersonRepository repository; + + @PostConstruct + public void init() { + repository.save(new Person(1, "Pushkin")); + + repository.findAll(); + } +} diff --git a/2022-02/spring-13/spring-data-keyvalue-class-work/spring-data-keyvalue-exercise/src/main/java/ru/otus/spring/domain/Email.java b/2022-02/spring-13/spring-data-keyvalue-class-work/spring-data-keyvalue-exercise/src/main/java/ru/otus/spring/domain/Email.java new file mode 100644 index 00000000..c1e24a7d --- /dev/null +++ b/2022-02/spring-13/spring-data-keyvalue-class-work/spring-data-keyvalue-exercise/src/main/java/ru/otus/spring/domain/Email.java @@ -0,0 +1,25 @@ +package ru.otus.spring.domain; + +public class Email { + + private int id; + + private String email; + + public Email(String email) { + this.email = email; + } + + public Email(int id, String email) { + this.id = id; + this.email = email; + } + + public int getId() { + return id; + } + + public String getEmail() { + return email; + } +} diff --git a/2022-02/spring-13/spring-data-keyvalue-class-work/spring-data-keyvalue-exercise/src/main/java/ru/otus/spring/domain/Person.java b/2022-02/spring-13/spring-data-keyvalue-class-work/spring-data-keyvalue-exercise/src/main/java/ru/otus/spring/domain/Person.java new file mode 100644 index 00000000..f707e14e --- /dev/null +++ b/2022-02/spring-13/spring-data-keyvalue-class-work/spring-data-keyvalue-exercise/src/main/java/ru/otus/spring/domain/Person.java @@ -0,0 +1,35 @@ +package ru.otus.spring.domain; + +import org.springframework.data.annotation.Id; +import org.springframework.data.keyvalue.annotation.KeySpace; + +public class Person { + + private int id; + private String name; + + public Person(String name) { + this.name = name; + } + + public Person(int id, String name) { + this.id = id; + this.name = name; + } + + 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; + } +} diff --git a/2022-02/spring-13/spring-data-keyvalue-class-work/spring-data-keyvalue-exercise/src/main/java/ru/otus/spring/repostory/PersonRepository.java b/2022-02/spring-13/spring-data-keyvalue-class-work/spring-data-keyvalue-exercise/src/main/java/ru/otus/spring/repostory/PersonRepository.java new file mode 100644 index 00000000..4b20e5b7 --- /dev/null +++ b/2022-02/spring-13/spring-data-keyvalue-class-work/spring-data-keyvalue-exercise/src/main/java/ru/otus/spring/repostory/PersonRepository.java @@ -0,0 +1,11 @@ +package ru.otus.spring.repostory; + +import org.springframework.data.repository.CrudRepository; +import ru.otus.spring.domain.Person; + +import java.util.List; + +public interface PersonRepository extends CrudRepository { + + List findAll(); +} diff --git a/2022-02/spring-13/spring-data-keyvalue-class-work/spring-data-keyvalue-solution/pom.xml b/2022-02/spring-13/spring-data-keyvalue-class-work/spring-data-keyvalue-solution/pom.xml new file mode 100644 index 00000000..7d0041e8 --- /dev/null +++ b/2022-02/spring-13/spring-data-keyvalue-class-work/spring-data-keyvalue-solution/pom.xml @@ -0,0 +1,43 @@ + + + 4.0.0 + + ru.otus + spring-data-keyvalue-solution + 1.0-SNAPSHOT + + + org.springframework.boot + spring-boot-starter-parent + 2.2.1.RELEASE + + + + + 11 + 11 + + + + + org.springframework.boot + spring-boot-starter + + + org.springframework.data + spring-data-keyvalue + 2.2.1.RELEASE + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + diff --git a/2022-02/spring-13/spring-data-keyvalue-class-work/spring-data-keyvalue-solution/src/main/java/ru/otus/spring/Main.java b/2022-02/spring-13/spring-data-keyvalue-class-work/spring-data-keyvalue-solution/src/main/java/ru/otus/spring/Main.java new file mode 100644 index 00000000..42d9078f --- /dev/null +++ b/2022-02/spring-13/spring-data-keyvalue-class-work/spring-data-keyvalue-solution/src/main/java/ru/otus/spring/Main.java @@ -0,0 +1,39 @@ +package ru.otus.spring; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.data.map.repository.config.EnableMapRepositories; +import ru.otus.spring.domain.Email; +import ru.otus.spring.domain.Person; +import ru.otus.spring.repostory.EmailRepository; +import ru.otus.spring.repostory.PersonRepository; + +import javax.annotation.PostConstruct; + +@SpringBootApplication +@EnableMapRepositories +public class Main { + + public static void main(String[] args) { + SpringApplication.run(Main.class); + } + + @SuppressWarnings("SpringJavaAutowiredFieldsWarningInspection") + @Autowired + private PersonRepository repository; + + @Autowired + private EmailRepository emailRepository; + + @PostConstruct + public void init() { + repository.save(new Person(1, "Pushkin")); + repository.save(new Person(2, "Lermontov")); + System.out.println(repository.findAll()); + + emailRepository.save(new Email(1, "alex@pushkin.com")); + emailRepository.save(new Email(2, "micha@pushkin.com")); + System.out.println(emailRepository.findAll()); + } +} diff --git a/2022-02/spring-13/spring-data-keyvalue-class-work/spring-data-keyvalue-solution/src/main/java/ru/otus/spring/domain/Email.java b/2022-02/spring-13/spring-data-keyvalue-class-work/spring-data-keyvalue-solution/src/main/java/ru/otus/spring/domain/Email.java new file mode 100644 index 00000000..86ddb0c1 --- /dev/null +++ b/2022-02/spring-13/spring-data-keyvalue-class-work/spring-data-keyvalue-solution/src/main/java/ru/otus/spring/domain/Email.java @@ -0,0 +1,37 @@ +package ru.otus.spring.domain; + +import org.springframework.data.annotation.Id; +import org.springframework.data.keyvalue.annotation.KeySpace; + +@KeySpace("email") +public class Email { + @Id + private int id; + + private String email; + + public Email(int id, String email) { + this.id = id; + this.email = email; + } + + public Email(String email) { + this.email = email; + } + + public int getId() { + return id; + } + + public String getEmail() { + return email; + } + + @Override + public String toString() { + return "Email{" + + "id=" + id + + ", email='" + email + '\'' + + '}'; + } +} diff --git a/2022-02/spring-13/spring-data-keyvalue-class-work/spring-data-keyvalue-solution/src/main/java/ru/otus/spring/domain/Person.java b/2022-02/spring-13/spring-data-keyvalue-class-work/spring-data-keyvalue-solution/src/main/java/ru/otus/spring/domain/Person.java new file mode 100644 index 00000000..b0181bd1 --- /dev/null +++ b/2022-02/spring-13/spring-data-keyvalue-class-work/spring-data-keyvalue-solution/src/main/java/ru/otus/spring/domain/Person.java @@ -0,0 +1,45 @@ +package ru.otus.spring.domain; + +import org.springframework.data.annotation.Id; +import org.springframework.data.keyvalue.annotation.KeySpace; + +@KeySpace("person") +public class Person { + + @Id + private int id; + private String name; + + public Person(int id, String name) { + this.id = id; + this.name = name; + } + + public Person(String name) { + this.name = name; + } + + 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; + } + + @Override + public String toString() { + return "Person{" + + "id=" + id + + ", name='" + name + '\'' + + '}'; + } +} diff --git a/2022-02/spring-13/spring-data-keyvalue-class-work/spring-data-keyvalue-solution/src/main/java/ru/otus/spring/repostory/EmailRepository.java b/2022-02/spring-13/spring-data-keyvalue-class-work/spring-data-keyvalue-solution/src/main/java/ru/otus/spring/repostory/EmailRepository.java new file mode 100644 index 00000000..6ce870a2 --- /dev/null +++ b/2022-02/spring-13/spring-data-keyvalue-class-work/spring-data-keyvalue-solution/src/main/java/ru/otus/spring/repostory/EmailRepository.java @@ -0,0 +1,14 @@ +package ru.otus.spring.repostory; + +import org.springframework.data.keyvalue.repository.KeyValueRepository; +import org.springframework.stereotype.Repository; +import ru.otus.spring.domain.Email; +import ru.otus.spring.domain.Person; + +import java.util.List; + +public interface EmailRepository { + + List findAll(); + Email save(Email email); +} diff --git a/2022-02/spring-13/spring-data-keyvalue-class-work/spring-data-keyvalue-solution/src/main/java/ru/otus/spring/repostory/EmailRepositoryImpl.java b/2022-02/spring-13/spring-data-keyvalue-class-work/spring-data-keyvalue-solution/src/main/java/ru/otus/spring/repostory/EmailRepositoryImpl.java new file mode 100644 index 00000000..e2aa75a1 --- /dev/null +++ b/2022-02/spring-13/spring-data-keyvalue-class-work/spring-data-keyvalue-solution/src/main/java/ru/otus/spring/repostory/EmailRepositoryImpl.java @@ -0,0 +1,27 @@ +package ru.otus.spring.repostory; + +import org.springframework.data.keyvalue.core.KeyValueOperations; +import org.springframework.stereotype.Repository; +import ru.otus.spring.domain.Email; + +import java.util.List; + +@Repository +public class EmailRepositoryImpl implements EmailRepository { + + final private KeyValueOperations keyValueTemplate; + + public EmailRepositoryImpl(KeyValueOperations keyValueTemplate) { + this.keyValueTemplate = keyValueTemplate; + } + + @Override + public List findAll() { + return (List) keyValueTemplate.findAll(Email.class); + } + + @Override + public Email save(Email email) { + return keyValueTemplate.insert(email); + } +} diff --git a/2022-02/spring-13/spring-data-keyvalue-class-work/spring-data-keyvalue-solution/src/main/java/ru/otus/spring/repostory/PersonRepository.java b/2022-02/spring-13/spring-data-keyvalue-class-work/spring-data-keyvalue-solution/src/main/java/ru/otus/spring/repostory/PersonRepository.java new file mode 100644 index 00000000..99a93c24 --- /dev/null +++ b/2022-02/spring-13/spring-data-keyvalue-class-work/spring-data-keyvalue-solution/src/main/java/ru/otus/spring/repostory/PersonRepository.java @@ -0,0 +1,12 @@ +package ru.otus.spring.repostory; + +import org.springframework.data.keyvalue.repository.KeyValueRepository; +import org.springframework.data.repository.CrudRepository; +import ru.otus.spring.domain.Person; + +import java.util.List; + +public interface PersonRepository extends KeyValueRepository { + + List findAll(); +} diff --git a/2022-02/spring-13/spring-data-mongo-class-work/pom.xml b/2022-02/spring-13/spring-data-mongo-class-work/pom.xml new file mode 100644 index 00000000..a13c15b7 --- /dev/null +++ b/2022-02/spring-13/spring-data-mongo-class-work/pom.xml @@ -0,0 +1,17 @@ + + + 4.0.0 + + ru.otus + spring-data-mongo-class-work + 1.0 + + pom + + + spring-data-mongo-exercise + spring-data-mongo-solution + + diff --git a/2022-02/spring-13/spring-data-mongo-class-work/spring-data-mongo-exercise/pom.xml b/2022-02/spring-13/spring-data-mongo-class-work/spring-data-mongo-exercise/pom.xml new file mode 100644 index 00000000..5cb9d0e1 --- /dev/null +++ b/2022-02/spring-13/spring-data-mongo-class-work/spring-data-mongo-exercise/pom.xml @@ -0,0 +1,46 @@ + + + 4.0.0 + + ru.otus + spring-data-mongo-exercise + 1.0-SNAPSHOT + + + org.springframework.boot + spring-boot-starter-parent + 2.3.4.RELEASE + + + + + 11 + 11 + + + + + org.springframework.boot + spring-boot-starter + + + org.springframework.boot + spring-boot-starter-data-mongodb + + + de.flapdoodle.embed + de.flapdoodle.embed.mongo + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + diff --git a/2022-02/spring-13/spring-data-mongo-class-work/spring-data-mongo-exercise/src/main/java/ru/otus/spring/Main.java b/2022-02/spring-13/spring-data-mongo-class-work/spring-data-mongo-exercise/src/main/java/ru/otus/spring/Main.java new file mode 100644 index 00000000..d67d7972 --- /dev/null +++ b/2022-02/spring-13/spring-data-mongo-class-work/spring-data-mongo-exercise/src/main/java/ru/otus/spring/Main.java @@ -0,0 +1,31 @@ +package ru.otus.spring; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.ApplicationContext; +import ru.otus.spring.domain.Person; +import ru.otus.spring.repostory.PersonRepository; + +@SpringBootApplication +public class Main { + + @SuppressWarnings("SpringJavaAutowiredFieldsWarningInspection") + @Autowired + private PersonRepository repository; + + public static void main(String[] args) throws InterruptedException { + ApplicationContext context = SpringApplication.run(Main.class); + + PersonRepository repository = context.getBean(PersonRepository.class); + + repository.save(new Person("Dostoevsky")); + + Thread.sleep(3000); + + System.out.println("\n\n\n----------------------------------------------\n\n"); + System.out.println("Авторы в БД:"); + repository.findAll().forEach(p -> System.out.println(p.getName())); + System.out.println("\n\n----------------------------------------------\n\n\n"); + } +} diff --git a/2022-02/spring-13/spring-data-mongo-class-work/spring-data-mongo-exercise/src/main/java/ru/otus/spring/domain/Person.java b/2022-02/spring-13/spring-data-mongo-class-work/spring-data-mongo-exercise/src/main/java/ru/otus/spring/domain/Person.java new file mode 100644 index 00000000..2bdc3894 --- /dev/null +++ b/2022-02/spring-13/spring-data-mongo-class-work/spring-data-mongo-exercise/src/main/java/ru/otus/spring/domain/Person.java @@ -0,0 +1,27 @@ +package ru.otus.spring.domain; + +public class Person { + + private String id; + private String name; + + public Person(String name) { + this.name = name; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/2022-02/spring-13/spring-data-mongo-class-work/spring-data-mongo-exercise/src/main/java/ru/otus/spring/repostory/PersonRepository.java b/2022-02/spring-13/spring-data-mongo-class-work/spring-data-mongo-exercise/src/main/java/ru/otus/spring/repostory/PersonRepository.java new file mode 100644 index 00000000..763a2288 --- /dev/null +++ b/2022-02/spring-13/spring-data-mongo-class-work/spring-data-mongo-exercise/src/main/java/ru/otus/spring/repostory/PersonRepository.java @@ -0,0 +1,12 @@ +package ru.otus.spring.repostory; + +import org.springframework.data.repository.CrudRepository; +import ru.otus.spring.domain.Person; + +import java.util.List; + + +public interface PersonRepository extends CrudRepository { + + List findAll(); +} diff --git a/2022-02/spring-13/spring-data-mongo-class-work/spring-data-mongo-exercise/src/main/resources/application.yml b/2022-02/spring-13/spring-data-mongo-class-work/spring-data-mongo-exercise/src/main/resources/application.yml new file mode 100644 index 00000000..9bffd5dc --- /dev/null +++ b/2022-02/spring-13/spring-data-mongo-class-work/spring-data-mongo-exercise/src/main/resources/application.yml @@ -0,0 +1,4 @@ +spring: + data: + mongodb: + database: company diff --git a/2022-02/spring-13/spring-data-mongo-class-work/spring-data-mongo-solution/pom.xml b/2022-02/spring-13/spring-data-mongo-class-work/spring-data-mongo-solution/pom.xml new file mode 100644 index 00000000..6045db5d --- /dev/null +++ b/2022-02/spring-13/spring-data-mongo-class-work/spring-data-mongo-solution/pom.xml @@ -0,0 +1,61 @@ + + + 4.0.0 + + ru.otus + spring-data-mongo-solution + 1.0-SNAPSHOT + + + org.springframework.boot + spring-boot-starter-parent + 2.3.4.RELEASE + + + + + 11 + 11 + 4.1.17 + + + + + + org.springframework.boot + spring-boot-starter + + + org.springframework.boot + spring-boot-starter-data-mongodb + + + de.flapdoodle.embed + de.flapdoodle.embed.mongo + + + + com.github.cloudyrock.mongock + mongock-spring-v5 + ${mongock.version} + + + + com.github.cloudyrock.mongock + mongodb-springdata-v3-driver + ${mongock.version} + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + diff --git a/2022-02/spring-13/spring-data-mongo-class-work/spring-data-mongo-solution/src/main/java/ru/otus/spring/Main.java b/2022-02/spring-13/spring-data-mongo-class-work/spring-data-mongo-solution/src/main/java/ru/otus/spring/Main.java new file mode 100644 index 00000000..fb0e8a60 --- /dev/null +++ b/2022-02/spring-13/spring-data-mongo-class-work/spring-data-mongo-solution/src/main/java/ru/otus/spring/Main.java @@ -0,0 +1,35 @@ +package ru.otus.spring; + +import com.github.cloudyrock.spring.v5.EnableMongock; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.ApplicationContext; +import org.springframework.data.mongodb.repository.config.EnableMongoRepositories; +import ru.otus.spring.domain.Person; +import ru.otus.spring.repostory.PersonRepository; + +@EnableMongock +@EnableMongoRepositories +@SpringBootApplication +public class Main { + + @SuppressWarnings("SpringJavaAutowiredFieldsWarningInspection") + @Autowired + private PersonRepository repository; + + public static void main(String[] args) throws InterruptedException { + ApplicationContext context = SpringApplication.run(Main.class); + + PersonRepository repository = context.getBean(PersonRepository.class); + + repository.save(new Person("Dostoevsky")); + + Thread.sleep(3000); + + System.out.println("\n\n\n----------------------------------------------\n\n"); + System.out.println("Авторы в БД:"); + repository.findAll().forEach(p -> System.out.println(p.getName())); + System.out.println("\n\n----------------------------------------------\n\n\n"); + } +} diff --git a/2022-02/spring-13/spring-data-mongo-class-work/spring-data-mongo-solution/src/main/java/ru/otus/spring/domain/Person.java b/2022-02/spring-13/spring-data-mongo-class-work/spring-data-mongo-solution/src/main/java/ru/otus/spring/domain/Person.java new file mode 100644 index 00000000..12cf6355 --- /dev/null +++ b/2022-02/spring-13/spring-data-mongo-class-work/spring-data-mongo-solution/src/main/java/ru/otus/spring/domain/Person.java @@ -0,0 +1,32 @@ +package ru.otus.spring.domain; + +import org.springframework.data.annotation.Id; +import org.springframework.data.mongodb.core.mapping.Document; + +@Document(collection = "persons") +public class Person { + + @Id + private String id; + private String name; + + public Person(String name) { + this.name = name; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/2022-02/spring-13/spring-data-mongo-class-work/spring-data-mongo-solution/src/main/java/ru/otus/spring/mongock/changelog/DatabaseChangelog.java b/2022-02/spring-13/spring-data-mongo-class-work/spring-data-mongo-solution/src/main/java/ru/otus/spring/mongock/changelog/DatabaseChangelog.java new file mode 100644 index 00000000..f9226e50 --- /dev/null +++ b/2022-02/spring-13/spring-data-mongo-class-work/spring-data-mongo-solution/src/main/java/ru/otus/spring/mongock/changelog/DatabaseChangelog.java @@ -0,0 +1,30 @@ +package ru.otus.spring.mongock.changelog; + +import com.github.cloudyrock.mongock.ChangeLog; +import com.github.cloudyrock.mongock.ChangeSet; +import com.mongodb.client.MongoCollection; +import com.mongodb.client.MongoDatabase; +import org.bson.Document; +import ru.otus.spring.domain.Person; +import ru.otus.spring.repostory.PersonRepository; + +@ChangeLog +public class DatabaseChangelog { + + @ChangeSet(order = "001", id = "dropDb", author = "stvort", runAlways = true) + public void dropDb(MongoDatabase db) { + db.drop(); + } + + @ChangeSet(order = "002", id = "insertLermontov", author = "ydvorzhetskiy") + public void insertLermontov(MongoDatabase db) { + MongoCollection myCollection = db.getCollection("persons"); + var doc = new Document().append("name", "Lermontov"); + myCollection.insertOne(doc); + } + + @ChangeSet(order = "003", id = "insertPushkin", author = "stvort") + public void insertPushkin(PersonRepository repository) { + repository.save(new Person("Pushkin")); + } +} diff --git a/2022-02/spring-13/spring-data-mongo-class-work/spring-data-mongo-solution/src/main/java/ru/otus/spring/repostory/PersonRepository.java b/2022-02/spring-13/spring-data-mongo-class-work/spring-data-mongo-solution/src/main/java/ru/otus/spring/repostory/PersonRepository.java new file mode 100644 index 00000000..763a2288 --- /dev/null +++ b/2022-02/spring-13/spring-data-mongo-class-work/spring-data-mongo-solution/src/main/java/ru/otus/spring/repostory/PersonRepository.java @@ -0,0 +1,12 @@ +package ru.otus.spring.repostory; + +import org.springframework.data.repository.CrudRepository; +import ru.otus.spring.domain.Person; + +import java.util.List; + + +public interface PersonRepository extends CrudRepository { + + List findAll(); +} diff --git a/2022-02/spring-13/spring-data-mongo-class-work/spring-data-mongo-solution/src/main/resources/application.yml b/2022-02/spring-13/spring-data-mongo-class-work/spring-data-mongo-solution/src/main/resources/application.yml new file mode 100644 index 00000000..dd00fa36 --- /dev/null +++ b/2022-02/spring-13/spring-data-mongo-class-work/spring-data-mongo-solution/src/main/resources/application.yml @@ -0,0 +1,10 @@ +spring: + data: + mongodb: + database: company + +mongock: + runner-type: "ApplicationRunner" # default + #runner-type: "InitializingBean" + change-logs-scan-package: + - ru.otus.spring.mongock.changelog diff --git a/2022-02/spring-17-mvc/pom.xml b/2022-02/spring-17-mvc/pom.xml new file mode 100644 index 00000000..c9bb3f66 --- /dev/null +++ b/2022-02/spring-17-mvc/pom.xml @@ -0,0 +1,20 @@ + + + 4.0.0 + + ru.otus + spring-mvc-class-work + 1.0 + + pom + + + spring-mvc-exercise + spring-mvc-solution-1 + spring-mvc-solution-2 + spring-mvc-solution-3 + spring-mvc-demo + + diff --git a/2022-02/spring-17-mvc/spring-mvc-demo/pom.xml b/2022-02/spring-17-mvc/spring-mvc-demo/pom.xml new file mode 100644 index 00000000..b5caf61f --- /dev/null +++ b/2022-02/spring-17-mvc/spring-mvc-demo/pom.xml @@ -0,0 +1,52 @@ + + + 4.0.0 + + ru.otus + spring-mvc-demo + 1.0 + + + org.springframework.boot + spring-boot-starter-parent + 2.6.7 + + + + + 11 + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + com.h2database + h2 + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + diff --git a/2022-02/spring-17-mvc/spring-mvc-demo/src/main/java/ru/otus/spring/Main.java b/2022-02/spring-17-mvc/spring-mvc-demo/src/main/java/ru/otus/spring/Main.java new file mode 100644 index 00000000..7d9d2703 --- /dev/null +++ b/2022-02/spring-17-mvc/spring-mvc-demo/src/main/java/ru/otus/spring/Main.java @@ -0,0 +1,27 @@ +package ru.otus.spring; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.data.map.repository.config.EnableMapRepositories; +import ru.otus.spring.domain.Person; +import ru.otus.spring.repostory.PersonRepository; + +import javax.annotation.PostConstruct; + +@SpringBootApplication +public class Main { + + public static void main(String[] args) { + SpringApplication.run(Main.class); + } + + @SuppressWarnings("SpringJavaAutowiredFieldsWarningInspection") + @Autowired + private PersonRepository repository; + + @PostConstruct + public void init() { + repository.save(new Person(1, "Pushkin")); + } +} diff --git a/2022-02/spring-17-mvc/spring-mvc-demo/src/main/java/ru/otus/spring/config/WebConfig.java b/2022-02/spring-17-mvc/spring-mvc-demo/src/main/java/ru/otus/spring/config/WebConfig.java new file mode 100644 index 00000000..e201fdcf --- /dev/null +++ b/2022-02/spring-17-mvc/spring-mvc-demo/src/main/java/ru/otus/spring/config/WebConfig.java @@ -0,0 +1,21 @@ +package ru.otus.spring.config; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.method.support.HandlerMethodArgumentResolver; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; +import ru.otus.spring.rest.resolvers.SystemInfoMethodArgumentResolver; + +import java.util.List; + +@Configuration +public class WebConfig implements WebMvcConfigurer { + + @Autowired + private SystemInfoMethodArgumentResolver systemInfoMethodArgumentResolver; + + @Override + public void addArgumentResolvers(List resolvers) { + resolvers.add(systemInfoMethodArgumentResolver); + } +} diff --git a/2022-02/spring-17-mvc/spring-mvc-demo/src/main/java/ru/otus/spring/domain/Person.java b/2022-02/spring-17-mvc/spring-mvc-demo/src/main/java/ru/otus/spring/domain/Person.java new file mode 100644 index 00000000..3a4c40b3 --- /dev/null +++ b/2022-02/spring-17-mvc/spring-mvc-demo/src/main/java/ru/otus/spring/domain/Person.java @@ -0,0 +1,40 @@ +package ru.otus.spring.domain; + +import javax.persistence.Entity; +import javax.persistence.Id; + +@Entity +public class Person { + + @Id + private long id; + private String name; + + public Person() { + } + + public Person(String name) { + this.name = name; + } + + public Person(long id, String name) { + this.id = id; + this.name = name; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/2022-02/spring-17-mvc/spring-mvc-demo/src/main/java/ru/otus/spring/domain/SystemInfo.java b/2022-02/spring-17-mvc/spring-mvc-demo/src/main/java/ru/otus/spring/domain/SystemInfo.java new file mode 100644 index 00000000..c16a8a78 --- /dev/null +++ b/2022-02/spring-17-mvc/spring-mvc-demo/src/main/java/ru/otus/spring/domain/SystemInfo.java @@ -0,0 +1,31 @@ +package ru.otus.spring.domain; + +public class SystemInfo { + private final String osName; + private final String timeZone; + private final String osArch; + private final int processorsCount; + + public SystemInfo(String osName, String timeZone, String osArch, int processorsCount) { + this.osName = osName; + this.timeZone = timeZone; + this.osArch = osArch; + this.processorsCount = processorsCount; + } + + public String getOsName() { + return osName; + } + + public String getTimeZone() { + return timeZone; + } + + public String getOsArch() { + return osArch; + } + + public int getProcessorsCount() { + return processorsCount; + } +} diff --git a/2022-02/spring-17-mvc/spring-mvc-demo/src/main/java/ru/otus/spring/repostory/PersonRepository.java b/2022-02/spring-17-mvc/spring-mvc-demo/src/main/java/ru/otus/spring/repostory/PersonRepository.java new file mode 100644 index 00000000..dd8a6966 --- /dev/null +++ b/2022-02/spring-17-mvc/spring-mvc-demo/src/main/java/ru/otus/spring/repostory/PersonRepository.java @@ -0,0 +1,11 @@ +package ru.otus.spring.repostory; + +import org.springframework.data.repository.PagingAndSortingRepository; +import ru.otus.spring.domain.Person; + +import java.util.List; + +public interface PersonRepository extends PagingAndSortingRepository { + + List findAll(); +} diff --git a/2022-02/spring-17-mvc/spring-mvc-demo/src/main/java/ru/otus/spring/rest/PersonController.java b/2022-02/spring-17-mvc/spring-mvc-demo/src/main/java/ru/otus/spring/rest/PersonController.java new file mode 100644 index 00000000..ab8603ff --- /dev/null +++ b/2022-02/spring-17-mvc/spring-mvc-demo/src/main/java/ru/otus/spring/rest/PersonController.java @@ -0,0 +1,64 @@ +package ru.otus.spring.rest; + +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; +import ru.otus.spring.domain.Person; +import ru.otus.spring.repostory.PersonRepository; +import ru.otus.spring.rest.dto.PersonDto; +import ru.otus.spring.rest.exceptions.NotFoundException; + +import java.util.List; +import java.util.stream.Collectors; + +@RestController +public class PersonController { + + private final PersonRepository repository; + + public PersonController(PersonRepository repository) { + this.repository = repository; + } + + @RequestMapping(value = "/persons/all", method = RequestMethod.GET) + public List getAllPersons() { + return repository.findAll().stream() + .map(PersonDto::toDto) + .collect(Collectors.toList()); + } + + @RequestMapping(value = "/persons", method = RequestMethod.GET) + public PersonDto getPersonByIdInRequest(@RequestParam("id") long id) { + Person person = repository.findById(id).orElseThrow(NotFoundException::new); + return PersonDto.toDto(person); + } + + @GetMapping("/persons/{id}") + public PersonDto getPersonByIdInPath(@PathVariable("id") long id) { + Person person = repository.findById(id).orElseThrow(NotFoundException::new); + return PersonDto.toDto(person); + } + + @PostMapping("/persons") + public PersonDto createNewPerson(@RequestBody PersonDto dto) { + Person person = PersonDto.toDomainObject(dto); + Person savedPerson = repository.save(person); + return PersonDto.toDto(savedPerson); + } + + @PatchMapping("/persons/{id}/name") + public PersonDto updateNameById(@PathVariable("id") long id, @RequestParam("name") String name) { + Person person = repository.findById(id).orElseThrow(NotFoundException::new); + person.setName(name); + return PersonDto.toDto(repository.save(person)); + } + + @DeleteMapping("/persons/{id}") + public void deleteById(@PathVariable("id") long id) { + repository.deleteById(id); + } + + @ExceptionHandler(NotFoundException.class) + public ResponseEntity handleNotFound(NotFoundException ex) { + return ResponseEntity.badRequest().body("Таких тут нет!"); + } +} diff --git a/2022-02/spring-17-mvc/spring-mvc-demo/src/main/java/ru/otus/spring/rest/SystemInfoController.java b/2022-02/spring-17-mvc/spring-mvc-demo/src/main/java/ru/otus/spring/rest/SystemInfoController.java new file mode 100644 index 00000000..f188a94f --- /dev/null +++ b/2022-02/spring-17-mvc/spring-mvc-demo/src/main/java/ru/otus/spring/rest/SystemInfoController.java @@ -0,0 +1,14 @@ +package ru.otus.spring.rest; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; +import ru.otus.spring.domain.SystemInfo; + +@RestController +public class SystemInfoController { + + @GetMapping("/server/system/info") + public SystemInfo getServerSystemInfo(SystemInfo systemInfo) { + return systemInfo; + } +} diff --git a/2022-02/spring-17-mvc/spring-mvc-demo/src/main/java/ru/otus/spring/rest/dto/PersonDto.java b/2022-02/spring-17-mvc/spring-mvc-demo/src/main/java/ru/otus/spring/rest/dto/PersonDto.java new file mode 100644 index 00000000..a2aeae8f --- /dev/null +++ b/2022-02/spring-17-mvc/spring-mvc-demo/src/main/java/ru/otus/spring/rest/dto/PersonDto.java @@ -0,0 +1,54 @@ +/* + * Copyright 2016 Russian Post + * + * This source code is Russian Post Confidential Proprietary. + * This software is protected by copyright. All rights and titles are reserved. + * You shall not use, copy, distribute, modify, decompile, disassemble or reverse engineer the software. + * Otherwise this violation would be treated by law and would be subject to legal prosecution. + * Legal use of the software provides receipt of a license from the right name only. + */ +package ru.otus.spring.rest.dto; + +import ru.otus.spring.domain.Person; + +/** + * DTO that represents Person + */ +@SuppressWarnings("all") +public class PersonDto { + + private long id; + private String name; + + public PersonDto() { + } + + public PersonDto(long id, String name) { + this.id = id; + this.name = name; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public static Person toDomainObject(PersonDto dto) { + return new Person(dto.getId(), dto.getName()); + } + + public static PersonDto toDto(Person person) { + return new PersonDto(person.getId(), person.getName()); + } +} diff --git a/2022-02/spring-17-mvc/spring-mvc-demo/src/main/java/ru/otus/spring/rest/exceptions/NotFoundException.java b/2022-02/spring-17-mvc/spring-mvc-demo/src/main/java/ru/otus/spring/rest/exceptions/NotFoundException.java new file mode 100644 index 00000000..5dc475b8 --- /dev/null +++ b/2022-02/spring-17-mvc/spring-mvc-demo/src/main/java/ru/otus/spring/rest/exceptions/NotFoundException.java @@ -0,0 +1,7 @@ +package ru.otus.spring.rest.exceptions; + +public class NotFoundException extends RuntimeException{ + + public NotFoundException() { + } +} diff --git a/2022-02/spring-17-mvc/spring-mvc-demo/src/main/java/ru/otus/spring/rest/resolvers/SystemInfoMethodArgumentResolver.java b/2022-02/spring-17-mvc/spring-mvc-demo/src/main/java/ru/otus/spring/rest/resolvers/SystemInfoMethodArgumentResolver.java new file mode 100644 index 00000000..51f517a7 --- /dev/null +++ b/2022-02/spring-17-mvc/spring-mvc-demo/src/main/java/ru/otus/spring/rest/resolvers/SystemInfoMethodArgumentResolver.java @@ -0,0 +1,33 @@ +package ru.otus.spring.rest.resolvers; + +import org.springframework.core.MethodParameter; +import org.springframework.stereotype.Component; +import org.springframework.web.bind.support.WebDataBinderFactory; +import org.springframework.web.context.request.NativeWebRequest; +import org.springframework.web.method.support.HandlerMethodArgumentResolver; +import org.springframework.web.method.support.ModelAndViewContainer; +import ru.otus.spring.domain.SystemInfo; +import ru.otus.spring.service.SystemInfoService; + +@Component +public class SystemInfoMethodArgumentResolver implements HandlerMethodArgumentResolver { + + private final SystemInfoService systemInfoService; + + public SystemInfoMethodArgumentResolver(SystemInfoService systemInfoService) { + this.systemInfoService = systemInfoService; + } + + @Override + public boolean supportsParameter(MethodParameter parameter) { + return parameter.getParameterType().equals(SystemInfo.class); + } + + @Override + public Object resolveArgument(MethodParameter parameter, + ModelAndViewContainer mavContainer, + NativeWebRequest webRequest, + WebDataBinderFactory binderFactory) throws Exception { + return systemInfoService.getSystemInfo(); + } +} diff --git a/2022-02/spring-17-mvc/spring-mvc-demo/src/main/java/ru/otus/spring/service/SystemInfoService.java b/2022-02/spring-17-mvc/spring-mvc-demo/src/main/java/ru/otus/spring/service/SystemInfoService.java new file mode 100644 index 00000000..26fb34d2 --- /dev/null +++ b/2022-02/spring-17-mvc/spring-mvc-demo/src/main/java/ru/otus/spring/service/SystemInfoService.java @@ -0,0 +1,17 @@ +package ru.otus.spring.service; + +import org.springframework.stereotype.Service; +import ru.otus.spring.domain.SystemInfo; + +@Service +public class SystemInfoService { + + public SystemInfo getSystemInfo(){ + String osName = System.getProperty("os.name"); + String timeZone = System.getProperty("user.timezone"); + String osArch = System.getProperty("os.arch"); + int processorsCount = Runtime.getRuntime().availableProcessors(); + return new SystemInfo(osName, timeZone, osArch, processorsCount); + + } +} diff --git a/2022-02/spring-17-mvc/spring-mvc-demo/src/test/java/ru/otus/spring/rest/PersonControllerTest.java b/2022-02/spring-17-mvc/spring-mvc-demo/src/test/java/ru/otus/spring/rest/PersonControllerTest.java new file mode 100644 index 00000000..31186817 --- /dev/null +++ b/2022-02/spring-17-mvc/spring-mvc-demo/src/test/java/ru/otus/spring/rest/PersonControllerTest.java @@ -0,0 +1,127 @@ +package ru.otus.spring.rest; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.test.web.servlet.MockMvc; +import ru.otus.spring.domain.Person; +import ru.otus.spring.repostory.PersonRepository; +import ru.otus.spring.rest.dto.PersonDto; +import ru.otus.spring.service.SystemInfoService; + +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.springframework.http.MediaType.APPLICATION_JSON; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@WebMvcTest(PersonController.class) +class PersonControllerTest { + + public static final String ERROR_STRING = "Таких тут нет!"; + + @Autowired + private MockMvc mvc; + + @Autowired + private ObjectMapper mapper; + + @MockBean + private PersonRepository repository; + + @MockBean + private SystemInfoService systemInfoService; + + @Test + void shouldReturnCorrectPersonsList() throws Exception { + List persons = List.of(new Person(1, "Person1"), new Person(2, "Person2")); + given(repository.findAll()).willReturn(persons); + + List expectedResult = persons.stream() + .map(PersonDto::toDto).collect(Collectors.toList()); + + mvc.perform(get("/persons/all")) + .andExpect(status().isOk()) + .andExpect(content().json(mapper.writeValueAsString(expectedResult))); + } + + @Test + void shouldReturnCorrectPersonByIdInRequest() throws Exception { + Person person = new Person(1, "Person1"); + given(repository.findById(1L)).willReturn(Optional.of(person)); + PersonDto expectedResult = PersonDto.toDto(person); + + mvc.perform(get("/persons").param("id", "1")) + .andExpect(status().isOk()) + .andExpect(content().json(mapper.writeValueAsString(expectedResult))); + } + + @Test + void shouldReturnCorrectPersonByIdInPath() throws Exception { + Person person = new Person(1, "Person1"); + given(repository.findById(1L)).willReturn(Optional.of(person)); + PersonDto expectedResult = PersonDto.toDto(person); + + mvc.perform(get("/persons/1")) + .andExpect(status().isOk()) + .andExpect(content().json(mapper.writeValueAsString(expectedResult))); + } + + @Test + void shouldReturnExpectedErrorWhenPersonNotFound() throws Exception { + given(repository.findById(1L)).willReturn(Optional.empty()); + + mvc.perform(get("/persons").param("id", "1")) + .andExpect(status().isBadRequest()) + .andExpect(content().string(ERROR_STRING)); + + mvc.perform(get("/persons/1")) + .andExpect(status().isBadRequest()) + .andExpect(content().string(ERROR_STRING)); + } + + @Test + void shouldCorrectSaveNewPerson() throws Exception { + Person person = new Person(1, "Person1"); + given(repository.save(any())).willReturn(person); + String expectedResult = mapper.writeValueAsString(PersonDto.toDto(person)); + + mvc.perform(post("/persons").contentType(APPLICATION_JSON) + .content(expectedResult)) + .andExpect(status().isOk()) + .andExpect(content().json(expectedResult)); + } + + @Test + void shouldCorrectUpdatePersonName() throws Exception { + Person person = new Person(1, "Person1"); + given(repository.findById(1L)).willReturn(Optional.of(person)); + given(repository.save(any())).willAnswer(invocation -> invocation.getArgument(0)); + + Person expectedPerson = new Person(1, "Person2"); + String expectedResult = mapper.writeValueAsString(PersonDto.toDto(expectedPerson)); + + mvc.perform(patch("/persons/{id}/name", 1).param("name", expectedPerson.getName()) + .content(expectedResult)) + .andExpect(status().isOk()) + .andExpect(content().json(expectedResult)); + } + + @Test + void shouldCorrectDeletePerson() throws Exception { + mvc.perform(delete("/persons/1")) + .andExpect(status().isOk()); + verify(repository, times(1)).deleteById(1L); + } + + +} \ No newline at end of file diff --git a/2022-02/spring-17-mvc/spring-mvc-demo/src/test/java/ru/otus/spring/rest/SystemInfoControllerTest.java b/2022-02/spring-17-mvc/spring-mvc-demo/src/test/java/ru/otus/spring/rest/SystemInfoControllerTest.java new file mode 100644 index 00000000..21629c26 --- /dev/null +++ b/2022-02/spring-17-mvc/spring-mvc-demo/src/test/java/ru/otus/spring/rest/SystemInfoControllerTest.java @@ -0,0 +1,34 @@ +package ru.otus.spring.rest; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.context.annotation.Import; +import org.springframework.test.web.servlet.MockMvc; +import ru.otus.spring.domain.SystemInfo; +import ru.otus.spring.service.SystemInfoService; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; + +@WebMvcTest(SystemInfoController.class) +@Import(SystemInfoService.class) +class SystemInfoControllerTest { + + @Autowired + private MockMvc mvc; + + @Autowired + private ObjectMapper mapper; + + @Autowired + private SystemInfoService systemInfoService; + + @Test + void shouldReturnCorrectServerSystemInfo() throws Exception { + SystemInfo expectedSystemInfo = systemInfoService.getSystemInfo(); + mvc.perform(get("/server/system/info")) + .andExpect(content().json(mapper.writeValueAsString(expectedSystemInfo))); + } +} \ No newline at end of file diff --git a/2022-02/spring-17-mvc/spring-mvc-exercise/pom.xml b/2022-02/spring-17-mvc/spring-mvc-exercise/pom.xml new file mode 100644 index 00000000..5156a942 --- /dev/null +++ b/2022-02/spring-17-mvc/spring-mvc-exercise/pom.xml @@ -0,0 +1,51 @@ + + + 4.0.0 + + ru.otus + spring-mvc-exercise + 1.0 + + + org.springframework.boot + spring-boot-starter-parent + 2.6.7 + + + + + 11 + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + com.h2database + h2 + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + diff --git a/2022-02/spring-17-mvc/spring-mvc-exercise/src/main/java/ru/otus/spring/Main.java b/2022-02/spring-17-mvc/spring-mvc-exercise/src/main/java/ru/otus/spring/Main.java new file mode 100644 index 00000000..e73a469d --- /dev/null +++ b/2022-02/spring-17-mvc/spring-mvc-exercise/src/main/java/ru/otus/spring/Main.java @@ -0,0 +1,26 @@ +package ru.otus.spring; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import ru.otus.spring.domain.Person; +import ru.otus.spring.repostory.PersonRepository; + +import javax.annotation.PostConstruct; + +@SpringBootApplication +public class Main { + + public static void main(String[] args) { + SpringApplication.run(Main.class); + } + + @SuppressWarnings("SpringJavaAutowiredFieldsWarningInspection") + @Autowired + private PersonRepository repository; + + @PostConstruct + public void init() { + repository.save(new Person(1, "Pushkin")); + } +} diff --git a/2022-02/spring-17-mvc/spring-mvc-exercise/src/main/java/ru/otus/spring/domain/Person.java b/2022-02/spring-17-mvc/spring-mvc-exercise/src/main/java/ru/otus/spring/domain/Person.java new file mode 100644 index 00000000..3a4c40b3 --- /dev/null +++ b/2022-02/spring-17-mvc/spring-mvc-exercise/src/main/java/ru/otus/spring/domain/Person.java @@ -0,0 +1,40 @@ +package ru.otus.spring.domain; + +import javax.persistence.Entity; +import javax.persistence.Id; + +@Entity +public class Person { + + @Id + private long id; + private String name; + + public Person() { + } + + public Person(String name) { + this.name = name; + } + + public Person(long id, String name) { + this.id = id; + this.name = name; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/2022-02/spring-17-mvc/spring-mvc-exercise/src/main/java/ru/otus/spring/repostory/PersonRepository.java b/2022-02/spring-17-mvc/spring-mvc-exercise/src/main/java/ru/otus/spring/repostory/PersonRepository.java new file mode 100644 index 00000000..dd8a6966 --- /dev/null +++ b/2022-02/spring-17-mvc/spring-mvc-exercise/src/main/java/ru/otus/spring/repostory/PersonRepository.java @@ -0,0 +1,11 @@ +package ru.otus.spring.repostory; + +import org.springframework.data.repository.PagingAndSortingRepository; +import ru.otus.spring.domain.Person; + +import java.util.List; + +public interface PersonRepository extends PagingAndSortingRepository { + + List findAll(); +} diff --git a/2022-02/spring-17-mvc/spring-mvc-exercise/src/main/java/ru/otus/spring/rest/PersonController.java b/2022-02/spring-17-mvc/spring-mvc-exercise/src/main/java/ru/otus/spring/rest/PersonController.java new file mode 100644 index 00000000..344a34b7 --- /dev/null +++ b/2022-02/spring-17-mvc/spring-mvc-exercise/src/main/java/ru/otus/spring/rest/PersonController.java @@ -0,0 +1,13 @@ +package ru.otus.spring.rest; + +import ru.otus.spring.repostory.PersonRepository; + + +public class PersonController { + + private final PersonRepository repository; + + public PersonController(PersonRepository repository) { + this.repository = repository; + } +} diff --git a/2022-02/spring-17-mvc/spring-mvc-exercise/src/main/java/ru/otus/spring/rest/dto/PersonDto.java b/2022-02/spring-17-mvc/spring-mvc-exercise/src/main/java/ru/otus/spring/rest/dto/PersonDto.java new file mode 100644 index 00000000..a2aeae8f --- /dev/null +++ b/2022-02/spring-17-mvc/spring-mvc-exercise/src/main/java/ru/otus/spring/rest/dto/PersonDto.java @@ -0,0 +1,54 @@ +/* + * Copyright 2016 Russian Post + * + * This source code is Russian Post Confidential Proprietary. + * This software is protected by copyright. All rights and titles are reserved. + * You shall not use, copy, distribute, modify, decompile, disassemble or reverse engineer the software. + * Otherwise this violation would be treated by law and would be subject to legal prosecution. + * Legal use of the software provides receipt of a license from the right name only. + */ +package ru.otus.spring.rest.dto; + +import ru.otus.spring.domain.Person; + +/** + * DTO that represents Person + */ +@SuppressWarnings("all") +public class PersonDto { + + private long id; + private String name; + + public PersonDto() { + } + + public PersonDto(long id, String name) { + this.id = id; + this.name = name; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public static Person toDomainObject(PersonDto dto) { + return new Person(dto.getId(), dto.getName()); + } + + public static PersonDto toDto(Person person) { + return new PersonDto(person.getId(), person.getName()); + } +} diff --git a/2022-02/spring-17-mvc/spring-mvc-exercise/src/main/java/ru/otus/spring/rest/exeptions/NotFoundException.java b/2022-02/spring-17-mvc/spring-mvc-exercise/src/main/java/ru/otus/spring/rest/exeptions/NotFoundException.java new file mode 100644 index 00000000..169b67b2 --- /dev/null +++ b/2022-02/spring-17-mvc/spring-mvc-exercise/src/main/java/ru/otus/spring/rest/exeptions/NotFoundException.java @@ -0,0 +1,7 @@ +package ru.otus.spring.rest.exeptions; + +public class NotFoundException extends RuntimeException{ + + public NotFoundException() { + } +} diff --git a/2022-02/spring-17-mvc/spring-mvc-exercise/src/test/java/ru/otus/spring/rest/PersonControllerTest.java b/2022-02/spring-17-mvc/spring-mvc-exercise/src/test/java/ru/otus/spring/rest/PersonControllerTest.java new file mode 100644 index 00000000..be82aa76 --- /dev/null +++ b/2022-02/spring-17-mvc/spring-mvc-exercise/src/test/java/ru/otus/spring/rest/PersonControllerTest.java @@ -0,0 +1,85 @@ +package ru.otus.spring.rest; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.test.web.servlet.MockMvc; +import ru.otus.spring.domain.Person; +import ru.otus.spring.repostory.PersonRepository; +import ru.otus.spring.rest.dto.PersonDto; + +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; + +import static org.mockito.BDDMockito.given; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@WebMvcTest(PersonController.class) +class PersonControllerTest { + + public static final String ERROR_STRING = "Таких тут нет!"; + + @Autowired + private MockMvc mvc; + + @Autowired + private ObjectMapper mapper; + + @MockBean + private PersonRepository repository; + + @Test + void shouldReturnCorrectPersonsList() throws Exception { + List persons = List.of(new Person(1, "Person1"), new Person(2, "Person2")); + given(repository.findAll()).willReturn(persons); + + List expectedResult = persons.stream() + .map(PersonDto::toDto).collect(Collectors.toList()); + + mvc.perform(get("/persons/all")) + .andExpect(status().isOk()) + .andExpect(content().json(mapper.writeValueAsString(expectedResult))); + } + + @Test + void shouldReturnCorrectPersonByIdInRequest() throws Exception { + Person person = new Person(1, "Person1"); + given(repository.findById(1L)).willReturn(Optional.of(person)); + PersonDto expectedResult = PersonDto.toDto(person); + + mvc.perform(get("/persons").param("id", "1")) + .andExpect(status().isOk()) + .andExpect(content().json(mapper.writeValueAsString(expectedResult))); + } + + @Test + void shouldReturnCorrectPersonByIdInPath() throws Exception { + Person person = new Person(1, "Person1"); + given(repository.findById(1L)).willReturn(Optional.of(person)); + PersonDto expectedResult = PersonDto.toDto(person); + + mvc.perform(get("/persons/1")) + .andExpect(status().isOk()) + .andExpect(content().json(mapper.writeValueAsString(expectedResult))); + } + + @Test + void shouldReturnExpectedErrorWhenPersonNotFound() throws Exception { + given(repository.findById(1L)).willReturn(Optional.empty()); + + mvc.perform(get("/persons").param("id", "1")) + .andExpect(status().isBadRequest()) + .andExpect(content().string(ERROR_STRING)); + + mvc.perform(get("/persons/1")) + .andExpect(status().isBadRequest()) + .andExpect(content().string(ERROR_STRING)); + } + + +} \ No newline at end of file diff --git a/2022-02/spring-17-mvc/spring-mvc-solution-1/pom.xml b/2022-02/spring-17-mvc/spring-mvc-solution-1/pom.xml new file mode 100644 index 00000000..4c4e2dd4 --- /dev/null +++ b/2022-02/spring-17-mvc/spring-mvc-solution-1/pom.xml @@ -0,0 +1,51 @@ + + + 4.0.0 + + ru.otus + spring-mvc-solution-1 + 1.0 + + + org.springframework.boot + spring-boot-starter-parent + 2.6.7 + + + + + 11 + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + com.h2database + h2 + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + diff --git a/2022-02/spring-17-mvc/spring-mvc-solution-1/src/main/java/ru/otus/spring/Main.java b/2022-02/spring-17-mvc/spring-mvc-solution-1/src/main/java/ru/otus/spring/Main.java new file mode 100644 index 00000000..e73a469d --- /dev/null +++ b/2022-02/spring-17-mvc/spring-mvc-solution-1/src/main/java/ru/otus/spring/Main.java @@ -0,0 +1,26 @@ +package ru.otus.spring; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import ru.otus.spring.domain.Person; +import ru.otus.spring.repostory.PersonRepository; + +import javax.annotation.PostConstruct; + +@SpringBootApplication +public class Main { + + public static void main(String[] args) { + SpringApplication.run(Main.class); + } + + @SuppressWarnings("SpringJavaAutowiredFieldsWarningInspection") + @Autowired + private PersonRepository repository; + + @PostConstruct + public void init() { + repository.save(new Person(1, "Pushkin")); + } +} diff --git a/2022-02/spring-17-mvc/spring-mvc-solution-1/src/main/java/ru/otus/spring/domain/Person.java b/2022-02/spring-17-mvc/spring-mvc-solution-1/src/main/java/ru/otus/spring/domain/Person.java new file mode 100644 index 00000000..3a4c40b3 --- /dev/null +++ b/2022-02/spring-17-mvc/spring-mvc-solution-1/src/main/java/ru/otus/spring/domain/Person.java @@ -0,0 +1,40 @@ +package ru.otus.spring.domain; + +import javax.persistence.Entity; +import javax.persistence.Id; + +@Entity +public class Person { + + @Id + private long id; + private String name; + + public Person() { + } + + public Person(String name) { + this.name = name; + } + + public Person(long id, String name) { + this.id = id; + this.name = name; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/2022-02/spring-17-mvc/spring-mvc-solution-1/src/main/java/ru/otus/spring/repostory/PersonRepository.java b/2022-02/spring-17-mvc/spring-mvc-solution-1/src/main/java/ru/otus/spring/repostory/PersonRepository.java new file mode 100644 index 00000000..dd8a6966 --- /dev/null +++ b/2022-02/spring-17-mvc/spring-mvc-solution-1/src/main/java/ru/otus/spring/repostory/PersonRepository.java @@ -0,0 +1,11 @@ +package ru.otus.spring.repostory; + +import org.springframework.data.repository.PagingAndSortingRepository; +import ru.otus.spring.domain.Person; + +import java.util.List; + +public interface PersonRepository extends PagingAndSortingRepository { + + List findAll(); +} diff --git a/2022-02/spring-17-mvc/spring-mvc-solution-1/src/main/java/ru/otus/spring/rest/PersonController.java b/2022-02/spring-17-mvc/spring-mvc-solution-1/src/main/java/ru/otus/spring/rest/PersonController.java new file mode 100644 index 00000000..1d9b23fb --- /dev/null +++ b/2022-02/spring-17-mvc/spring-mvc-solution-1/src/main/java/ru/otus/spring/rest/PersonController.java @@ -0,0 +1,25 @@ +package ru.otus.spring.rest; + +import org.springframework.web.bind.annotation.*; +import ru.otus.spring.repostory.PersonRepository; +import ru.otus.spring.rest.dto.PersonDto; + +import java.util.List; +import java.util.stream.Collectors; + +@RestController +public class PersonController { + + private final PersonRepository repository; + + public PersonController(PersonRepository repository) { + this.repository = repository; + } + + @RequestMapping(value = "/persons/all", method = RequestMethod.GET) + public List getAllPersons() { + return repository.findAll().stream() + .map(PersonDto::toDto) + .collect(Collectors.toList()); + } +} diff --git a/2022-02/spring-17-mvc/spring-mvc-solution-1/src/main/java/ru/otus/spring/rest/dto/PersonDto.java b/2022-02/spring-17-mvc/spring-mvc-solution-1/src/main/java/ru/otus/spring/rest/dto/PersonDto.java new file mode 100644 index 00000000..a2aeae8f --- /dev/null +++ b/2022-02/spring-17-mvc/spring-mvc-solution-1/src/main/java/ru/otus/spring/rest/dto/PersonDto.java @@ -0,0 +1,54 @@ +/* + * Copyright 2016 Russian Post + * + * This source code is Russian Post Confidential Proprietary. + * This software is protected by copyright. All rights and titles are reserved. + * You shall not use, copy, distribute, modify, decompile, disassemble or reverse engineer the software. + * Otherwise this violation would be treated by law and would be subject to legal prosecution. + * Legal use of the software provides receipt of a license from the right name only. + */ +package ru.otus.spring.rest.dto; + +import ru.otus.spring.domain.Person; + +/** + * DTO that represents Person + */ +@SuppressWarnings("all") +public class PersonDto { + + private long id; + private String name; + + public PersonDto() { + } + + public PersonDto(long id, String name) { + this.id = id; + this.name = name; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public static Person toDomainObject(PersonDto dto) { + return new Person(dto.getId(), dto.getName()); + } + + public static PersonDto toDto(Person person) { + return new PersonDto(person.getId(), person.getName()); + } +} diff --git a/2022-02/spring-17-mvc/spring-mvc-solution-1/src/main/java/ru/otus/spring/rest/exceptions/NotFoundException.java b/2022-02/spring-17-mvc/spring-mvc-solution-1/src/main/java/ru/otus/spring/rest/exceptions/NotFoundException.java new file mode 100644 index 00000000..5dc475b8 --- /dev/null +++ b/2022-02/spring-17-mvc/spring-mvc-solution-1/src/main/java/ru/otus/spring/rest/exceptions/NotFoundException.java @@ -0,0 +1,7 @@ +package ru.otus.spring.rest.exceptions; + +public class NotFoundException extends RuntimeException{ + + public NotFoundException() { + } +} diff --git a/2022-02/spring-17-mvc/spring-mvc-solution-1/src/test/java/ru/otus/spring/rest/PersonControllerTest.java b/2022-02/spring-17-mvc/spring-mvc-solution-1/src/test/java/ru/otus/spring/rest/PersonControllerTest.java new file mode 100644 index 00000000..be82aa76 --- /dev/null +++ b/2022-02/spring-17-mvc/spring-mvc-solution-1/src/test/java/ru/otus/spring/rest/PersonControllerTest.java @@ -0,0 +1,85 @@ +package ru.otus.spring.rest; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.test.web.servlet.MockMvc; +import ru.otus.spring.domain.Person; +import ru.otus.spring.repostory.PersonRepository; +import ru.otus.spring.rest.dto.PersonDto; + +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; + +import static org.mockito.BDDMockito.given; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@WebMvcTest(PersonController.class) +class PersonControllerTest { + + public static final String ERROR_STRING = "Таких тут нет!"; + + @Autowired + private MockMvc mvc; + + @Autowired + private ObjectMapper mapper; + + @MockBean + private PersonRepository repository; + + @Test + void shouldReturnCorrectPersonsList() throws Exception { + List persons = List.of(new Person(1, "Person1"), new Person(2, "Person2")); + given(repository.findAll()).willReturn(persons); + + List expectedResult = persons.stream() + .map(PersonDto::toDto).collect(Collectors.toList()); + + mvc.perform(get("/persons/all")) + .andExpect(status().isOk()) + .andExpect(content().json(mapper.writeValueAsString(expectedResult))); + } + + @Test + void shouldReturnCorrectPersonByIdInRequest() throws Exception { + Person person = new Person(1, "Person1"); + given(repository.findById(1L)).willReturn(Optional.of(person)); + PersonDto expectedResult = PersonDto.toDto(person); + + mvc.perform(get("/persons").param("id", "1")) + .andExpect(status().isOk()) + .andExpect(content().json(mapper.writeValueAsString(expectedResult))); + } + + @Test + void shouldReturnCorrectPersonByIdInPath() throws Exception { + Person person = new Person(1, "Person1"); + given(repository.findById(1L)).willReturn(Optional.of(person)); + PersonDto expectedResult = PersonDto.toDto(person); + + mvc.perform(get("/persons/1")) + .andExpect(status().isOk()) + .andExpect(content().json(mapper.writeValueAsString(expectedResult))); + } + + @Test + void shouldReturnExpectedErrorWhenPersonNotFound() throws Exception { + given(repository.findById(1L)).willReturn(Optional.empty()); + + mvc.perform(get("/persons").param("id", "1")) + .andExpect(status().isBadRequest()) + .andExpect(content().string(ERROR_STRING)); + + mvc.perform(get("/persons/1")) + .andExpect(status().isBadRequest()) + .andExpect(content().string(ERROR_STRING)); + } + + +} \ No newline at end of file diff --git a/2022-02/spring-17-mvc/spring-mvc-solution-2/pom.xml b/2022-02/spring-17-mvc/spring-mvc-solution-2/pom.xml new file mode 100644 index 00000000..8c12d0f5 --- /dev/null +++ b/2022-02/spring-17-mvc/spring-mvc-solution-2/pom.xml @@ -0,0 +1,52 @@ + + + 4.0.0 + + ru.otus + spring-mvc-solution-2 + 1.0 + + + org.springframework.boot + spring-boot-starter-parent + 2.6.7 + + + + + 11 + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + com.h2database + h2 + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + diff --git a/2022-02/spring-17-mvc/spring-mvc-solution-2/src/main/java/ru/otus/spring/Main.java b/2022-02/spring-17-mvc/spring-mvc-solution-2/src/main/java/ru/otus/spring/Main.java new file mode 100644 index 00000000..e73a469d --- /dev/null +++ b/2022-02/spring-17-mvc/spring-mvc-solution-2/src/main/java/ru/otus/spring/Main.java @@ -0,0 +1,26 @@ +package ru.otus.spring; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import ru.otus.spring.domain.Person; +import ru.otus.spring.repostory.PersonRepository; + +import javax.annotation.PostConstruct; + +@SpringBootApplication +public class Main { + + public static void main(String[] args) { + SpringApplication.run(Main.class); + } + + @SuppressWarnings("SpringJavaAutowiredFieldsWarningInspection") + @Autowired + private PersonRepository repository; + + @PostConstruct + public void init() { + repository.save(new Person(1, "Pushkin")); + } +} diff --git a/2022-02/spring-17-mvc/spring-mvc-solution-2/src/main/java/ru/otus/spring/domain/Person.java b/2022-02/spring-17-mvc/spring-mvc-solution-2/src/main/java/ru/otus/spring/domain/Person.java new file mode 100644 index 00000000..3a4c40b3 --- /dev/null +++ b/2022-02/spring-17-mvc/spring-mvc-solution-2/src/main/java/ru/otus/spring/domain/Person.java @@ -0,0 +1,40 @@ +package ru.otus.spring.domain; + +import javax.persistence.Entity; +import javax.persistence.Id; + +@Entity +public class Person { + + @Id + private long id; + private String name; + + public Person() { + } + + public Person(String name) { + this.name = name; + } + + public Person(long id, String name) { + this.id = id; + this.name = name; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/2022-02/spring-17-mvc/spring-mvc-solution-2/src/main/java/ru/otus/spring/repostory/PersonRepository.java b/2022-02/spring-17-mvc/spring-mvc-solution-2/src/main/java/ru/otus/spring/repostory/PersonRepository.java new file mode 100644 index 00000000..dd8a6966 --- /dev/null +++ b/2022-02/spring-17-mvc/spring-mvc-solution-2/src/main/java/ru/otus/spring/repostory/PersonRepository.java @@ -0,0 +1,11 @@ +package ru.otus.spring.repostory; + +import org.springframework.data.repository.PagingAndSortingRepository; +import ru.otus.spring.domain.Person; + +import java.util.List; + +public interface PersonRepository extends PagingAndSortingRepository { + + List findAll(); +} diff --git a/2022-02/spring-17-mvc/spring-mvc-solution-2/src/main/java/ru/otus/spring/rest/PersonController.java b/2022-02/spring-17-mvc/spring-mvc-solution-2/src/main/java/ru/otus/spring/rest/PersonController.java new file mode 100644 index 00000000..ee46a75d --- /dev/null +++ b/2022-02/spring-17-mvc/spring-mvc-solution-2/src/main/java/ru/otus/spring/rest/PersonController.java @@ -0,0 +1,40 @@ +package ru.otus.spring.rest; + +import org.springframework.web.bind.annotation.*; +import ru.otus.spring.domain.Person; +import ru.otus.spring.repostory.PersonRepository; +import ru.otus.spring.rest.dto.PersonDto; +import ru.otus.spring.rest.exceptions.NotFoundException; + +import java.util.List; +import java.util.stream.Collectors; + +@RestController +public class PersonController { + + private final PersonRepository repository; + + public PersonController(PersonRepository repository) { + this.repository = repository; + } + + @RequestMapping(value = "/persons/all", method = RequestMethod.GET, params = {}) + public List getAllPersons() { + return repository.findAll().stream() + .map(PersonDto::toDto) + .collect(Collectors.toList()); + } + + @RequestMapping(value = "/persons", method = RequestMethod.GET) + public PersonDto getPersonByIdInRequest(@RequestParam("id") long id) { + Person person = repository.findById(id).orElseThrow(NotFoundException::new); + return PersonDto.toDto(person); + } + + @GetMapping("/persons/{id}") + public PersonDto getPersonByIdInPath(@PathVariable("id") long id) { + Person person = repository.findById(id).orElseThrow(NotFoundException::new); + return PersonDto.toDto(person); + } + +} diff --git a/2022-02/spring-17-mvc/spring-mvc-solution-2/src/main/java/ru/otus/spring/rest/dto/PersonDto.java b/2022-02/spring-17-mvc/spring-mvc-solution-2/src/main/java/ru/otus/spring/rest/dto/PersonDto.java new file mode 100644 index 00000000..a2aeae8f --- /dev/null +++ b/2022-02/spring-17-mvc/spring-mvc-solution-2/src/main/java/ru/otus/spring/rest/dto/PersonDto.java @@ -0,0 +1,54 @@ +/* + * Copyright 2016 Russian Post + * + * This source code is Russian Post Confidential Proprietary. + * This software is protected by copyright. All rights and titles are reserved. + * You shall not use, copy, distribute, modify, decompile, disassemble or reverse engineer the software. + * Otherwise this violation would be treated by law and would be subject to legal prosecution. + * Legal use of the software provides receipt of a license from the right name only. + */ +package ru.otus.spring.rest.dto; + +import ru.otus.spring.domain.Person; + +/** + * DTO that represents Person + */ +@SuppressWarnings("all") +public class PersonDto { + + private long id; + private String name; + + public PersonDto() { + } + + public PersonDto(long id, String name) { + this.id = id; + this.name = name; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public static Person toDomainObject(PersonDto dto) { + return new Person(dto.getId(), dto.getName()); + } + + public static PersonDto toDto(Person person) { + return new PersonDto(person.getId(), person.getName()); + } +} diff --git a/2022-02/spring-17-mvc/spring-mvc-solution-2/src/main/java/ru/otus/spring/rest/exceptions/NotFoundException.java b/2022-02/spring-17-mvc/spring-mvc-solution-2/src/main/java/ru/otus/spring/rest/exceptions/NotFoundException.java new file mode 100644 index 00000000..5dc475b8 --- /dev/null +++ b/2022-02/spring-17-mvc/spring-mvc-solution-2/src/main/java/ru/otus/spring/rest/exceptions/NotFoundException.java @@ -0,0 +1,7 @@ +package ru.otus.spring.rest.exceptions; + +public class NotFoundException extends RuntimeException{ + + public NotFoundException() { + } +} diff --git a/2022-02/spring-17-mvc/spring-mvc-solution-2/src/test/java/ru/otus/spring/rest/PersonControllerTest.java b/2022-02/spring-17-mvc/spring-mvc-solution-2/src/test/java/ru/otus/spring/rest/PersonControllerTest.java new file mode 100644 index 00000000..be82aa76 --- /dev/null +++ b/2022-02/spring-17-mvc/spring-mvc-solution-2/src/test/java/ru/otus/spring/rest/PersonControllerTest.java @@ -0,0 +1,85 @@ +package ru.otus.spring.rest; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.test.web.servlet.MockMvc; +import ru.otus.spring.domain.Person; +import ru.otus.spring.repostory.PersonRepository; +import ru.otus.spring.rest.dto.PersonDto; + +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; + +import static org.mockito.BDDMockito.given; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@WebMvcTest(PersonController.class) +class PersonControllerTest { + + public static final String ERROR_STRING = "Таких тут нет!"; + + @Autowired + private MockMvc mvc; + + @Autowired + private ObjectMapper mapper; + + @MockBean + private PersonRepository repository; + + @Test + void shouldReturnCorrectPersonsList() throws Exception { + List persons = List.of(new Person(1, "Person1"), new Person(2, "Person2")); + given(repository.findAll()).willReturn(persons); + + List expectedResult = persons.stream() + .map(PersonDto::toDto).collect(Collectors.toList()); + + mvc.perform(get("/persons/all")) + .andExpect(status().isOk()) + .andExpect(content().json(mapper.writeValueAsString(expectedResult))); + } + + @Test + void shouldReturnCorrectPersonByIdInRequest() throws Exception { + Person person = new Person(1, "Person1"); + given(repository.findById(1L)).willReturn(Optional.of(person)); + PersonDto expectedResult = PersonDto.toDto(person); + + mvc.perform(get("/persons").param("id", "1")) + .andExpect(status().isOk()) + .andExpect(content().json(mapper.writeValueAsString(expectedResult))); + } + + @Test + void shouldReturnCorrectPersonByIdInPath() throws Exception { + Person person = new Person(1, "Person1"); + given(repository.findById(1L)).willReturn(Optional.of(person)); + PersonDto expectedResult = PersonDto.toDto(person); + + mvc.perform(get("/persons/1")) + .andExpect(status().isOk()) + .andExpect(content().json(mapper.writeValueAsString(expectedResult))); + } + + @Test + void shouldReturnExpectedErrorWhenPersonNotFound() throws Exception { + given(repository.findById(1L)).willReturn(Optional.empty()); + + mvc.perform(get("/persons").param("id", "1")) + .andExpect(status().isBadRequest()) + .andExpect(content().string(ERROR_STRING)); + + mvc.perform(get("/persons/1")) + .andExpect(status().isBadRequest()) + .andExpect(content().string(ERROR_STRING)); + } + + +} \ No newline at end of file diff --git a/2022-02/spring-17-mvc/spring-mvc-solution-3/pom.xml b/2022-02/spring-17-mvc/spring-mvc-solution-3/pom.xml new file mode 100644 index 00000000..7ba73a68 --- /dev/null +++ b/2022-02/spring-17-mvc/spring-mvc-solution-3/pom.xml @@ -0,0 +1,52 @@ + + + 4.0.0 + + ru.otus + spring-mvc-solution-3 + 1.0 + + + org.springframework.boot + spring-boot-starter-parent + 2.6.7 + + + + + 11 + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + com.h2database + h2 + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + diff --git a/2022-02/spring-17-mvc/spring-mvc-solution-3/requests.http b/2022-02/spring-17-mvc/spring-mvc-solution-3/requests.http new file mode 100644 index 00000000..958a57b2 --- /dev/null +++ b/2022-02/spring-17-mvc/spring-mvc-solution-3/requests.http @@ -0,0 +1,10 @@ +POST http://localhost:8080/person +Content-Type: application/json + +{ + "id": "2", + "name": "Pushkin" +} + +### +GET http://localhost:8080/persons/all \ No newline at end of file diff --git a/2022-02/spring-17-mvc/spring-mvc-solution-3/src/main/java/ru/otus/spring/Main.java b/2022-02/spring-17-mvc/spring-mvc-solution-3/src/main/java/ru/otus/spring/Main.java new file mode 100644 index 00000000..e73a469d --- /dev/null +++ b/2022-02/spring-17-mvc/spring-mvc-solution-3/src/main/java/ru/otus/spring/Main.java @@ -0,0 +1,26 @@ +package ru.otus.spring; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import ru.otus.spring.domain.Person; +import ru.otus.spring.repostory.PersonRepository; + +import javax.annotation.PostConstruct; + +@SpringBootApplication +public class Main { + + public static void main(String[] args) { + SpringApplication.run(Main.class); + } + + @SuppressWarnings("SpringJavaAutowiredFieldsWarningInspection") + @Autowired + private PersonRepository repository; + + @PostConstruct + public void init() { + repository.save(new Person(1, "Pushkin")); + } +} diff --git a/2022-02/spring-17-mvc/spring-mvc-solution-3/src/main/java/ru/otus/spring/domain/Person.java b/2022-02/spring-17-mvc/spring-mvc-solution-3/src/main/java/ru/otus/spring/domain/Person.java new file mode 100644 index 00000000..3a4c40b3 --- /dev/null +++ b/2022-02/spring-17-mvc/spring-mvc-solution-3/src/main/java/ru/otus/spring/domain/Person.java @@ -0,0 +1,40 @@ +package ru.otus.spring.domain; + +import javax.persistence.Entity; +import javax.persistence.Id; + +@Entity +public class Person { + + @Id + private long id; + private String name; + + public Person() { + } + + public Person(String name) { + this.name = name; + } + + public Person(long id, String name) { + this.id = id; + this.name = name; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/2022-02/spring-17-mvc/spring-mvc-solution-3/src/main/java/ru/otus/spring/repostory/PersonRepository.java b/2022-02/spring-17-mvc/spring-mvc-solution-3/src/main/java/ru/otus/spring/repostory/PersonRepository.java new file mode 100644 index 00000000..dd8a6966 --- /dev/null +++ b/2022-02/spring-17-mvc/spring-mvc-solution-3/src/main/java/ru/otus/spring/repostory/PersonRepository.java @@ -0,0 +1,11 @@ +package ru.otus.spring.repostory; + +import org.springframework.data.repository.PagingAndSortingRepository; +import ru.otus.spring.domain.Person; + +import java.util.List; + +public interface PersonRepository extends PagingAndSortingRepository { + + List findAll(); +} diff --git a/2022-02/spring-17-mvc/spring-mvc-solution-3/src/main/java/ru/otus/spring/rest/PersonController.java b/2022-02/spring-17-mvc/spring-mvc-solution-3/src/main/java/ru/otus/spring/rest/PersonController.java new file mode 100644 index 00000000..b24c91ca --- /dev/null +++ b/2022-02/spring-17-mvc/spring-mvc-solution-3/src/main/java/ru/otus/spring/rest/PersonController.java @@ -0,0 +1,45 @@ +package ru.otus.spring.rest; + +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; +import ru.otus.spring.domain.Person; +import ru.otus.spring.repostory.PersonRepository; +import ru.otus.spring.rest.dto.PersonDto; +import ru.otus.spring.rest.exceptions.NotFoundException; + +import java.util.List; +import java.util.stream.Collectors; + +@RestController +public class PersonController { + + private final PersonRepository repository; + + public PersonController(PersonRepository repository) { + this.repository = repository; + } + + @RequestMapping(value = "/persons/all", method = RequestMethod.GET, params = {}) + public List getAllPersons() { + return repository.findAll().stream() + .map(PersonDto::toDto) + .collect(Collectors.toList()); + } + + @RequestMapping(value = "/persons", method = RequestMethod.GET) + public PersonDto getPersonByIdInRequest(@RequestParam("id") long id) { + Person person = repository.findById(id).orElseThrow(NotFoundException::new); + return PersonDto.toDto(person); + } + + @GetMapping("/persons/{id}") + public PersonDto getPersonByIdInPath(@PathVariable("id") long id) { + Person person = repository.findById(id).orElseThrow(NotFoundException::new); + return PersonDto.toDto(person); + } + + @ExceptionHandler(NotFoundException.class) + public ResponseEntity handleNotFound(NotFoundException ex) { + return ResponseEntity.badRequest().body("Таких тут нет!"); + } +} diff --git a/2022-02/spring-17-mvc/spring-mvc-solution-3/src/main/java/ru/otus/spring/rest/dto/PersonDto.java b/2022-02/spring-17-mvc/spring-mvc-solution-3/src/main/java/ru/otus/spring/rest/dto/PersonDto.java new file mode 100644 index 00000000..a2aeae8f --- /dev/null +++ b/2022-02/spring-17-mvc/spring-mvc-solution-3/src/main/java/ru/otus/spring/rest/dto/PersonDto.java @@ -0,0 +1,54 @@ +/* + * Copyright 2016 Russian Post + * + * This source code is Russian Post Confidential Proprietary. + * This software is protected by copyright. All rights and titles are reserved. + * You shall not use, copy, distribute, modify, decompile, disassemble or reverse engineer the software. + * Otherwise this violation would be treated by law and would be subject to legal prosecution. + * Legal use of the software provides receipt of a license from the right name only. + */ +package ru.otus.spring.rest.dto; + +import ru.otus.spring.domain.Person; + +/** + * DTO that represents Person + */ +@SuppressWarnings("all") +public class PersonDto { + + private long id; + private String name; + + public PersonDto() { + } + + public PersonDto(long id, String name) { + this.id = id; + this.name = name; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public static Person toDomainObject(PersonDto dto) { + return new Person(dto.getId(), dto.getName()); + } + + public static PersonDto toDto(Person person) { + return new PersonDto(person.getId(), person.getName()); + } +} diff --git a/2022-02/spring-17-mvc/spring-mvc-solution-3/src/main/java/ru/otus/spring/rest/exceptions/NotFoundException.java b/2022-02/spring-17-mvc/spring-mvc-solution-3/src/main/java/ru/otus/spring/rest/exceptions/NotFoundException.java new file mode 100644 index 00000000..5dc475b8 --- /dev/null +++ b/2022-02/spring-17-mvc/spring-mvc-solution-3/src/main/java/ru/otus/spring/rest/exceptions/NotFoundException.java @@ -0,0 +1,7 @@ +package ru.otus.spring.rest.exceptions; + +public class NotFoundException extends RuntimeException{ + + public NotFoundException() { + } +} diff --git a/2022-02/spring-17-mvc/spring-mvc-solution-3/src/test/java/ru/otus/spring/rest/PersonControllerTest.java b/2022-02/spring-17-mvc/spring-mvc-solution-3/src/test/java/ru/otus/spring/rest/PersonControllerTest.java new file mode 100644 index 00000000..be82aa76 --- /dev/null +++ b/2022-02/spring-17-mvc/spring-mvc-solution-3/src/test/java/ru/otus/spring/rest/PersonControllerTest.java @@ -0,0 +1,85 @@ +package ru.otus.spring.rest; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.test.web.servlet.MockMvc; +import ru.otus.spring.domain.Person; +import ru.otus.spring.repostory.PersonRepository; +import ru.otus.spring.rest.dto.PersonDto; + +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; + +import static org.mockito.BDDMockito.given; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@WebMvcTest(PersonController.class) +class PersonControllerTest { + + public static final String ERROR_STRING = "Таких тут нет!"; + + @Autowired + private MockMvc mvc; + + @Autowired + private ObjectMapper mapper; + + @MockBean + private PersonRepository repository; + + @Test + void shouldReturnCorrectPersonsList() throws Exception { + List persons = List.of(new Person(1, "Person1"), new Person(2, "Person2")); + given(repository.findAll()).willReturn(persons); + + List expectedResult = persons.stream() + .map(PersonDto::toDto).collect(Collectors.toList()); + + mvc.perform(get("/persons/all")) + .andExpect(status().isOk()) + .andExpect(content().json(mapper.writeValueAsString(expectedResult))); + } + + @Test + void shouldReturnCorrectPersonByIdInRequest() throws Exception { + Person person = new Person(1, "Person1"); + given(repository.findById(1L)).willReturn(Optional.of(person)); + PersonDto expectedResult = PersonDto.toDto(person); + + mvc.perform(get("/persons").param("id", "1")) + .andExpect(status().isOk()) + .andExpect(content().json(mapper.writeValueAsString(expectedResult))); + } + + @Test + void shouldReturnCorrectPersonByIdInPath() throws Exception { + Person person = new Person(1, "Person1"); + given(repository.findById(1L)).willReturn(Optional.of(person)); + PersonDto expectedResult = PersonDto.toDto(person); + + mvc.perform(get("/persons/1")) + .andExpect(status().isOk()) + .andExpect(content().json(mapper.writeValueAsString(expectedResult))); + } + + @Test + void shouldReturnExpectedErrorWhenPersonNotFound() throws Exception { + given(repository.findById(1L)).willReturn(Optional.empty()); + + mvc.perform(get("/persons").param("id", "1")) + .andExpect(status().isBadRequest()) + .andExpect(content().string(ERROR_STRING)); + + mvc.perform(get("/persons/1")) + .andExpect(status().isBadRequest()) + .andExpect(content().string(ERROR_STRING)); + } + + +} \ No newline at end of file diff --git a/2022-02/spring-18-view/.gitignore b/2022-02/spring-18-view/.gitignore new file mode 100644 index 00000000..4ea52072 --- /dev/null +++ b/2022-02/spring-18-view/.gitignore @@ -0,0 +1,24 @@ +target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/build/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ diff --git a/2022-02/spring-18-view/pom.xml b/2022-02/spring-18-view/pom.xml new file mode 100644 index 00000000..f2ad9bdf --- /dev/null +++ b/2022-02/spring-18-view/pom.xml @@ -0,0 +1,21 @@ + + + 4.0.0 + + ru.otus + spring-mvc-view + 1.0 + + pom + + + spring-mvc-view-exercise + spring-mvc-view-demo + spring-mvc-view-solution1 + spring-mvc-view-solution2 + spring-mvc-view-solution3 + spring-mvc-view-solution4 + + diff --git a/2022-02/spring-18-view/spring-mvc-view-demo/.gitignore b/2022-02/spring-18-view/spring-mvc-view-demo/.gitignore new file mode 100644 index 00000000..4ea52072 --- /dev/null +++ b/2022-02/spring-18-view/spring-mvc-view-demo/.gitignore @@ -0,0 +1,24 @@ +target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/build/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ diff --git a/2022-02/spring-18-view/spring-mvc-view-demo/pom.xml b/2022-02/spring-18-view/spring-mvc-view-demo/pom.xml new file mode 100644 index 00000000..8c4b9db0 --- /dev/null +++ b/2022-02/spring-18-view/spring-mvc-view-demo/pom.xml @@ -0,0 +1,69 @@ + + + 4.0.0 + + ru.otus + spring-mvc-view-demo + 1.0 + + + org.springframework.boot + spring-boot-starter-parent + 2.6.3 + + + + + 11 + 11 + 7.0.2.Final + + + + + org.springframework.boot + spring-boot-starter + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-thymeleaf + + + + com.h2database + h2 + + + + org.springframework.data + spring-data-jpa + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + org.springframework.boot + spring-boot-starter-validation + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + diff --git a/2022-02/spring-18-view/spring-mvc-view-demo/src/main/java/ru/otus/spring/Main.java b/2022-02/spring-18-view/spring-mvc-view-demo/src/main/java/ru/otus/spring/Main.java new file mode 100644 index 00000000..d33c8908 --- /dev/null +++ b/2022-02/spring-18-view/spring-mvc-view-demo/src/main/java/ru/otus/spring/Main.java @@ -0,0 +1,27 @@ +package ru.otus.spring; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import ru.otus.spring.domain.Person; +import ru.otus.spring.repostory.PersonRepository; + +import javax.annotation.PostConstruct; + +@SpringBootApplication +public class Main { + + public static void main(String[] args) { + SpringApplication.run(Main.class); + } + + @SuppressWarnings("SpringJavaAutowiredFieldsWarningInspection") + @Autowired + private PersonRepository repository; + + @PostConstruct + public void init() { + repository.save(new Person("Pushkin")); + repository.save(new Person("Lermontov")); + } +} diff --git a/2022-02/spring-18-view/spring-mvc-view-demo/src/main/java/ru/otus/spring/config/LocalizationConfig.java b/2022-02/spring-18-view/spring-mvc-view-demo/src/main/java/ru/otus/spring/config/LocalizationConfig.java new file mode 100644 index 00000000..55871937 --- /dev/null +++ b/2022-02/spring-18-view/spring-mvc-view-demo/src/main/java/ru/otus/spring/config/LocalizationConfig.java @@ -0,0 +1,35 @@ +package ru.otus.spring.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.LocaleResolver; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; +import org.springframework.web.servlet.i18n.CookieLocaleResolver; +import org.springframework.web.servlet.i18n.LocaleChangeInterceptor; + +import java.util.Locale; + +@Configuration +public class LocalizationConfig implements WebMvcConfigurer { + + @Bean(name = "localeResolver") + public LocaleResolver localeResolver() { + var resolver = new CookieLocaleResolver(); + resolver.setDefaultLocale(new Locale("en")); + resolver.setCookieName("locale"); + return resolver; + } + + @Bean + public LocaleChangeInterceptor localeChangeInterceptor() { + var localeChangeInterceptor = new LocaleChangeInterceptor(); + localeChangeInterceptor.setParamName("lang"); + return localeChangeInterceptor; + } + + @Override + public void addInterceptors(InterceptorRegistry registry) { + registry.addInterceptor(localeChangeInterceptor()); + } +} diff --git a/2022-02/spring-18-view/spring-mvc-view-demo/src/main/java/ru/otus/spring/controller/NotFoundException.java b/2022-02/spring-18-view/spring-mvc-view-demo/src/main/java/ru/otus/spring/controller/NotFoundException.java new file mode 100644 index 00000000..41b48826 --- /dev/null +++ b/2022-02/spring-18-view/spring-mvc-view-demo/src/main/java/ru/otus/spring/controller/NotFoundException.java @@ -0,0 +1,7 @@ +package ru.otus.spring.controller; + +class NotFoundException extends RuntimeException{ + + NotFoundException() { + } +} diff --git a/2022-02/spring-18-view/spring-mvc-view-demo/src/main/java/ru/otus/spring/controller/PersonController.java b/2022-02/spring-18-view/spring-mvc-view-demo/src/main/java/ru/otus/spring/controller/PersonController.java new file mode 100644 index 00000000..44d500af --- /dev/null +++ b/2022-02/spring-18-view/spring-mvc-view-demo/src/main/java/ru/otus/spring/controller/PersonController.java @@ -0,0 +1,50 @@ +package ru.otus.spring.controller; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.validation.BindingResult; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; +import ru.otus.spring.domain.Person; +import ru.otus.spring.dto.PersonDto; +import ru.otus.spring.repostory.PersonRepository; + +import javax.validation.Valid; +import java.util.List; + +@Controller +public class PersonController { + + private final PersonRepository repository; + + @Autowired + public PersonController(PersonRepository repository) { + this.repository = repository; + } + + @GetMapping("/") + public String listPage(Model model) { + List persons = repository.findAll(); + model.addAttribute("persons", persons); + return "list"; + } + + @GetMapping("/edit") + public String editPage(@RequestParam("id") int id, Model model) { + Person person = repository.findById(id).orElseThrow(NotFoundException::new); + model.addAttribute("person", person); + return "edit"; + } + + @Validated + @PostMapping("/edit") + public String savePerson(@Valid @ModelAttribute("person") PersonDto person, + BindingResult bindingResult, Model model) { + if (bindingResult.hasErrors()) { + return "edit"; + } + repository.save(person.toDomainObject()); + return "redirect:/"; + } +} diff --git a/2022-02/spring-18-view/spring-mvc-view-demo/src/main/java/ru/otus/spring/domain/Person.java b/2022-02/spring-18-view/spring-mvc-view-demo/src/main/java/ru/otus/spring/domain/Person.java new file mode 100644 index 00000000..a20f0032 --- /dev/null +++ b/2022-02/spring-18-view/spring-mvc-view-demo/src/main/java/ru/otus/spring/domain/Person.java @@ -0,0 +1,42 @@ +package ru.otus.spring.domain; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; + +@Entity +public class Person { + + @Id + @GeneratedValue + private int id; + private String name; + + public Person() { + } + + public Person(String name) { + this.name = name; + } + + public Person(int id, String name) { + this.id = id; + this.name = name; + } + + 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; + } +} diff --git a/2022-02/spring-18-view/spring-mvc-view-demo/src/main/java/ru/otus/spring/dto/PersonDto.java b/2022-02/spring-18-view/spring-mvc-view-demo/src/main/java/ru/otus/spring/dto/PersonDto.java new file mode 100644 index 00000000..743d91cc --- /dev/null +++ b/2022-02/spring-18-view/spring-mvc-view-demo/src/main/java/ru/otus/spring/dto/PersonDto.java @@ -0,0 +1,51 @@ +package ru.otus.spring.dto; + +import ru.otus.spring.domain.Person; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Size; + +public class PersonDto { + + private int id; + + @NotBlank(message = "{name-field-should-not-be-blank}") + @Size(min = 2, max = 10, message = "{name-field-should-has-expected-size}") + private String name; + + public PersonDto() { + } + + public PersonDto(String name) { + this.name = name; + } + + public PersonDto(int id, String name) { + this.id = id; + this.name = name; + } + + 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 Person toDomainObject(){ + return new Person(id, name); + } + + public static PersonDto fromDomainObject(Person person) { + return new PersonDto(person.getId(), person.getName()); + } +} diff --git a/2022-02/spring-18-view/spring-mvc-view-demo/src/main/java/ru/otus/spring/repostory/PersonRepository.java b/2022-02/spring-18-view/spring-mvc-view-demo/src/main/java/ru/otus/spring/repostory/PersonRepository.java new file mode 100644 index 00000000..4b20e5b7 --- /dev/null +++ b/2022-02/spring-18-view/spring-mvc-view-demo/src/main/java/ru/otus/spring/repostory/PersonRepository.java @@ -0,0 +1,11 @@ +package ru.otus.spring.repostory; + +import org.springframework.data.repository.CrudRepository; +import ru.otus.spring.domain.Person; + +import java.util.List; + +public interface PersonRepository extends CrudRepository { + + List findAll(); +} diff --git a/2022-02/spring-18-view/spring-mvc-view-demo/src/main/resources/application.yml b/2022-02/spring-18-view/spring-mvc-view-demo/src/main/resources/application.yml new file mode 100644 index 00000000..407f9445 --- /dev/null +++ b/2022-02/spring-18-view/spring-mvc-view-demo/src/main/resources/application.yml @@ -0,0 +1,3 @@ +spring: + messages: + encoding: UTF-8 \ No newline at end of file diff --git a/2022-02/spring-18-view/spring-mvc-view-demo/src/main/resources/messages.properties b/2022-02/spring-18-view/spring-mvc-view-demo/src/main/resources/messages.properties new file mode 100644 index 00000000..216bf5a6 --- /dev/null +++ b/2022-02/spring-18-view/spring-mvc-view-demo/src/main/resources/messages.properties @@ -0,0 +1,10 @@ +lang-switcher-header=Select language +en-lang-switch-button-caption=Language - EN +ru-lang-switch-button-caption=Language - RU +persons-table-header=Persons: +edit-button-caption=Edit +person-form-header=Person Info: +save-button-caption=Save +cancel-button-caption=Cancel +name-field-should-not-be-blank=Name field should not be blank +name-field-should-has-expected-size=Name field should be between 2 and 10 characters \ No newline at end of file diff --git a/2022-02/spring-18-view/spring-mvc-view-demo/src/main/resources/messages_en.properties b/2022-02/spring-18-view/spring-mvc-view-demo/src/main/resources/messages_en.properties new file mode 100644 index 00000000..216bf5a6 --- /dev/null +++ b/2022-02/spring-18-view/spring-mvc-view-demo/src/main/resources/messages_en.properties @@ -0,0 +1,10 @@ +lang-switcher-header=Select language +en-lang-switch-button-caption=Language - EN +ru-lang-switch-button-caption=Language - RU +persons-table-header=Persons: +edit-button-caption=Edit +person-form-header=Person Info: +save-button-caption=Save +cancel-button-caption=Cancel +name-field-should-not-be-blank=Name field should not be blank +name-field-should-has-expected-size=Name field should be between 2 and 10 characters \ No newline at end of file diff --git a/2022-02/spring-18-view/spring-mvc-view-demo/src/main/resources/messages_ru.properties b/2022-02/spring-18-view/spring-mvc-view-demo/src/main/resources/messages_ru.properties new file mode 100644 index 00000000..00e66529 --- /dev/null +++ b/2022-02/spring-18-view/spring-mvc-view-demo/src/main/resources/messages_ru.properties @@ -0,0 +1,10 @@ +lang-switcher-header=Выбор языка +en-lang-switch-button-caption=Язык - EN +ru-lang-switch-button-caption=Язык - RU +persons-table-header=Пёрсоны: +edit-button-caption=Изменить +person-form-header=Информация о пёрсоне: +save-button-caption=Сохранить +cancel-button-caption=Отмена +name-field-should-not-be-blank=Имя не должно быть пустым +name-field-should-has-expected-size=Длина имени должна быть от 2 до 10 символов \ No newline at end of file diff --git a/2022-02/spring-18-view/spring-mvc-view-demo/src/main/resources/static/listmark.png b/2022-02/spring-18-view/spring-mvc-view-demo/src/main/resources/static/listmark.png new file mode 100644 index 00000000..f8eb391b Binary files /dev/null and b/2022-02/spring-18-view/spring-mvc-view-demo/src/main/resources/static/listmark.png differ diff --git a/2022-02/spring-18-view/spring-mvc-view-demo/src/main/resources/templates/edit.html b/2022-02/spring-18-view/spring-mvc-view-demo/src/main/resources/templates/edit.html new file mode 100644 index 00000000..3eb2f065 --- /dev/null +++ b/2022-02/spring-18-view/spring-mvc-view-demo/src/main/resources/templates/edit.html @@ -0,0 +1,69 @@ + + + + + Edit person + + + + + + + +
+

Person Info:

+ +
+ + +
+ +
+ + +
Wrong person name error
+
+ +
+ + +
+
+ + + diff --git a/2022-02/spring-18-view/spring-mvc-view-demo/src/main/resources/templates/list.html b/2022-02/spring-18-view/spring-mvc-view-demo/src/main/resources/templates/list.html new file mode 100644 index 00000000..f345f6b7 --- /dev/null +++ b/2022-02/spring-18-view/spring-mvc-view-demo/src/main/resources/templates/list.html @@ -0,0 +1,74 @@ + + + + + List of all persons + + + + + + +

Select language

+ + +

Persons:

+ + + + + + + + + + + + + + + + +
IDNameAction
1John Doe + Edit +
+ + diff --git a/2022-02/spring-18-view/spring-mvc-view-exercise/.gitignore b/2022-02/spring-18-view/spring-mvc-view-exercise/.gitignore new file mode 100644 index 00000000..4ea52072 --- /dev/null +++ b/2022-02/spring-18-view/spring-mvc-view-exercise/.gitignore @@ -0,0 +1,24 @@ +target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/build/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ diff --git a/2022-02/spring-18-view/spring-mvc-view-exercise/pom.xml b/2022-02/spring-18-view/spring-mvc-view-exercise/pom.xml new file mode 100644 index 00000000..2b922735 --- /dev/null +++ b/2022-02/spring-18-view/spring-mvc-view-exercise/pom.xml @@ -0,0 +1,62 @@ + + + 4.0.0 + + ru.otus + spring-mvc-view-exercise + 1.0 + + + org.springframework.boot + spring-boot-starter-parent + 2.6.3 + + + + + 11 + 11 + + + + + org.springframework.boot + spring-boot-starter + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-thymeleaf + + + + com.h2database + h2 + + + + org.springframework.data + spring-data-jpa + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + diff --git a/2022-02/spring-18-view/spring-mvc-view-exercise/src/main/java/ru/otus/spring/Main.java b/2022-02/spring-18-view/spring-mvc-view-exercise/src/main/java/ru/otus/spring/Main.java new file mode 100644 index 00000000..395af78d --- /dev/null +++ b/2022-02/spring-18-view/spring-mvc-view-exercise/src/main/java/ru/otus/spring/Main.java @@ -0,0 +1,28 @@ +package ru.otus.spring; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import ru.otus.spring.domain.Person; +import ru.otus.spring.repostory.PersonRepository; + +import javax.annotation.PostConstruct; + +@SpringBootApplication +public class Main { + + public static void main(String[] args) { + SpringApplication.run(Main.class); + } + + //Чтобы не усложнять пример, делать так нельзя :) + @SuppressWarnings("SpringJavaAutowiredFieldsWarningInspection") + @Autowired + private PersonRepository repository; + + @PostConstruct + public void init() { + repository.save(new Person("Pushkin")); + repository.save(new Person("Lermontov")); + } +} diff --git a/2022-02/spring-18-view/spring-mvc-view-exercise/src/main/java/ru/otus/spring/controller/NotFoundException.java b/2022-02/spring-18-view/spring-mvc-view-exercise/src/main/java/ru/otus/spring/controller/NotFoundException.java new file mode 100644 index 00000000..41b48826 --- /dev/null +++ b/2022-02/spring-18-view/spring-mvc-view-exercise/src/main/java/ru/otus/spring/controller/NotFoundException.java @@ -0,0 +1,7 @@ +package ru.otus.spring.controller; + +class NotFoundException extends RuntimeException{ + + NotFoundException() { + } +} diff --git a/2022-02/spring-18-view/spring-mvc-view-exercise/src/main/java/ru/otus/spring/controller/PersonController.java b/2022-02/spring-18-view/spring-mvc-view-exercise/src/main/java/ru/otus/spring/controller/PersonController.java new file mode 100644 index 00000000..248dc4ed --- /dev/null +++ b/2022-02/spring-18-view/spring-mvc-view-exercise/src/main/java/ru/otus/spring/controller/PersonController.java @@ -0,0 +1,33 @@ +package ru.otus.spring.controller; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.*; +import ru.otus.spring.domain.Person; +import ru.otus.spring.repostory.PersonRepository; + +import java.util.List; + +@Controller +public class PersonController { + + private final PersonRepository repository; + + @Autowired + public PersonController(PersonRepository repository) { + this.repository = repository; + } + + @GetMapping("/") + public String listPage(Model model) { + List persons = repository.findAll(); + model.addAttribute("persons", persons); + return "list"; + } + + @GetMapping("/edit") + public String editPage(@RequestParam("id") int id, Model model) { + return null; + } +} diff --git a/2022-02/spring-18-view/spring-mvc-view-exercise/src/main/java/ru/otus/spring/domain/Person.java b/2022-02/spring-18-view/spring-mvc-view-exercise/src/main/java/ru/otus/spring/domain/Person.java new file mode 100644 index 00000000..374c55ac --- /dev/null +++ b/2022-02/spring-18-view/spring-mvc-view-exercise/src/main/java/ru/otus/spring/domain/Person.java @@ -0,0 +1,37 @@ +package ru.otus.spring.domain; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; + +@Entity +public class Person { + + @Id + @GeneratedValue + private int id; + private String name; + + public Person() { + } + + public Person(String name) { + this.name = name; + } + + 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; + } +} diff --git a/2022-02/spring-18-view/spring-mvc-view-exercise/src/main/java/ru/otus/spring/repostory/PersonRepository.java b/2022-02/spring-18-view/spring-mvc-view-exercise/src/main/java/ru/otus/spring/repostory/PersonRepository.java new file mode 100644 index 00000000..4b20e5b7 --- /dev/null +++ b/2022-02/spring-18-view/spring-mvc-view-exercise/src/main/java/ru/otus/spring/repostory/PersonRepository.java @@ -0,0 +1,11 @@ +package ru.otus.spring.repostory; + +import org.springframework.data.repository.CrudRepository; +import ru.otus.spring.domain.Person; + +import java.util.List; + +public interface PersonRepository extends CrudRepository { + + List findAll(); +} diff --git a/2022-02/spring-18-view/spring-mvc-view-exercise/src/main/resources/templates/edit.html b/2022-02/spring-18-view/spring-mvc-view-exercise/src/main/resources/templates/edit.html new file mode 100644 index 00000000..87d8c8f1 --- /dev/null +++ b/2022-02/spring-18-view/spring-mvc-view-exercise/src/main/resources/templates/edit.html @@ -0,0 +1,49 @@ + + + + + Edit person + + + + + + +
+

Person Info:

+ +
+ + +
+ +
+ + +
+ +
+ + +
+
+ + + diff --git a/2022-02/spring-18-view/spring-mvc-view-exercise/src/main/resources/templates/list.html b/2022-02/spring-18-view/spring-mvc-view-exercise/src/main/resources/templates/list.html new file mode 100644 index 00000000..a5b52a8d --- /dev/null +++ b/2022-02/spring-18-view/spring-mvc-view-exercise/src/main/resources/templates/list.html @@ -0,0 +1,49 @@ + + + + + List of all persons + + + +

Persons:

+ + + + + + + + + + + + + + + + +
IDNameAction
1John Doe + Edit +
+ + diff --git a/2022-02/spring-18-view/spring-mvc-view-solution1/.gitignore b/2022-02/spring-18-view/spring-mvc-view-solution1/.gitignore new file mode 100644 index 00000000..4ea52072 --- /dev/null +++ b/2022-02/spring-18-view/spring-mvc-view-solution1/.gitignore @@ -0,0 +1,24 @@ +target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/build/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ diff --git a/2022-02/spring-18-view/spring-mvc-view-solution1/pom.xml b/2022-02/spring-18-view/spring-mvc-view-solution1/pom.xml new file mode 100644 index 00000000..94cb0b54 --- /dev/null +++ b/2022-02/spring-18-view/spring-mvc-view-solution1/pom.xml @@ -0,0 +1,62 @@ + + + 4.0.0 + + ru.otus + spring-mvc-view-solution1 + 1.0 + + + org.springframework.boot + spring-boot-starter-parent + 2.6.3 + + + + + 11 + 11 + + + + + org.springframework.boot + spring-boot-starter + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-thymeleaf + + + + com.h2database + h2 + + + + org.springframework.data + spring-data-jpa + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + diff --git a/2022-02/spring-18-view/spring-mvc-view-solution1/src/main/java/ru/otus/spring/Main.java b/2022-02/spring-18-view/spring-mvc-view-solution1/src/main/java/ru/otus/spring/Main.java new file mode 100644 index 00000000..c41d5ecf --- /dev/null +++ b/2022-02/spring-18-view/spring-mvc-view-solution1/src/main/java/ru/otus/spring/Main.java @@ -0,0 +1,29 @@ +package ru.otus.spring; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import ru.otus.spring.domain.Person; +import ru.otus.spring.repostory.PersonRepository; + +import javax.annotation.PostConstruct; + +//http://localhost:8080/edit?id=1 +@SpringBootApplication +public class Main { + + public static void main(String[] args) { + SpringApplication.run(Main.class); + } + + //Чтобы не усложнять пример, делать так нельзя :) + @SuppressWarnings("SpringJavaAutowiredFieldsWarningInspection") + @Autowired + private PersonRepository repository; + + @PostConstruct + public void init() { + repository.save(new Person("Pushkin")); + repository.save(new Person("Lermontov")); + } +} diff --git a/2022-02/spring-18-view/spring-mvc-view-solution1/src/main/java/ru/otus/spring/controller/NotFoundException.java b/2022-02/spring-18-view/spring-mvc-view-solution1/src/main/java/ru/otus/spring/controller/NotFoundException.java new file mode 100644 index 00000000..41b48826 --- /dev/null +++ b/2022-02/spring-18-view/spring-mvc-view-solution1/src/main/java/ru/otus/spring/controller/NotFoundException.java @@ -0,0 +1,7 @@ +package ru.otus.spring.controller; + +class NotFoundException extends RuntimeException{ + + NotFoundException() { + } +} diff --git a/2022-02/spring-18-view/spring-mvc-view-solution1/src/main/java/ru/otus/spring/controller/PersonController.java b/2022-02/spring-18-view/spring-mvc-view-solution1/src/main/java/ru/otus/spring/controller/PersonController.java new file mode 100644 index 00000000..51c7edf8 --- /dev/null +++ b/2022-02/spring-18-view/spring-mvc-view-solution1/src/main/java/ru/otus/spring/controller/PersonController.java @@ -0,0 +1,35 @@ +package ru.otus.spring.controller; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.*; +import ru.otus.spring.domain.Person; +import ru.otus.spring.repostory.PersonRepository; + +import java.util.List; + +@Controller +public class PersonController { + + private final PersonRepository repository; + + @Autowired + public PersonController(PersonRepository repository) { + this.repository = repository; + } + + @GetMapping("/") + public String listPage(Model model) { + List persons = repository.findAll(); + model.addAttribute("persons", persons); + return "list"; + } + + @GetMapping("/edit") + public String editPage(@RequestParam("id") int id, Model model) { + Person person = repository.findById(id).orElseThrow(NotFoundException::new); + model.addAttribute("person", person); + return "edit"; + } +} diff --git a/2022-02/spring-18-view/spring-mvc-view-solution1/src/main/java/ru/otus/spring/domain/Person.java b/2022-02/spring-18-view/spring-mvc-view-solution1/src/main/java/ru/otus/spring/domain/Person.java new file mode 100644 index 00000000..374c55ac --- /dev/null +++ b/2022-02/spring-18-view/spring-mvc-view-solution1/src/main/java/ru/otus/spring/domain/Person.java @@ -0,0 +1,37 @@ +package ru.otus.spring.domain; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; + +@Entity +public class Person { + + @Id + @GeneratedValue + private int id; + private String name; + + public Person() { + } + + public Person(String name) { + this.name = name; + } + + 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; + } +} diff --git a/2022-02/spring-18-view/spring-mvc-view-solution1/src/main/java/ru/otus/spring/repostory/PersonRepository.java b/2022-02/spring-18-view/spring-mvc-view-solution1/src/main/java/ru/otus/spring/repostory/PersonRepository.java new file mode 100644 index 00000000..4b20e5b7 --- /dev/null +++ b/2022-02/spring-18-view/spring-mvc-view-solution1/src/main/java/ru/otus/spring/repostory/PersonRepository.java @@ -0,0 +1,11 @@ +package ru.otus.spring.repostory; + +import org.springframework.data.repository.CrudRepository; +import ru.otus.spring.domain.Person; + +import java.util.List; + +public interface PersonRepository extends CrudRepository { + + List findAll(); +} diff --git a/2022-02/spring-18-view/spring-mvc-view-solution1/src/main/resources/templates/edit.html b/2022-02/spring-18-view/spring-mvc-view-solution1/src/main/resources/templates/edit.html new file mode 100644 index 00000000..7b3f5d6a --- /dev/null +++ b/2022-02/spring-18-view/spring-mvc-view-solution1/src/main/resources/templates/edit.html @@ -0,0 +1,48 @@ + + + + + Edit person + + + + + +
+

Person Info:

+ +
+ + +
+ +
+ + +
+ +
+ + +
+
+ + + diff --git a/2022-02/spring-18-view/spring-mvc-view-solution1/src/main/resources/templates/list.html b/2022-02/spring-18-view/spring-mvc-view-solution1/src/main/resources/templates/list.html new file mode 100644 index 00000000..0d59a759 --- /dev/null +++ b/2022-02/spring-18-view/spring-mvc-view-solution1/src/main/resources/templates/list.html @@ -0,0 +1,50 @@ + + + + + List of all persons + + + + +

Persons:

+ + + + + + + + + + + + + + + + +
IDNameAction
1John Doe + Edit +
+ + diff --git a/2022-02/spring-18-view/spring-mvc-view-solution2/.gitignore b/2022-02/spring-18-view/spring-mvc-view-solution2/.gitignore new file mode 100644 index 00000000..4ea52072 --- /dev/null +++ b/2022-02/spring-18-view/spring-mvc-view-solution2/.gitignore @@ -0,0 +1,24 @@ +target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/build/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ diff --git a/2022-02/spring-18-view/spring-mvc-view-solution2/pom.xml b/2022-02/spring-18-view/spring-mvc-view-solution2/pom.xml new file mode 100644 index 00000000..f88c66cd --- /dev/null +++ b/2022-02/spring-18-view/spring-mvc-view-solution2/pom.xml @@ -0,0 +1,62 @@ + + + 4.0.0 + + ru.otus + spring-mvc-view-solution2 + 1.0 + + + org.springframework.boot + spring-boot-starter-parent + 2.6.3 + + + + + 11 + 11 + + + + + org.springframework.boot + spring-boot-starter + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-thymeleaf + + + + com.h2database + h2 + + + + org.springframework.data + spring-data-jpa + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + diff --git a/2022-02/spring-18-view/spring-mvc-view-solution2/src/main/java/ru/otus/spring/Main.java b/2022-02/spring-18-view/spring-mvc-view-solution2/src/main/java/ru/otus/spring/Main.java new file mode 100644 index 00000000..c41d5ecf --- /dev/null +++ b/2022-02/spring-18-view/spring-mvc-view-solution2/src/main/java/ru/otus/spring/Main.java @@ -0,0 +1,29 @@ +package ru.otus.spring; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import ru.otus.spring.domain.Person; +import ru.otus.spring.repostory.PersonRepository; + +import javax.annotation.PostConstruct; + +//http://localhost:8080/edit?id=1 +@SpringBootApplication +public class Main { + + public static void main(String[] args) { + SpringApplication.run(Main.class); + } + + //Чтобы не усложнять пример, делать так нельзя :) + @SuppressWarnings("SpringJavaAutowiredFieldsWarningInspection") + @Autowired + private PersonRepository repository; + + @PostConstruct + public void init() { + repository.save(new Person("Pushkin")); + repository.save(new Person("Lermontov")); + } +} diff --git a/2022-02/spring-18-view/spring-mvc-view-solution2/src/main/java/ru/otus/spring/controller/NotFoundException.java b/2022-02/spring-18-view/spring-mvc-view-solution2/src/main/java/ru/otus/spring/controller/NotFoundException.java new file mode 100644 index 00000000..41b48826 --- /dev/null +++ b/2022-02/spring-18-view/spring-mvc-view-solution2/src/main/java/ru/otus/spring/controller/NotFoundException.java @@ -0,0 +1,7 @@ +package ru.otus.spring.controller; + +class NotFoundException extends RuntimeException{ + + NotFoundException() { + } +} diff --git a/2022-02/spring-18-view/spring-mvc-view-solution2/src/main/java/ru/otus/spring/controller/PersonController.java b/2022-02/spring-18-view/spring-mvc-view-solution2/src/main/java/ru/otus/spring/controller/PersonController.java new file mode 100644 index 00000000..51c7edf8 --- /dev/null +++ b/2022-02/spring-18-view/spring-mvc-view-solution2/src/main/java/ru/otus/spring/controller/PersonController.java @@ -0,0 +1,35 @@ +package ru.otus.spring.controller; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.*; +import ru.otus.spring.domain.Person; +import ru.otus.spring.repostory.PersonRepository; + +import java.util.List; + +@Controller +public class PersonController { + + private final PersonRepository repository; + + @Autowired + public PersonController(PersonRepository repository) { + this.repository = repository; + } + + @GetMapping("/") + public String listPage(Model model) { + List persons = repository.findAll(); + model.addAttribute("persons", persons); + return "list"; + } + + @GetMapping("/edit") + public String editPage(@RequestParam("id") int id, Model model) { + Person person = repository.findById(id).orElseThrow(NotFoundException::new); + model.addAttribute("person", person); + return "edit"; + } +} diff --git a/2022-02/spring-18-view/spring-mvc-view-solution2/src/main/java/ru/otus/spring/domain/Person.java b/2022-02/spring-18-view/spring-mvc-view-solution2/src/main/java/ru/otus/spring/domain/Person.java new file mode 100644 index 00000000..374c55ac --- /dev/null +++ b/2022-02/spring-18-view/spring-mvc-view-solution2/src/main/java/ru/otus/spring/domain/Person.java @@ -0,0 +1,37 @@ +package ru.otus.spring.domain; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; + +@Entity +public class Person { + + @Id + @GeneratedValue + private int id; + private String name; + + public Person() { + } + + public Person(String name) { + this.name = name; + } + + 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; + } +} diff --git a/2022-02/spring-18-view/spring-mvc-view-solution2/src/main/java/ru/otus/spring/repostory/PersonRepository.java b/2022-02/spring-18-view/spring-mvc-view-solution2/src/main/java/ru/otus/spring/repostory/PersonRepository.java new file mode 100644 index 00000000..4b20e5b7 --- /dev/null +++ b/2022-02/spring-18-view/spring-mvc-view-solution2/src/main/java/ru/otus/spring/repostory/PersonRepository.java @@ -0,0 +1,11 @@ +package ru.otus.spring.repostory; + +import org.springframework.data.repository.CrudRepository; +import ru.otus.spring.domain.Person; + +import java.util.List; + +public interface PersonRepository extends CrudRepository { + + List findAll(); +} diff --git a/2022-02/spring-18-view/spring-mvc-view-solution2/src/main/resources/templates/edit.html b/2022-02/spring-18-view/spring-mvc-view-solution2/src/main/resources/templates/edit.html new file mode 100644 index 00000000..ef643cff --- /dev/null +++ b/2022-02/spring-18-view/spring-mvc-view-solution2/src/main/resources/templates/edit.html @@ -0,0 +1,48 @@ + + + + + Edit person + + + + + +
+

Person Info:

+ +
+ + +
+ +
+ + +
+ +
+ + +
+
+ + + diff --git a/2022-02/spring-18-view/spring-mvc-view-solution2/src/main/resources/templates/list.html b/2022-02/spring-18-view/spring-mvc-view-solution2/src/main/resources/templates/list.html new file mode 100644 index 00000000..a5b52a8d --- /dev/null +++ b/2022-02/spring-18-view/spring-mvc-view-solution2/src/main/resources/templates/list.html @@ -0,0 +1,49 @@ + + + + + List of all persons + + + +

Persons:

+ + + + + + + + + + + + + + + + +
IDNameAction
1John Doe + Edit +
+ + diff --git a/2022-02/spring-18-view/spring-mvc-view-solution3/.gitignore b/2022-02/spring-18-view/spring-mvc-view-solution3/.gitignore new file mode 100644 index 00000000..4ea52072 --- /dev/null +++ b/2022-02/spring-18-view/spring-mvc-view-solution3/.gitignore @@ -0,0 +1,24 @@ +target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/build/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ diff --git a/2022-02/spring-18-view/spring-mvc-view-solution3/pom.xml b/2022-02/spring-18-view/spring-mvc-view-solution3/pom.xml new file mode 100644 index 00000000..d3ad8d2a --- /dev/null +++ b/2022-02/spring-18-view/spring-mvc-view-solution3/pom.xml @@ -0,0 +1,62 @@ + + + 4.0.0 + + ru.otus + spring-mvc-view-solution3 + 1.0 + + + org.springframework.boot + spring-boot-starter-parent + 2.6.3 + + + + + 11 + 11 + + + + + org.springframework.boot + spring-boot-starter + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-thymeleaf + + + + com.h2database + h2 + + + + org.springframework.data + spring-data-jpa + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + diff --git a/2022-02/spring-18-view/spring-mvc-view-solution3/src/main/java/ru/otus/spring/Main.java b/2022-02/spring-18-view/spring-mvc-view-solution3/src/main/java/ru/otus/spring/Main.java new file mode 100644 index 00000000..aa67bfa1 --- /dev/null +++ b/2022-02/spring-18-view/spring-mvc-view-solution3/src/main/java/ru/otus/spring/Main.java @@ -0,0 +1,30 @@ +package ru.otus.spring; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import ru.otus.spring.domain.Person; +import ru.otus.spring.repostory.PersonRepository; + +import javax.annotation.PostConstruct; + +//http://localhost:8080 +//http://localhost:8080/edit?id=1 +@SpringBootApplication +public class Main { + + public static void main(String[] args) { + SpringApplication.run(Main.class); + } + + //Чтобы не усложнять пример, делать так нельзя :) + @SuppressWarnings("SpringJavaAutowiredFieldsWarningInspection") + @Autowired + private PersonRepository repository; + + @PostConstruct + public void init() { + repository.save(new Person("Pushkin")); + repository.save(new Person("Lermontov")); + } +} diff --git a/2022-02/spring-18-view/spring-mvc-view-solution3/src/main/java/ru/otus/spring/controller/NotFoundException.java b/2022-02/spring-18-view/spring-mvc-view-solution3/src/main/java/ru/otus/spring/controller/NotFoundException.java new file mode 100644 index 00000000..41b48826 --- /dev/null +++ b/2022-02/spring-18-view/spring-mvc-view-solution3/src/main/java/ru/otus/spring/controller/NotFoundException.java @@ -0,0 +1,7 @@ +package ru.otus.spring.controller; + +class NotFoundException extends RuntimeException{ + + NotFoundException() { + } +} diff --git a/2022-02/spring-18-view/spring-mvc-view-solution3/src/main/java/ru/otus/spring/controller/PersonController.java b/2022-02/spring-18-view/spring-mvc-view-solution3/src/main/java/ru/otus/spring/controller/PersonController.java new file mode 100644 index 00000000..51c7edf8 --- /dev/null +++ b/2022-02/spring-18-view/spring-mvc-view-solution3/src/main/java/ru/otus/spring/controller/PersonController.java @@ -0,0 +1,35 @@ +package ru.otus.spring.controller; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.*; +import ru.otus.spring.domain.Person; +import ru.otus.spring.repostory.PersonRepository; + +import java.util.List; + +@Controller +public class PersonController { + + private final PersonRepository repository; + + @Autowired + public PersonController(PersonRepository repository) { + this.repository = repository; + } + + @GetMapping("/") + public String listPage(Model model) { + List persons = repository.findAll(); + model.addAttribute("persons", persons); + return "list"; + } + + @GetMapping("/edit") + public String editPage(@RequestParam("id") int id, Model model) { + Person person = repository.findById(id).orElseThrow(NotFoundException::new); + model.addAttribute("person", person); + return "edit"; + } +} diff --git a/2022-02/spring-18-view/spring-mvc-view-solution3/src/main/java/ru/otus/spring/domain/Person.java b/2022-02/spring-18-view/spring-mvc-view-solution3/src/main/java/ru/otus/spring/domain/Person.java new file mode 100644 index 00000000..374c55ac --- /dev/null +++ b/2022-02/spring-18-view/spring-mvc-view-solution3/src/main/java/ru/otus/spring/domain/Person.java @@ -0,0 +1,37 @@ +package ru.otus.spring.domain; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; + +@Entity +public class Person { + + @Id + @GeneratedValue + private int id; + private String name; + + public Person() { + } + + public Person(String name) { + this.name = name; + } + + 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; + } +} diff --git a/2022-02/spring-18-view/spring-mvc-view-solution3/src/main/java/ru/otus/spring/repostory/PersonRepository.java b/2022-02/spring-18-view/spring-mvc-view-solution3/src/main/java/ru/otus/spring/repostory/PersonRepository.java new file mode 100644 index 00000000..4b20e5b7 --- /dev/null +++ b/2022-02/spring-18-view/spring-mvc-view-solution3/src/main/java/ru/otus/spring/repostory/PersonRepository.java @@ -0,0 +1,11 @@ +package ru.otus.spring.repostory; + +import org.springframework.data.repository.CrudRepository; +import ru.otus.spring.domain.Person; + +import java.util.List; + +public interface PersonRepository extends CrudRepository { + + List findAll(); +} diff --git a/2022-02/spring-18-view/spring-mvc-view-solution3/src/main/resources/static/listmark.png b/2022-02/spring-18-view/spring-mvc-view-solution3/src/main/resources/static/listmark.png new file mode 100644 index 00000000..f8eb391b Binary files /dev/null and b/2022-02/spring-18-view/spring-mvc-view-solution3/src/main/resources/static/listmark.png differ diff --git a/2022-02/spring-18-view/spring-mvc-view-solution3/src/main/resources/templates/edit.html b/2022-02/spring-18-view/spring-mvc-view-solution3/src/main/resources/templates/edit.html new file mode 100644 index 00000000..ef643cff --- /dev/null +++ b/2022-02/spring-18-view/spring-mvc-view-solution3/src/main/resources/templates/edit.html @@ -0,0 +1,48 @@ + + + + + Edit person + + + + + +
+

Person Info:

+ +
+ + +
+ +
+ + +
+ +
+ + +
+
+ + + diff --git a/2022-02/spring-18-view/spring-mvc-view-solution3/src/main/resources/templates/list.html b/2022-02/spring-18-view/spring-mvc-view-solution3/src/main/resources/templates/list.html new file mode 100644 index 00000000..19fec79d --- /dev/null +++ b/2022-02/spring-18-view/spring-mvc-view-solution3/src/main/resources/templates/list.html @@ -0,0 +1,49 @@ + + + + + List of all persons + + + +

Persons:

+ + + + + + + + + + + + + + + + +
IDNameAction
1John Doe + Edit +
+ + diff --git a/2022-02/spring-18-view/spring-mvc-view-solution4/.gitignore b/2022-02/spring-18-view/spring-mvc-view-solution4/.gitignore new file mode 100644 index 00000000..4ea52072 --- /dev/null +++ b/2022-02/spring-18-view/spring-mvc-view-solution4/.gitignore @@ -0,0 +1,24 @@ +target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/build/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ diff --git a/2022-02/spring-18-view/spring-mvc-view-solution4/pom.xml b/2022-02/spring-18-view/spring-mvc-view-solution4/pom.xml new file mode 100644 index 00000000..d89ba256 --- /dev/null +++ b/2022-02/spring-18-view/spring-mvc-view-solution4/pom.xml @@ -0,0 +1,62 @@ + + + 4.0.0 + + ru.otus + spring-mvc-view-solution4 + 1.0 + + + org.springframework.boot + spring-boot-starter-parent + 2.6.3 + + + + + 11 + 11 + + + + + org.springframework.boot + spring-boot-starter + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-thymeleaf + + + + com.h2database + h2 + + + + org.springframework.data + spring-data-jpa + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + diff --git a/2022-02/spring-18-view/spring-mvc-view-solution4/src/main/java/ru/otus/spring/Main.java b/2022-02/spring-18-view/spring-mvc-view-solution4/src/main/java/ru/otus/spring/Main.java new file mode 100644 index 00000000..aa67bfa1 --- /dev/null +++ b/2022-02/spring-18-view/spring-mvc-view-solution4/src/main/java/ru/otus/spring/Main.java @@ -0,0 +1,30 @@ +package ru.otus.spring; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import ru.otus.spring.domain.Person; +import ru.otus.spring.repostory.PersonRepository; + +import javax.annotation.PostConstruct; + +//http://localhost:8080 +//http://localhost:8080/edit?id=1 +@SpringBootApplication +public class Main { + + public static void main(String[] args) { + SpringApplication.run(Main.class); + } + + //Чтобы не усложнять пример, делать так нельзя :) + @SuppressWarnings("SpringJavaAutowiredFieldsWarningInspection") + @Autowired + private PersonRepository repository; + + @PostConstruct + public void init() { + repository.save(new Person("Pushkin")); + repository.save(new Person("Lermontov")); + } +} diff --git a/2022-02/spring-18-view/spring-mvc-view-solution4/src/main/java/ru/otus/spring/controller/NotFoundException.java b/2022-02/spring-18-view/spring-mvc-view-solution4/src/main/java/ru/otus/spring/controller/NotFoundException.java new file mode 100644 index 00000000..41b48826 --- /dev/null +++ b/2022-02/spring-18-view/spring-mvc-view-solution4/src/main/java/ru/otus/spring/controller/NotFoundException.java @@ -0,0 +1,7 @@ +package ru.otus.spring.controller; + +class NotFoundException extends RuntimeException{ + + NotFoundException() { + } +} diff --git a/2022-02/spring-18-view/spring-mvc-view-solution4/src/main/java/ru/otus/spring/controller/PersonController.java b/2022-02/spring-18-view/spring-mvc-view-solution4/src/main/java/ru/otus/spring/controller/PersonController.java new file mode 100644 index 00000000..f1a367f9 --- /dev/null +++ b/2022-02/spring-18-view/spring-mvc-view-solution4/src/main/java/ru/otus/spring/controller/PersonController.java @@ -0,0 +1,41 @@ +package ru.otus.spring.controller; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.*; +import ru.otus.spring.domain.Person; +import ru.otus.spring.repostory.PersonRepository; + +import java.util.List; + +@Controller +public class PersonController { + + private final PersonRepository repository; + + @Autowired + public PersonController(PersonRepository repository) { + this.repository = repository; + } + + @GetMapping("/") + public String listPage(Model model) { + List persons = repository.findAll(); + model.addAttribute("persons", persons); + return "list"; + } + + @GetMapping("/edit") + public String editPage(@RequestParam("id") int id, Model model) { + Person person = repository.findById(id).orElseThrow(NotFoundException::new); + model.addAttribute("person", person); + return "edit"; + } + + @PostMapping("/edit") + public String savePerson(Person person) { + repository.save(person); + return "redirect:/"; + } +} diff --git a/2022-02/spring-18-view/spring-mvc-view-solution4/src/main/java/ru/otus/spring/domain/Person.java b/2022-02/spring-18-view/spring-mvc-view-solution4/src/main/java/ru/otus/spring/domain/Person.java new file mode 100644 index 00000000..374c55ac --- /dev/null +++ b/2022-02/spring-18-view/spring-mvc-view-solution4/src/main/java/ru/otus/spring/domain/Person.java @@ -0,0 +1,37 @@ +package ru.otus.spring.domain; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; + +@Entity +public class Person { + + @Id + @GeneratedValue + private int id; + private String name; + + public Person() { + } + + public Person(String name) { + this.name = name; + } + + 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; + } +} diff --git a/2022-02/spring-18-view/spring-mvc-view-solution4/src/main/java/ru/otus/spring/repostory/PersonRepository.java b/2022-02/spring-18-view/spring-mvc-view-solution4/src/main/java/ru/otus/spring/repostory/PersonRepository.java new file mode 100644 index 00000000..4b20e5b7 --- /dev/null +++ b/2022-02/spring-18-view/spring-mvc-view-solution4/src/main/java/ru/otus/spring/repostory/PersonRepository.java @@ -0,0 +1,11 @@ +package ru.otus.spring.repostory; + +import org.springframework.data.repository.CrudRepository; +import ru.otus.spring.domain.Person; + +import java.util.List; + +public interface PersonRepository extends CrudRepository { + + List findAll(); +} diff --git a/2022-02/spring-18-view/spring-mvc-view-solution4/src/main/resources/templates/edit.html b/2022-02/spring-18-view/spring-mvc-view-solution4/src/main/resources/templates/edit.html new file mode 100644 index 00000000..4482d17a --- /dev/null +++ b/2022-02/spring-18-view/spring-mvc-view-solution4/src/main/resources/templates/edit.html @@ -0,0 +1,48 @@ + + + + + Edit person + + + + + +
+

Person Info:

+ +
+ + +
+ +
+ + +
+ +
+ + +
+
+ + + diff --git a/2022-02/spring-18-view/spring-mvc-view-solution4/src/main/resources/templates/list.html b/2022-02/spring-18-view/spring-mvc-view-solution4/src/main/resources/templates/list.html new file mode 100644 index 00000000..9af2d61c --- /dev/null +++ b/2022-02/spring-18-view/spring-mvc-view-solution4/src/main/resources/templates/list.html @@ -0,0 +1,49 @@ + + + + + List of all persons + + + +

Persons:

+ + + + + + + + + + + + + + + + +
IDNameAction
1John Doe + Edit +
+ + diff --git a/2022-02/spring-19-ajax/ajax-demo.html b/2022-02/spring-19-ajax/ajax-demo.html new file mode 100644 index 00000000..5165cdfc --- /dev/null +++ b/2022-02/spring-19-ajax/ajax-demo.html @@ -0,0 +1,90 @@ + + + + Технологии JS для отправки запросов + + + + + + + + + + + + + + +

+

+

+

+ +

+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/2022-02/spring-19-ajax/pom.xml b/2022-02/spring-19-ajax/pom.xml
new file mode 100644
index 00000000..0a47af1c
--- /dev/null
+++ b/2022-02/spring-19-ajax/pom.xml
@@ -0,0 +1,17 @@
+
+
+    4.0.0
+
+    ru.otus
+    spring-mvc-ajax
+    1.0
+
+    pom
+
+    
+        spring-ajax-demo
+        spring-boot-and-react-demo
+    
+
diff --git a/2022-02/spring-19-ajax/spring-ajax-demo/pom.xml b/2022-02/spring-19-ajax/spring-ajax-demo/pom.xml
new file mode 100644
index 00000000..9df3dae3
--- /dev/null
+++ b/2022-02/spring-19-ajax/spring-ajax-demo/pom.xml
@@ -0,0 +1,72 @@
+
+
+    4.0.0
+
+    ru.otus
+    spring-ajax-demo
+    1.0
+
+    
+        org.springframework.boot
+        spring-boot-starter-parent
+        2.6.3
+    
+
+    
+        11
+        11
+    
+
+    
+        
+            org.springframework.boot
+            spring-boot-starter
+        
+
+        
+            org.springframework.boot
+            spring-boot-starter-web
+        
+
+        
+            org.springframework.boot
+            spring-boot-starter-thymeleaf
+        
+
+        
+            org.webjars
+            jquery
+            3.5.1
+        
+
+
+        
+            com.h2database
+            h2
+        
+
+        
+            org.springframework.boot
+            spring-boot-starter-data-jpa
+        
+
+        
+            org.projectlombok
+            lombok
+            1.18.20
+            provided
+        
+
+    
+
+    
+        
+            
+                org.springframework.boot
+                spring-boot-maven-plugin
+            
+        
+    
+
diff --git a/2022-02/spring-19-ajax/spring-ajax-demo/src/main/java/ru/otus/spring/Main.java b/2022-02/spring-19-ajax/spring-ajax-demo/src/main/java/ru/otus/spring/Main.java
new file mode 100644
index 00000000..e2779e96
--- /dev/null
+++ b/2022-02/spring-19-ajax/spring-ajax-demo/src/main/java/ru/otus/spring/Main.java
@@ -0,0 +1,13 @@
+package ru.otus.spring;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+
+@SpringBootApplication
+public class Main {
+
+    public static void main(String[] args) {
+        SpringApplication.run(Main.class);
+    }
+
+}
diff --git a/2022-02/spring-19-ajax/spring-ajax-demo/src/main/java/ru/otus/spring/domain/Person.java b/2022-02/spring-19-ajax/spring-ajax-demo/src/main/java/ru/otus/spring/domain/Person.java
new file mode 100644
index 00000000..56404ae3
--- /dev/null
+++ b/2022-02/spring-19-ajax/spring-ajax-demo/src/main/java/ru/otus/spring/domain/Person.java
@@ -0,0 +1,22 @@
+package ru.otus.spring.domain;
+
+import lombok.AllArgsConstructor;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+
+import javax.persistence.*;
+
+@Data
+@NoArgsConstructor
+@AllArgsConstructor
+@Entity
+@Table(name = "persons")
+public class Person {
+
+    @Id
+    @GeneratedValue(strategy = GenerationType.IDENTITY)
+    private long id;
+
+    @Column(name = "name")
+    private String name;
+}
diff --git a/2022-02/spring-19-ajax/spring-ajax-demo/src/main/java/ru/otus/spring/page/PersonPagesController.java b/2022-02/spring-19-ajax/spring-ajax-demo/src/main/java/ru/otus/spring/page/PersonPagesController.java
new file mode 100644
index 00000000..0f3a2e76
--- /dev/null
+++ b/2022-02/spring-19-ajax/spring-ajax-demo/src/main/java/ru/otus/spring/page/PersonPagesController.java
@@ -0,0 +1,15 @@
+package ru.otus.spring.page;
+
+import org.springframework.stereotype.Controller;
+import org.springframework.ui.Model;
+import org.springframework.web.bind.annotation.GetMapping;
+
+@Controller
+public class PersonPagesController {
+
+    @GetMapping("/")
+    public String listPage(Model model) {
+        model.addAttribute("keywords", "list users in Omsk, omsk, list users, list users free");
+        return "list";
+    }
+}
diff --git a/2022-02/spring-19-ajax/spring-ajax-demo/src/main/java/ru/otus/spring/repostory/PersonRepository.java b/2022-02/spring-19-ajax/spring-ajax-demo/src/main/java/ru/otus/spring/repostory/PersonRepository.java
new file mode 100644
index 00000000..4fb88650
--- /dev/null
+++ b/2022-02/spring-19-ajax/spring-ajax-demo/src/main/java/ru/otus/spring/repostory/PersonRepository.java
@@ -0,0 +1,11 @@
+package ru.otus.spring.repostory;
+
+import org.springframework.data.repository.CrudRepository;
+import ru.otus.spring.domain.Person;
+
+import java.util.List;
+
+public interface PersonRepository extends CrudRepository {
+
+    List findAll();
+}
diff --git a/2022-02/spring-19-ajax/spring-ajax-demo/src/main/java/ru/otus/spring/rest/PersonController.java b/2022-02/spring-19-ajax/spring-ajax-demo/src/main/java/ru/otus/spring/rest/PersonController.java
new file mode 100644
index 00000000..26fee19f
--- /dev/null
+++ b/2022-02/spring-19-ajax/spring-ajax-demo/src/main/java/ru/otus/spring/rest/PersonController.java
@@ -0,0 +1,23 @@
+package ru.otus.spring.rest;
+
+import lombok.RequiredArgsConstructor;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.RestController;
+import ru.otus.spring.repostory.PersonRepository;
+import ru.otus.spring.rest.dto.PersonDto;
+
+import java.util.List;
+import java.util.stream.Collectors;
+
+@RequiredArgsConstructor
+@RestController
+public class PersonController {
+
+    private final PersonRepository repository;
+
+    @GetMapping("/api/persons")
+    public List getAllPersons() {
+        return repository.findAll().stream().map(PersonDto::toDto)
+                .collect(Collectors.toList());
+    }
+}
diff --git a/2022-02/spring-19-ajax/spring-ajax-demo/src/main/java/ru/otus/spring/rest/dto/PersonDto.java b/2022-02/spring-19-ajax/spring-ajax-demo/src/main/java/ru/otus/spring/rest/dto/PersonDto.java
new file mode 100644
index 00000000..ee966a8e
--- /dev/null
+++ b/2022-02/spring-19-ajax/spring-ajax-demo/src/main/java/ru/otus/spring/rest/dto/PersonDto.java
@@ -0,0 +1,26 @@
+/*
+ * Copyright 2016 Russian Post
+ *
+ * This source code is Russian Post Confidential Proprietary.
+ * This software is protected by copyright. All rights and titles are reserved.
+ * You shall not use, copy, distribute, modify, decompile, disassemble or reverse engineer the software.
+ * Otherwise this violation would be treated by law and would be subject to legal prosecution.
+ * Legal use of the software provides receipt of a license from the right name only.
+ */
+package ru.otus.spring.rest.dto;
+
+import lombok.AllArgsConstructor;
+import lombok.Data;
+import ru.otus.spring.domain.Person;
+
+@Data
+@AllArgsConstructor
+public class PersonDto {
+
+    private long id = -1;
+    private String name;
+
+    public static PersonDto toDto(Person person) {
+        return new PersonDto(person.getId(), person.getName());
+    }
+}
diff --git a/2022-02/spring-19-ajax/spring-ajax-demo/src/main/resources/application.yml b/2022-02/spring-19-ajax/spring-ajax-demo/src/main/resources/application.yml
new file mode 100644
index 00000000..02e01231
--- /dev/null
+++ b/2022-02/spring-19-ajax/spring-ajax-demo/src/main/resources/application.yml
@@ -0,0 +1,11 @@
+spring:
+  datasource:
+    url: jdbc:h2:mem:testdb
+    initialization-mode: always
+
+  jpa:
+    generate-ddl: false
+    hibernate:
+      ddl-auto: none
+
+    show-sql: true
\ No newline at end of file
diff --git a/2022-02/spring-19-ajax/spring-ajax-demo/src/main/resources/data.sql b/2022-02/spring-19-ajax/spring-ajax-demo/src/main/resources/data.sql
new file mode 100644
index 00000000..e60c79ca
--- /dev/null
+++ b/2022-02/spring-19-ajax/spring-ajax-demo/src/main/resources/data.sql
@@ -0,0 +1 @@
+INSERT INTO persons (name) VALUES ('Pushkin'), ('Lermontov')
\ No newline at end of file
diff --git a/2022-02/spring-19-ajax/spring-ajax-demo/src/main/resources/schema.sql b/2022-02/spring-19-ajax/spring-ajax-demo/src/main/resources/schema.sql
new file mode 100644
index 00000000..2190e858
--- /dev/null
+++ b/2022-02/spring-19-ajax/spring-ajax-demo/src/main/resources/schema.sql
@@ -0,0 +1,8 @@
+DROP TABLE IF EXISTS persons;
+
+CREATE TABLE persons (
+    id BIGSERIAL,
+    name VARCHAR(250),
+
+    PRIMARY KEY (id)
+);
\ No newline at end of file
diff --git a/2022-02/spring-19-ajax/spring-ajax-demo/src/main/resources/templates/list.html b/2022-02/spring-19-ajax/spring-ajax-demo/src/main/resources/templates/list.html
new file mode 100644
index 00000000..21696341
--- /dev/null
+++ b/2022-02/spring-19-ajax/spring-ajax-demo/src/main/resources/templates/list.html
@@ -0,0 +1,63 @@
+
+
+
+    
+    
+    List of all persons
+    
+    
+
+
+

Persons:

+ + + + + + + + + + +
IDName
+ + + + + diff --git a/2022-02/spring-19-ajax/spring-boot-and-react-demo/.gitignore b/2022-02/spring-19-ajax/spring-boot-and-react-demo/.gitignore new file mode 100644 index 00000000..b11e399f --- /dev/null +++ b/2022-02/spring-19-ajax/spring-boot-and-react-demo/.gitignore @@ -0,0 +1,30 @@ +target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/build/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + + +node/ +/node_modules +/output +package-lock.json diff --git a/2022-02/spring-19-ajax/spring-boot-and-react-demo/package.json b/2022-02/spring-19-ajax/spring-boot-and-react-demo/package.json new file mode 100644 index 00000000..64793e02 --- /dev/null +++ b/2022-02/spring-19-ajax/spring-boot-and-react-demo/package.json @@ -0,0 +1,28 @@ +{ + "name": "client", + "version": "1.0.0", + "description": "Simple react demo", + "main": "index.js", + "scripts": { + "dev": "webpack-dev-server --config webpack.dev.config.js", + "build": "webpack" + }, + "author": "", + "license": "ISC", + "dependencies": { + "react": "^16.2.0", + "react-dom": "^16.2.0" + }, + "devDependencies": { + "babel-core": "^6.26.3", + "babel-loader": "^7.1.5", + "babel-preset-env": "^1.7.0", + "babel-preset-react": "^6.24.1", + "react-css-modules": "^4.7.11", + "html-webpack-plugin": "^5.5.0", + "terser-webpack-plugin": "^5.3.0", + "webpack": "^5.67.0", + "webpack-cli": "^4.9.2", + "webpack-dev-server": "^4.7.3" + } +} diff --git a/2022-02/spring-19-ajax/spring-boot-and-react-demo/pom.xml b/2022-02/spring-19-ajax/spring-boot-and-react-demo/pom.xml new file mode 100644 index 00000000..d31f9b0d --- /dev/null +++ b/2022-02/spring-19-ajax/spring-boot-and-react-demo/pom.xml @@ -0,0 +1,88 @@ + + + 4.0.0 + + ru.otus + spring-boot-and-react-demo + 1.0 + + + org.springframework.boot + spring-boot-starter-parent + 2.6.3 + + + + 11 + 11 + + + + + org.springframework.boot + spring-boot-starter + + + org.springframework.boot + spring-boot-starter-web + + + + + com.h2database + h2 + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + com.github.eirslett + frontend-maven-plugin + 1.6 + + + install node and npm + + install-node-and-npm + + + v10.15.1 + 6.4.1 + + + + npm install + + npm + + generate-resources + + install + + + + npm run build + + npm + + generate-resources + + run build + + + + + + + diff --git a/2022-02/spring-19-ajax/spring-boot-and-react-demo/src/main/java/ru/otus/spring/Main.java b/2022-02/spring-19-ajax/spring-boot-and-react-demo/src/main/java/ru/otus/spring/Main.java new file mode 100644 index 00000000..e2779e96 --- /dev/null +++ b/2022-02/spring-19-ajax/spring-boot-and-react-demo/src/main/java/ru/otus/spring/Main.java @@ -0,0 +1,13 @@ +package ru.otus.spring; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Main { + + public static void main(String[] args) { + SpringApplication.run(Main.class); + } + +} diff --git a/2022-02/spring-19-ajax/spring-boot-and-react-demo/src/main/java/ru/otus/spring/domain/Person.java b/2022-02/spring-19-ajax/spring-boot-and-react-demo/src/main/java/ru/otus/spring/domain/Person.java new file mode 100644 index 00000000..84422dcb --- /dev/null +++ b/2022-02/spring-19-ajax/spring-boot-and-react-demo/src/main/java/ru/otus/spring/domain/Person.java @@ -0,0 +1,36 @@ +package ru.otus.spring.domain; + +import javax.persistence.*; + +@Entity +@Table(name = "persons") +public class Person { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private int id; + private String name; + + public Person() { + } + + public Person(String name) { + this.name = name; + } + + 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; + } +} diff --git a/2022-02/spring-19-ajax/spring-boot-and-react-demo/src/main/java/ru/otus/spring/repostory/PersonRepository.java b/2022-02/spring-19-ajax/spring-boot-and-react-demo/src/main/java/ru/otus/spring/repostory/PersonRepository.java new file mode 100644 index 00000000..4b20e5b7 --- /dev/null +++ b/2022-02/spring-19-ajax/spring-boot-and-react-demo/src/main/java/ru/otus/spring/repostory/PersonRepository.java @@ -0,0 +1,11 @@ +package ru.otus.spring.repostory; + +import org.springframework.data.repository.CrudRepository; +import ru.otus.spring.domain.Person; + +import java.util.List; + +public interface PersonRepository extends CrudRepository { + + List findAll(); +} diff --git a/2022-02/spring-19-ajax/spring-boot-and-react-demo/src/main/java/ru/otus/spring/rest/PersonController.java b/2022-02/spring-19-ajax/spring-boot-and-react-demo/src/main/java/ru/otus/spring/rest/PersonController.java new file mode 100644 index 00000000..8073a615 --- /dev/null +++ b/2022-02/spring-19-ajax/spring-boot-and-react-demo/src/main/java/ru/otus/spring/rest/PersonController.java @@ -0,0 +1,30 @@ +package ru.otus.spring.rest; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; +import ru.otus.spring.domain.Person; +import ru.otus.spring.repostory.PersonRepository; +import ru.otus.spring.rest.dto.PersonDto; + +import java.util.List; +import java.util.stream.Collectors; + +@RestController +public class PersonController { + + private final PersonRepository repository; + + @Autowired + public PersonController(PersonRepository repository) { + this.repository = repository; + } + + @GetMapping("/api/persons") + public List getAllPersons() { + return repository.findAll().stream().map(PersonDto::toDto) + .collect(Collectors.toList()); + } +} diff --git a/2022-02/spring-19-ajax/spring-boot-and-react-demo/src/main/java/ru/otus/spring/rest/dto/PersonDto.java b/2022-02/spring-19-ajax/spring-boot-and-react-demo/src/main/java/ru/otus/spring/rest/dto/PersonDto.java new file mode 100644 index 00000000..03918447 --- /dev/null +++ b/2022-02/spring-19-ajax/spring-boot-and-react-demo/src/main/java/ru/otus/spring/rest/dto/PersonDto.java @@ -0,0 +1,50 @@ +/* + * Copyright 2016 Russian Post + * + * This source code is Russian Post Confidential Proprietary. + * This software is protected by copyright. All rights and titles are reserved. + * You shall not use, copy, distribute, modify, decompile, disassemble or reverse engineer the software. + * Otherwise this violation would be treated by law and would be subject to legal prosecution. + * Legal use of the software provides receipt of a license from the right name only. + */ +package ru.otus.spring.rest.dto; + +import ru.otus.spring.domain.Person; + +/** + * DTO that represents Account + */ +@SuppressWarnings("all") +public class PersonDto { + + private int id = -1; + private String name; + + public PersonDto() { + } + + public PersonDto(int id, String name) { + this.id = id; + this.name = name; + } + + 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 static PersonDto toDto(Person person) { + return new PersonDto(person.getId(), person.getName()); + } +} diff --git a/2022-02/spring-19-ajax/spring-boot-and-react-demo/src/main/resources/application.yml b/2022-02/spring-19-ajax/spring-boot-and-react-demo/src/main/resources/application.yml new file mode 100644 index 00000000..02e01231 --- /dev/null +++ b/2022-02/spring-19-ajax/spring-boot-and-react-demo/src/main/resources/application.yml @@ -0,0 +1,11 @@ +spring: + datasource: + url: jdbc:h2:mem:testdb + initialization-mode: always + + jpa: + generate-ddl: false + hibernate: + ddl-auto: none + + show-sql: true \ No newline at end of file diff --git a/2022-02/spring-19-ajax/spring-boot-and-react-demo/src/main/resources/data.sql b/2022-02/spring-19-ajax/spring-boot-and-react-demo/src/main/resources/data.sql new file mode 100644 index 00000000..e60c79ca --- /dev/null +++ b/2022-02/spring-19-ajax/spring-boot-and-react-demo/src/main/resources/data.sql @@ -0,0 +1 @@ +INSERT INTO persons (name) VALUES ('Pushkin'), ('Lermontov') \ No newline at end of file diff --git a/2022-02/spring-19-ajax/spring-boot-and-react-demo/src/main/resources/schema.sql b/2022-02/spring-19-ajax/spring-boot-and-react-demo/src/main/resources/schema.sql new file mode 100644 index 00000000..2190e858 --- /dev/null +++ b/2022-02/spring-19-ajax/spring-boot-and-react-demo/src/main/resources/schema.sql @@ -0,0 +1,8 @@ +DROP TABLE IF EXISTS persons; + +CREATE TABLE persons ( + id BIGSERIAL, + name VARCHAR(250), + + PRIMARY KEY (id) +); \ No newline at end of file diff --git a/2022-02/spring-19-ajax/spring-boot-and-react-demo/src/ui/components/App.js b/2022-02/spring-19-ajax/spring-boot-and-react-demo/src/ui/components/App.js new file mode 100644 index 00000000..4a638db3 --- /dev/null +++ b/2022-02/spring-19-ajax/spring-boot-and-react-demo/src/ui/components/App.js @@ -0,0 +1,58 @@ +import React from 'react' + +const styles = { + personsTable: { + border: "1px solid steelblue", + width: "300px", + borderCollapse: "collapse", + }, + + personsTableItem: { + padding: "5px", + border: "1px solid steelblue" + } +} + +const Header = (props) => ( +

{props.title}

+); + +export default class App extends React.Component { + + constructor() { + super(); + this.state = {persons: []}; + } + + componentDidMount() { + fetch('/api/persons') + .then(response => response.json()) + .then(persons => this.setState({persons})); + } + + render() { + return ( + +
+ + + + + + + + + { + this.state.persons.map((person, i) => ( + + + + + )) + } + +
IDName
{person.id}{person.name}
+ + ) + } +}; diff --git a/2022-02/spring-19-ajax/spring-boot-and-react-demo/src/ui/index.html b/2022-02/spring-19-ajax/spring-boot-and-react-demo/src/ui/index.html new file mode 100644 index 00000000..86fc7182 --- /dev/null +++ b/2022-02/spring-19-ajax/spring-boot-and-react-demo/src/ui/index.html @@ -0,0 +1,15 @@ + + + + Minimal React Boilerplate + + + + +
+ + + + diff --git a/2022-02/spring-19-ajax/spring-boot-and-react-demo/src/ui/index.js b/2022-02/spring-19-ajax/spring-boot-and-react-demo/src/ui/index.js new file mode 100644 index 00000000..b054022e --- /dev/null +++ b/2022-02/spring-19-ajax/spring-boot-and-react-demo/src/ui/index.js @@ -0,0 +1,8 @@ +import React from 'react' +import ReactDOM from 'react-dom' +import App from './components/App' + +ReactDOM.render( + , + document.getElementById('root') +) \ No newline at end of file diff --git a/2022-02/spring-19-ajax/spring-boot-and-react-demo/webpack.config.js b/2022-02/spring-19-ajax/spring-boot-and-react-demo/webpack.config.js new file mode 100644 index 00000000..243d6d88 --- /dev/null +++ b/2022-02/spring-19-ajax/spring-boot-and-react-demo/webpack.config.js @@ -0,0 +1,51 @@ +const TerserPlugin = require("terser-webpack-plugin"); +const HtmlWebpackPlugin = require('html-webpack-plugin') +const path = require('path'); +const webpack = require('webpack'); + +module.exports = { + entry: './src/ui/index.js', + mode: "production", + output: { + path: path.resolve(__dirname, 'target/classes/public/'), + filename: 'bundle.min.js', + libraryTarget: 'umd' + }, + + module: { + rules: [ + { + test: /\.js$/, + exclude: /(node_modules|bower_components|build)/, + use: { + loader: 'babel-loader', + options: { + presets: ['env', 'react'] + } + } + } + ] + }, + + optimization: { + minimize: true, + minimizer: [ + new TerserPlugin({ + extractComments: true, + }), + ], + }, + + plugins: [ + new webpack.DefinePlugin({ + "process.env": { + NODE_ENV: JSON.stringify("production") + } + }), + + new HtmlWebpackPlugin({ + filename: 'index.html', + template: 'src/ui/index.html' + }) + ] +} diff --git a/2022-02/spring-19-ajax/spring-boot-and-react-demo/webpack.dev.config.js b/2022-02/spring-19-ajax/spring-boot-and-react-demo/webpack.dev.config.js new file mode 100644 index 00000000..4d53c007 --- /dev/null +++ b/2022-02/spring-19-ajax/spring-boot-and-react-demo/webpack.dev.config.js @@ -0,0 +1,63 @@ +const HtmlWebpackPlugin = require('html-webpack-plugin') +const path = require('path'); + +module.exports = { + entry: './src/ui/index.js', + devtool: 'inline-source-map', + mode: 'development', + output: { + path: path.resolve(__dirname), + filename: 'bundle.js', + libraryTarget: 'umd' + }, + + devServer: { + static: path.resolve(__dirname) + '/src/ui', + compress: true, + port: 9000, + host: 'localhost', + open: true, +/* + setupMiddlewares: (middlewares, devServer) => { + middlewares.unshift({ + name: 'inital-data-mw', + path: '/api/persons', + middleware: (req, res) => res.send([ + {id: '1', name: 'Привяу'} + ]) + }); + return middlewares; + }, +*/ + proxy: { + '*': { + target: 'http://localhost:8080', + secure: false, + changeOrigin: true + } + } + + + }, + + module: { + rules: [ + { + test: /\.js$/, + exclude: /(node_modules|bower_components|build)/, + use: { + loader: 'babel-loader', + options: { + presets: ['env', 'react'] + } + } + } + ] + }, + plugins: [ + new HtmlWebpackPlugin({ + filename: 'index.html', + template: 'src/ui/index.html' + }) + ] +} diff --git a/2022-02/spring-20/.gitignore b/2022-02/spring-20/.gitignore new file mode 100644 index 00000000..fbe7a1ed --- /dev/null +++ b/2022-02/spring-20/.gitignore @@ -0,0 +1,7 @@ +.idea/ +*.iml + +target/ + +/node_modules +/output diff --git a/2022-02/spring-20/pom.xml b/2022-02/spring-20/pom.xml new file mode 100644 index 00000000..d4fa3309 --- /dev/null +++ b/2022-02/spring-20/pom.xml @@ -0,0 +1,33 @@ + + + 4.0.0 + + ru.otus + spring-18 + 1.0-SNAPSHOT + + + org.springframework.boot + spring-boot-starter-parent + 2.2.4.RELEASE + + + + 11 + 11 + + + + + io.reactivex.rxjava2 + rxjava + + + com.google.guava + guava + 27.1-jre + + + diff --git a/2022-02/spring-20/src/main/java/ru/otus/CreateExamples.java b/2022-02/spring-20/src/main/java/ru/otus/CreateExamples.java new file mode 100644 index 00000000..b8a21736 --- /dev/null +++ b/2022-02/spring-20/src/main/java/ru/otus/CreateExamples.java @@ -0,0 +1,35 @@ +package ru.otus; + +import io.reactivex.Observable; + +@SuppressWarnings("ResultOfMethodCallIgnored") +public class CreateExamples { + + public static void main(String[] args) { + Observable obs = justExample(); + obs.forEach(System.out::println); + obs.forEach(System.out::println); + } + + public static Observable justExample() { + return Observable.just("one", "two", "three"); + } + + public static Observable createExample() { + return Observable.create(emitter -> { + if (emitter.isDisposed()) { + return; + } + emitter.onNext("one"); + emitter.onNext("two");//! + emitter.onNext("three"); + if (!emitter.isDisposed()) { + emitter.onComplete(); + } + }); + } + + public static Observable deferExample() { + return Observable.defer(() -> Observable.just("one", "two", "three")); + } +} diff --git a/2022-02/spring-20/src/main/java/ru/otus/LiveLikeExample.java b/2022-02/spring-20/src/main/java/ru/otus/LiveLikeExample.java new file mode 100644 index 00000000..3f8e31d4 --- /dev/null +++ b/2022-02/spring-20/src/main/java/ru/otus/LiveLikeExample.java @@ -0,0 +1,26 @@ +package ru.otus; + +import io.reactivex.Observable; + +import java.io.IOException; + +public class LiveLikeExample { + + public static void main(String[] args) throws IOException { + + System.in.read(); + } + + static Observable getName() { + return Observable.just("Jake"); + } + + static Observable getSurname() { + return Observable.just("Foo"); + } + + static Observable save(String fullName) { + System.out.println(fullName + " saved!"); + return Observable.just("OK!"); + } +} diff --git a/2022-02/spring-20/src/main/java/ru/otus/OperatorsExample.java b/2022-02/spring-20/src/main/java/ru/otus/OperatorsExample.java new file mode 100644 index 00000000..21397f79 --- /dev/null +++ b/2022-02/spring-20/src/main/java/ru/otus/OperatorsExample.java @@ -0,0 +1,81 @@ +package ru.otus; + +import com.google.common.collect.ImmutableList; +import io.reactivex.Observable; +import io.reactivex.ObservableTransformer; +import io.reactivex.schedulers.Schedulers; +import io.reactivex.subjects.PublishSubject; + +import java.time.LocalDate; +import java.util.List; +import java.util.Random; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; + +@SuppressWarnings("ResultOfMethodCallIgnored") +public class OperatorsExample { + public static void main(String[] args) throws Exception { + simpleExample(); + System.in.read(); + } + + public static void simpleExample() throws Exception { + List persons = ImmutableList.of( + new Person("John", "Dow", "male", LocalDate.of(1992, 3, 12)), + new Person("Jane", "Dow", "female", LocalDate.of(2001, 6, 23)), + new Person("Howard", "Lovecraft", "male", LocalDate.of(1890, 8, 20)), + new Person("Joanne", "Rowling", "female", LocalDate.of(1965, 6, 30))); + + Observable.fromIterable(persons) + .filter( + person -> person.getBirth().isAfter(LocalDate.of(1990, 1, 1)) + ) + .map(p -> p.getFirstName() + " " + p.getLastName()) + .toList() + .subscribe(System.out::println); + } + + public static void publisherExample() throws Exception { + Observable ob = magicPublisher(); + System.out.println("First subscribed"); + ob.subscribe(System.out::println); + Thread.sleep(5000); + System.out.println("Second subscribed"); + ob.subscribe(System.out::println); + } + + public static Observable magicPublisher() { + Random r = new Random(1); + AtomicInteger i = new AtomicInteger(); + Observable obs = Observable.generate( + emitter -> { + emitter.onNext("" + i.incrementAndGet()); + Thread.sleep(1000); + }) + .subscribeOn(Schedulers.newThread()); + PublishSubject subject = PublishSubject.create(); + +// BehaviorSubject subject = BehaviorSubject.create(); + +// AsyncSubject subject = AsyncSubject.create(); +// CompletableFuture.runAsync(() -> { +// try { +// Thread.sleep(7000); +// } catch (InterruptedException e) { +// e.printStackTrace(); +// } +// subject.onComplete(); +// }); + +// ReplaySubject subject = ReplaySubject.create(); + obs.subscribe(subject); + return subject; + } + + //composeExmaple + private static ObservableTransformer filterAndUpperCase() { + return upstream -> upstream + .filter(s -> s.length() >= 4) + .map(String::toUpperCase); + } +} diff --git a/2022-02/spring-20/src/main/java/ru/otus/Person.java b/2022-02/spring-20/src/main/java/ru/otus/Person.java new file mode 100644 index 00000000..72d3f520 --- /dev/null +++ b/2022-02/spring-20/src/main/java/ru/otus/Person.java @@ -0,0 +1,66 @@ +package ru.otus; + +import java.time.LocalDate; +import java.util.Objects; + +public class Person { + private String firstName; + private String lastName; + private String gender; + private LocalDate birth; + + public Person(String firstName, String lastName, String gender, LocalDate birth) { + this.firstName = firstName; + this.lastName = lastName; + this.gender = gender; + this.birth = birth; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getGender() { + return gender; + } + + public void setGender(String gender) { + this.gender = gender; + } + + public LocalDate getBirth() { + return birth; + } + + public void setBirth(LocalDate birth) { + this.birth = birth; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Person person = (Person) o; + return Objects.equals(firstName, person.firstName) && + Objects.equals(lastName, person.lastName) && + Objects.equals(gender, person.gender) && + Objects.equals(birth, person.birth); + } + + @Override + public int hashCode() { + return Objects.hash(firstName, lastName, gender, birth); + } +} diff --git a/2022-02/spring-20/src/main/java/ru/otus/comparison/AsyncComparison.java b/2022-02/spring-20/src/main/java/ru/otus/comparison/AsyncComparison.java new file mode 100644 index 00000000..5b0b227a --- /dev/null +++ b/2022-02/spring-20/src/main/java/ru/otus/comparison/AsyncComparison.java @@ -0,0 +1,40 @@ +package ru.otus.comparison; + +import io.reactivex.Observable; +import io.reactivex.schedulers.Schedulers; + +import java.io.IOException; + +public class AsyncComparison { + + public static void main(String[] args) throws IOException { + final long timeStarted = System.currentTimeMillis(); + final Observable obs = controller(); + obs.subscribe(System.out::println); + System.out.println("Wait time " + (System.currentTimeMillis() - timeStarted)); + System.in.read(); + } + + static Observable controller() { + return service(); + } + + static Observable service() { + return repository(); + } + + static Observable repository() { + return database(); + } + + static Observable database() { + return Observable.defer(() -> { + try { + Thread.sleep(4000); + } catch (Exception e) { + System.out.println("Don't do this"); + } + return Observable.just("Hello world"); + }).subscribeOn(Schedulers.newThread()); + } +} diff --git a/2022-02/spring-20/src/main/java/ru/otus/comparison/SyncComparison.java b/2022-02/spring-20/src/main/java/ru/otus/comparison/SyncComparison.java new file mode 100644 index 00000000..c2bf7077 --- /dev/null +++ b/2022-02/spring-20/src/main/java/ru/otus/comparison/SyncComparison.java @@ -0,0 +1,31 @@ +package ru.otus.comparison; + +public class SyncComparison { + + public static void main(String[] args) { + final long timeStarted = System.currentTimeMillis(); + System.out.println(controller()); + System.out.println(System.currentTimeMillis() - timeStarted); + } + + static String controller() { + return service(); + } + + static String service() { + return repository(); + } + + static String repository() { + return database(); + } + + static String database() { + try { + Thread.sleep(4000); + } catch (Exception e) { + System.out.println("Don't do this"); + } + return "Hello world"; + } +} diff --git a/2022-02/spring-21/.gitignore b/2022-02/spring-21/.gitignore new file mode 100644 index 00000000..4ea52072 --- /dev/null +++ b/2022-02/spring-21/.gitignore @@ -0,0 +1,24 @@ +target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/build/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ diff --git a/2022-02/spring-21/pom.xml b/2022-02/spring-21/pom.xml new file mode 100644 index 00000000..ad4f8eda --- /dev/null +++ b/2022-02/spring-21/pom.xml @@ -0,0 +1,18 @@ + + + 4.0.0 + + ru.otus + spring-21 + 1.0 + + pom + + + spring-21-web-flux + spring-21-reactor + spring-21-reactive-spring-data + + diff --git a/2022-02/spring-21/spring-21-reactive-spring-data/pom.xml b/2022-02/spring-21/spring-21-reactive-spring-data/pom.xml new file mode 100644 index 00000000..0b9b89b1 --- /dev/null +++ b/2022-02/spring-21/spring-21-reactive-spring-data/pom.xml @@ -0,0 +1,50 @@ + + + 4.0.0 + + ru.otus + spring-21-reactive-spring-data + 1.0 + + + org.springframework.boot + spring-boot-starter-parent + 2.5.6 + + + + + 11 + + + + + org.springframework.boot + spring-boot-starter + + + + org.springframework.boot + spring-boot-starter-data-mongodb-reactive + + + org.mongodb + mongodb-driver-reactivestreams + + + de.flapdoodle.embed + de.flapdoodle.embed.mongo + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + diff --git a/2022-02/spring-21/spring-21-reactive-spring-data/src/main/java/ru/otus/spring/Main.java b/2022-02/spring-21/spring-21-reactive-spring-data/src/main/java/ru/otus/spring/Main.java new file mode 100644 index 00000000..e68a7f08 --- /dev/null +++ b/2022-02/spring-21/spring-21-reactive-spring-data/src/main/java/ru/otus/spring/Main.java @@ -0,0 +1,42 @@ +package ru.otus.spring; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.ApplicationContext; +import reactor.core.publisher.Flux; +import ru.otus.spring.domain.Person; +import ru.otus.spring.repostory.AccountRepository; +import ru.otus.spring.repostory.PersonRepository; + +import java.util.List; + +@SpringBootApplication +public class Main { + + public static void main(String[] args) throws InterruptedException { + ApplicationContext context = SpringApplication.run(Main.class); + + PersonRepository repository = context.getBean(PersonRepository.class); + AccountRepository accountRepository = context.getBean(AccountRepository.class); + + var persons = List.of( + new Person("Pushkin"), + new Person("Lermontov")); + + // subscribe блокирует текущий поток и дожидается Flux + repository.saveAll(persons) + .subscribe(); + + // а вот это уже неблокирующий subscribe + repository.findAll() + .map(Person::getName) + .subscribe(System.out::println); + + // Пример объединения двух Flux + Flux.merge(repository.findAll(), repository.findAll()) + .map(Person::getName) + .subscribe(System.out::println); + + Thread.sleep(20000); + } +} diff --git a/2022-02/spring-21/spring-21-reactive-spring-data/src/main/java/ru/otus/spring/domain/Account.java b/2022-02/spring-21/spring-21-reactive-spring-data/src/main/java/ru/otus/spring/domain/Account.java new file mode 100644 index 00000000..0f34a772 --- /dev/null +++ b/2022-02/spring-21/spring-21-reactive-spring-data/src/main/java/ru/otus/spring/domain/Account.java @@ -0,0 +1,37 @@ +package ru.otus.spring.domain; + +public class Account { + private String id; + private String personId; + private Long amount; + + public Account(String id, String personId, Long amount) { + this.id = id; + this.personId = personId; + this.amount = amount; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getPersonId() { + return personId; + } + + public void setPersonId(String personId) { + this.personId = personId; + } + + public Long getAmount() { + return amount; + } + + public void setAmount(Long amount) { + this.amount = amount; + } +} diff --git a/2022-02/spring-21/spring-21-reactive-spring-data/src/main/java/ru/otus/spring/domain/Person.java b/2022-02/spring-21/spring-21-reactive-spring-data/src/main/java/ru/otus/spring/domain/Person.java new file mode 100644 index 00000000..2bdc3894 --- /dev/null +++ b/2022-02/spring-21/spring-21-reactive-spring-data/src/main/java/ru/otus/spring/domain/Person.java @@ -0,0 +1,27 @@ +package ru.otus.spring.domain; + +public class Person { + + private String id; + private String name; + + public Person(String name) { + this.name = name; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/2022-02/spring-21/spring-21-reactive-spring-data/src/main/java/ru/otus/spring/repostory/AccountRepository.java b/2022-02/spring-21/spring-21-reactive-spring-data/src/main/java/ru/otus/spring/repostory/AccountRepository.java new file mode 100644 index 00000000..a06fcdb3 --- /dev/null +++ b/2022-02/spring-21/spring-21-reactive-spring-data/src/main/java/ru/otus/spring/repostory/AccountRepository.java @@ -0,0 +1,7 @@ +package ru.otus.spring.repostory; + +import org.springframework.data.mongodb.repository.ReactiveMongoRepository; +import ru.otus.spring.domain.Account; + +public interface AccountRepository extends ReactiveMongoRepository { +} diff --git a/2022-02/spring-21/spring-21-reactive-spring-data/src/main/java/ru/otus/spring/repostory/PersonRepository.java b/2022-02/spring-21/spring-21-reactive-spring-data/src/main/java/ru/otus/spring/repostory/PersonRepository.java new file mode 100644 index 00000000..26b562e2 --- /dev/null +++ b/2022-02/spring-21/spring-21-reactive-spring-data/src/main/java/ru/otus/spring/repostory/PersonRepository.java @@ -0,0 +1,15 @@ +package ru.otus.spring.repostory; + +import org.springframework.data.mongodb.repository.Query; +import org.springframework.data.mongodb.repository.ReactiveMongoRepository; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; +import ru.otus.spring.domain.Person; + +public interface PersonRepository extends ReactiveMongoRepository { + + Flux findByName(String name); + + @Query("{ 'name': ?0 }") + Mono findFirstByName(String name); +} diff --git a/2022-02/spring-21/spring-21-reactive-spring-data/src/main/resources/application.yml b/2022-02/spring-21/spring-21-reactive-spring-data/src/main/resources/application.yml new file mode 100644 index 00000000..e69de29b diff --git a/2022-02/spring-21/spring-21-reactor/pom.xml b/2022-02/spring-21/spring-21-reactor/pom.xml new file mode 100644 index 00000000..b583fdc7 --- /dev/null +++ b/2022-02/spring-21/spring-21-reactor/pom.xml @@ -0,0 +1,41 @@ + + + 4.0.0 + + ru.otus + spring-21-reactor + 1.0 + + + org.springframework.boot + spring-boot-starter-parent + 2.6.3 + + + + + 11 + + + + + org.springframework.boot + spring-boot-starter + + + io.projectreactor + reactor-core + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + diff --git a/2022-02/spring-21/spring-21-reactor/src/main/java/ru/otus/spring/Main.java b/2022-02/spring-21/spring-21-reactor/src/main/java/ru/otus/spring/Main.java new file mode 100644 index 00000000..ff27392b --- /dev/null +++ b/2022-02/spring-21/spring-21-reactor/src/main/java/ru/otus/spring/Main.java @@ -0,0 +1,20 @@ +package ru.otus.spring; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.ConfigurableApplicationContext; +import ru.otus.spring.reactor.ReactiveProcessingService; + +@SpringBootApplication +public class Main { + + public static void main(String[] args) { + ConfigurableApplicationContext context = SpringApplication.run(Main.class); + + ReactiveProcessingService service = context.getBean(ReactiveProcessingService.class); + + service.printHello("Ivan"); + } +} + + diff --git a/2022-02/spring-21/spring-21-reactor/src/main/java/ru/otus/spring/reactor/Message.java b/2022-02/spring-21/spring-21-reactor/src/main/java/ru/otus/spring/reactor/Message.java new file mode 100644 index 00000000..ac58a62c --- /dev/null +++ b/2022-02/spring-21/spring-21-reactor/src/main/java/ru/otus/spring/reactor/Message.java @@ -0,0 +1,14 @@ +package ru.otus.spring.reactor; + +public class Message { + + private final String value; + + public Message(String value) { + this.value = value; + } + + public String getValue() { + return value; + } +} diff --git a/2022-02/spring-21/spring-21-reactor/src/main/java/ru/otus/spring/reactor/ReactiveProcessingService.java b/2022-02/spring-21/spring-21-reactor/src/main/java/ru/otus/spring/reactor/ReactiveProcessingService.java new file mode 100644 index 00000000..99836fe0 --- /dev/null +++ b/2022-02/spring-21/spring-21-reactor/src/main/java/ru/otus/spring/reactor/ReactiveProcessingService.java @@ -0,0 +1,58 @@ +package ru.otus.spring.reactor; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; +import reactor.core.Disposable; +import reactor.core.publisher.Sinks; +import ru.otus.spring.service.NonFluxService; + +import javax.annotation.PreDestroy; + +@Service +public class ReactiveProcessingService { + + private final Logger logger = LoggerFactory.getLogger(ReactiveProcessingService.class); + + private final Sinks.Many sink; + private final Disposable flow; + + public ReactiveProcessingService(NonFluxService nonFluxService) { + // Создаём sink (ранее - процессор) + // Это reactor-овская реализация reactive-stream интерфейса + // Обрабатывает данные как простой последовательный вызов методов :) + sink = Sinks.many().multicast().directBestEffort(); + // Здесь мы настраиваем flow + flow = sink.asFlux() + .map(nonFluxService::nonFluxSayHello) + .subscribe(this::printMessage); + // в идеале в коде выше должен быть doOnNext + // в map не предполагаются задержки + } + + /** + * Этот метод будет инициировать асинхронную обрабтку сообщения + * + * @param name это имя будет приходить из не-reactor окружения + */ + public void printHello(String name) { + sink.tryEmitNext(new Message(name)); + } + + /** + * А это терминальный шаг для сообщения + * + * @param message а это финальный шаг для сообщения, отсюда можно вернуть рзультат в не-реактив окружение + */ + private void printMessage(Message message) { + logger.info("Message received: {}", message.getValue()); + } + + /** + * Просто пример, как остановить процесс + */ + @PreDestroy + public void dispose() { + this.flow.dispose(); + } +} diff --git a/2022-02/spring-21/spring-21-reactor/src/main/java/ru/otus/spring/service/NonFluxService.java b/2022-02/spring-21/spring-21-reactor/src/main/java/ru/otus/spring/service/NonFluxService.java new file mode 100644 index 00000000..848971ed --- /dev/null +++ b/2022-02/spring-21/spring-21-reactor/src/main/java/ru/otus/spring/service/NonFluxService.java @@ -0,0 +1,25 @@ +package ru.otus.spring.service; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; +import ru.otus.spring.reactor.Message; + +@Service +public class NonFluxService { + + private final Logger logger = LoggerFactory.getLogger(NonFluxService.class); + + public Message nonFluxSayHello(Message message) { + logger.info("Message received in non-flux service: {}", message.getValue()); + + String name = message.getValue(); + String withHello = "Hello, " + name + "!"; + try { + Thread.sleep(1000); + return new Message(withHello); + } catch (InterruptedException ex) { + return new Message(withHello); + } + } +} diff --git a/2022-02/spring-21/spring-21-web-flux/pom.xml b/2022-02/spring-21/spring-21-web-flux/pom.xml new file mode 100644 index 00000000..f359099b --- /dev/null +++ b/2022-02/spring-21/spring-21-web-flux/pom.xml @@ -0,0 +1,45 @@ + + + 4.0.0 + + ru.otus + spring-21-web-flux + 1.0 + + + org.springframework.boot + spring-boot-starter-parent + 2.6.3 + + + + + 11 + + + + + org.springframework.boot + spring-boot-starter-webflux + + + + + io.reactivex.rxjava2 + rxjava + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + diff --git a/2022-02/spring-21/spring-21-web-flux/src/main/java/ru/otus/spring/Main.java b/2022-02/spring-21/spring-21-web-flux/src/main/java/ru/otus/spring/Main.java new file mode 100644 index 00000000..cad1ae76 --- /dev/null +++ b/2022-02/spring-21/spring-21-web-flux/src/main/java/ru/otus/spring/Main.java @@ -0,0 +1,14 @@ +package ru.otus.spring; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Main { + + public static void main(String[] args) { + SpringApplication.run(Main.class); + } +} + + diff --git a/2022-02/spring-21/spring-21-web-flux/src/main/java/ru/otus/spring/ReactorController.java b/2022-02/spring-21/spring-21-web-flux/src/main/java/ru/otus/spring/ReactorController.java new file mode 100644 index 00000000..ef1b72ac --- /dev/null +++ b/2022-02/spring-21/spring-21-web-flux/src/main/java/ru/otus/spring/ReactorController.java @@ -0,0 +1,34 @@ +package ru.otus.spring; + +import org.springframework.http.MediaType; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +import java.time.Duration; + +@RestController +public class ReactorController { + + @GetMapping("/flux/one") + public Mono one() { + return Mono.just("one"); + } + + @GetMapping("/flux/ten") + public Flux list() { + return repository.findAll() + .map(); + } + + @GetMapping(path = "/flux/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE) + public Flux stream() { + return Flux.generate(() -> 0, (state, emitter) -> { + emitter.next(state); + return state + 1; + }) + .delayElements(Duration.ofSeconds(1L)) + .map(Object::toString); + } +} diff --git a/2022-02/spring-21/spring-21-web-flux/src/main/java/ru/otus/spring/RxJava2Controller.java b/2022-02/spring-21/spring-21-web-flux/src/main/java/ru/otus/spring/RxJava2Controller.java new file mode 100644 index 00000000..edf0035f --- /dev/null +++ b/2022-02/spring-21/spring-21-web-flux/src/main/java/ru/otus/spring/RxJava2Controller.java @@ -0,0 +1,20 @@ +package ru.otus.spring; + +import io.reactivex.Flowable; +import io.reactivex.Single; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class RxJava2Controller { + + @GetMapping("/rx/one") + public Single single() { + return Single.just("one"); + } + + @GetMapping("/rx/ten") + public Flowable list() { + return Flowable.range(1, 10); + } +} diff --git a/2022-02/spring-22/.gitignore b/2022-02/spring-22/.gitignore new file mode 100644 index 00000000..e62c33c2 --- /dev/null +++ b/2022-02/spring-22/.gitignore @@ -0,0 +1,4 @@ +.idea/ +*.iml + +target/ diff --git a/2022-02/spring-22/spring-22-exercise/pom.xml b/2022-02/spring-22/spring-22-exercise/pom.xml new file mode 100644 index 00000000..4bb3b696 --- /dev/null +++ b/2022-02/spring-22/spring-22-exercise/pom.xml @@ -0,0 +1,60 @@ + + + 4.0.0 + + ru.otus + spring-22-exercise + 1.0 + + + org.springframework.boot + spring-boot-starter-parent + 2.4.5 + + + + + 11 + + + + + + org.springframework.boot + spring-boot-starter-webflux + + + + + org.springframework.boot + spring-boot-starter-data-mongodb-reactive + + + de.flapdoodle.embed + de.flapdoodle.embed.mongo + + + + + io.projectreactor + reactor-test + test + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + diff --git a/2022-02/spring-22/spring-22-exercise/src/main/java/ru/otus/spring/Main.java b/2022-02/spring-22/spring-22-exercise/src/main/java/ru/otus/spring/Main.java new file mode 100644 index 00000000..7b3c42bf --- /dev/null +++ b/2022-02/spring-22/spring-22-exercise/src/main/java/ru/otus/spring/Main.java @@ -0,0 +1,69 @@ +package ru.otus.spring; + +import org.apache.commons.lang3.StringUtils; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.web.reactive.function.server.RouterFunction; +import org.springframework.web.reactive.function.server.ServerRequest; +import org.springframework.web.reactive.function.server.ServerResponse; +import reactor.core.publisher.Mono; +import ru.otus.spring.domain.Person; +import ru.otus.spring.repository.PersonRepository; + +import java.util.Arrays; + +import static org.springframework.http.MediaType.APPLICATION_JSON; +import static org.springframework.web.reactive.function.BodyInserters.fromObject; +import static org.springframework.web.reactive.function.BodyInserters.fromValue; +import static org.springframework.web.reactive.function.server.RequestPredicates.accept; +import static org.springframework.web.reactive.function.server.RequestPredicates.queryParam; +import static org.springframework.web.reactive.function.server.RouterFunctions.route; +import static org.springframework.web.reactive.function.server.ServerResponse.*; + +@SpringBootApplication +public class Main { + + public static void main(String[] args) { + ApplicationContext context = SpringApplication.run(Main.class); + PersonRepository repository = context.getBean(PersonRepository.class); + + repository.saveAll(Arrays.asList( + new Person("Pushkin", 22), + new Person("Lermontov", 22), + new Person("Tolstoy", 60) + )).subscribe(p -> System.out.println(p.getLastName())); + + } + + @Bean + public RouterFunction composedRoutes(PersonRepository repository) { + return route() + // Обратите внимание на использование хэндлера + .GET("/func/person", accept(APPLICATION_JSON), new PersonHandler(repository)::list) + // Обратите внимание на использование pathVariable + .GET("/func/person/{id}", accept(APPLICATION_JSON), + request -> repository.findById(request.pathVariable("id")) + .flatMap(person -> ok().contentType(APPLICATION_JSON).body(fromValue(person))) + .switchIfEmpty(notFound().build()) + ).build(); + } + + // Это пример хэндлера, который даже не бин + static class PersonHandler { + + private final PersonRepository repository; + + PersonHandler(PersonRepository repository) { + this.repository = repository; + } + + Mono list(ServerRequest request) { + // Обратите внимание на пример другого порядка создания response от Flux + return ok().contentType(APPLICATION_JSON).body(repository.findAll(), Person.class); + } + } +} + + diff --git a/2022-02/spring-22/spring-22-exercise/src/main/java/ru/otus/spring/domain/Person.java b/2022-02/spring-22/spring-22-exercise/src/main/java/ru/otus/spring/domain/Person.java new file mode 100644 index 00000000..d40218ec --- /dev/null +++ b/2022-02/spring-22/spring-22-exercise/src/main/java/ru/otus/spring/domain/Person.java @@ -0,0 +1,55 @@ +package ru.otus.spring.domain; + +import com.fasterxml.jackson.annotation.JsonProperty; +import org.springframework.data.annotation.Id; +import org.springframework.data.mongodb.core.mapping.Document; +import org.springframework.data.mongodb.core.mapping.Field; + +@Document +public class Person { + + @Id + private String id; + + @JsonProperty("name") + @Field("name") + private String lastName; + + private int age; + + public Person() { + } + + public Person(String lastName) { + this.lastName = lastName; + } + + public Person(String lastName, int age) { + this.lastName = lastName; + this.age = age; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } +} diff --git a/2022-02/spring-22/spring-22-exercise/src/main/java/ru/otus/spring/repository/PersonRepository.java b/2022-02/spring-22/spring-22-exercise/src/main/java/ru/otus/spring/repository/PersonRepository.java new file mode 100644 index 00000000..0584f0cb --- /dev/null +++ b/2022-02/spring-22/spring-22-exercise/src/main/java/ru/otus/spring/repository/PersonRepository.java @@ -0,0 +1,20 @@ +package ru.otus.spring.repository; + +import org.springframework.data.mongodb.repository.ReactiveMongoRepository; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; +import ru.otus.spring.domain.Person; + +public interface PersonRepository + extends ReactiveMongoRepository { + + Flux findAll(); + + Mono findById(String id); + + Mono save(Mono person); + + Flux findAllByLastName(String lastName); + + Flux findAllByAge(int age); +} diff --git a/2022-02/spring-22/spring-22-exercise/src/main/java/ru/otus/spring/rest/AnnotatedController.java b/2022-02/spring-22/spring-22-exercise/src/main/java/ru/otus/spring/rest/AnnotatedController.java new file mode 100644 index 00000000..fc3bded8 --- /dev/null +++ b/2022-02/spring-22/spring-22-exercise/src/main/java/ru/otus/spring/rest/AnnotatedController.java @@ -0,0 +1,33 @@ +package ru.otus.spring.rest; + +import org.springframework.http.MediaType; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +import java.time.Duration; + +@RestController +public class AnnotatedController { + + @GetMapping("/flux/one") + public Mono one() { + return Mono.just("one"); + } + + @GetMapping("/flux/ten") + public Flux list() { + return Flux.range(1, 10).delayElements(Duration.ofSeconds(1)); + } + + @GetMapping(path = "/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE) + public Flux stream() { + return Flux.generate(() -> 0, (state, emitter) -> { + emitter.next(state); + return state + 1; + }) + .delayElements(Duration.ofSeconds(1L)) + .map(i -> "" + i); + } +} diff --git a/2022-02/spring-22/spring-22-exercise/src/main/java/ru/otus/spring/rest/PersonController.java b/2022-02/spring-22/spring-22-exercise/src/main/java/ru/otus/spring/rest/PersonController.java new file mode 100644 index 00000000..c6f2df03 --- /dev/null +++ b/2022-02/spring-22/spring-22-exercise/src/main/java/ru/otus/spring/rest/PersonController.java @@ -0,0 +1,37 @@ +package ru.otus.spring.rest; + +import org.springframework.web.bind.annotation.*; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; +import ru.otus.spring.domain.Person; +import ru.otus.spring.repository.PersonRepository; + +@RestController +public class PersonController { + + private final PersonRepository repository; + + public PersonController(PersonRepository repository) { + this.repository = repository; + } + + @GetMapping("/person") + public Flux all() { + return repository.findAll(); + } + + @GetMapping("/person/{id}") + public Mono byId(@PathVariable("id") String id) { + return repository.findById(id); + } + + @PostMapping("/person") + public Mono save(@RequestBody Mono dto) { + return repository.save(dto); + } + + @GetMapping("/person/find") + public Flux byName(@RequestParam("name") String name) { + return repository.findAllByLastName(name); + } +} diff --git a/2022-02/spring-22/spring-22-exercise/src/test/java/ru/otus/spring/repository/PersonRepositoryTest.java b/2022-02/spring-22/spring-22-exercise/src/test/java/ru/otus/spring/repository/PersonRepositoryTest.java new file mode 100644 index 00000000..2f373b60 --- /dev/null +++ b/2022-02/spring-22/spring-22-exercise/src/test/java/ru/otus/spring/repository/PersonRepositoryTest.java @@ -0,0 +1,28 @@ +package ru.otus.spring.repository; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest; +import reactor.core.publisher.Mono; +import reactor.test.StepVerifier; +import ru.otus.spring.domain.Person; + +import static org.junit.jupiter.api.Assertions.assertNotNull; + +@DataMongoTest +public class PersonRepositoryTest { + + @Autowired + private PersonRepository repository; + + @Test + public void shouldSetIdOnSave() { + Mono personMono = repository.save(new Person("Bill", 12)); + + StepVerifier + .create(personMono) + .assertNext(person -> assertNotNull(person.getId())) + .expectComplete() + .verify(); + } +} diff --git a/2022-02/spring-22/spring-22-exercise/src/test/java/ru/otus/spring/rest/PersonControllerTest.java b/2022-02/spring-22/spring-22-exercise/src/test/java/ru/otus/spring/rest/PersonControllerTest.java new file mode 100644 index 00000000..d1504547 --- /dev/null +++ b/2022-02/spring-22/spring-22-exercise/src/test/java/ru/otus/spring/rest/PersonControllerTest.java @@ -0,0 +1,28 @@ +package ru.otus.spring.rest; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.web.reactive.server.WebTestClient; +import org.springframework.web.reactive.function.server.RouterFunction; +import org.springframework.web.reactive.function.server.ServerResponse; + +@SpringBootTest +public class PersonControllerTest { + + @Autowired + private RouterFunction route; + + @Test + public void testRoute() { + WebTestClient client = WebTestClient + .bindToRouterFunction(route) + .build(); + + client.get() + .uri("/func/person") + .exchange() + .expectStatus() + .isOk(); + } +} diff --git a/2022-02/spring-22/spring-22-solution/pom.xml b/2022-02/spring-22/spring-22-solution/pom.xml new file mode 100644 index 00000000..0b076478 --- /dev/null +++ b/2022-02/spring-22/spring-22-solution/pom.xml @@ -0,0 +1,60 @@ + + + 4.0.0 + + ru.otus + spring-22-solution + 1.0 + + + org.springframework.boot + spring-boot-starter-parent + 2.4.5 + + + + + 11 + + + + + + org.springframework.boot + spring-boot-starter-webflux + + + + + org.springframework.boot + spring-boot-starter-data-mongodb-reactive + + + de.flapdoodle.embed + de.flapdoodle.embed.mongo + + + + + io.projectreactor + reactor-test + test + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + diff --git a/2022-02/spring-22/spring-22-solution/src/main/java/ru/otus/spring/Main.java b/2022-02/spring-22/spring-22-solution/src/main/java/ru/otus/spring/Main.java new file mode 100644 index 00000000..8bad8f3d --- /dev/null +++ b/2022-02/spring-22/spring-22-solution/src/main/java/ru/otus/spring/Main.java @@ -0,0 +1,82 @@ +package ru.otus.spring; + +import org.apache.commons.lang3.StringUtils; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.web.reactive.function.server.RouterFunction; +import org.springframework.web.reactive.function.server.ServerRequest; +import org.springframework.web.reactive.function.server.ServerResponse; +import reactor.core.publisher.Mono; +import ru.otus.spring.domain.Person; +import ru.otus.spring.repository.PersonRepository; + +import java.util.Arrays; + +import static org.springframework.http.MediaType.APPLICATION_JSON; +import static org.springframework.web.reactive.function.BodyInserters.fromObject; +import static org.springframework.web.reactive.function.BodyInserters.fromValue; +import static org.springframework.web.reactive.function.server.RequestPredicates.accept; +import static org.springframework.web.reactive.function.server.RequestPredicates.queryParam; +import static org.springframework.web.reactive.function.server.RouterFunctions.route; +import static org.springframework.web.reactive.function.server.ServerResponse.*; + +@SpringBootApplication +public class Main { + + public static void main(String[] args) { + ApplicationContext context = SpringApplication.run(Main.class); + PersonRepository repository = context.getBean(PersonRepository.class); + + repository.saveAll(Arrays.asList( + new Person("Pushkin", 22), + new Person("Lermontov", 22), + new Person("Tolstoy", 60) + )).subscribe(p -> System.out.println(p.getLastName())); + } + + @Bean + public RouterFunction composedRoutes(PersonRepository repository) { + return route() + // эта функция должна стоять раньше findAll - порядок следования роутов - важен + .GET("/func/person", queryParam("name", StringUtils::isNotEmpty), + request -> request.queryParam("name") + .map(repository::findAllByLastName) + .map(persons -> ok().body(persons, Person.class)) + .orElse(badRequest().build()) + ) + // пример другой реализации - начиная с запроса репозитория + .GET("/func/person", queryParam("age", StringUtils::isNotEmpty), + req -> repository.findAllByLastName( + req.queryParam("age").orElseThrow(IllegalArgumentException::new) + ) + .collectList() + .flatMap(persons -> ok().body(persons, Person.class))) + // Обратите внимание на использование хэндлера + .GET("/func/person", accept(APPLICATION_JSON), new PersonHandler(repository)::list) + // Обратите внимание на использование pathVariable + .GET("/func/person/{id}", accept(APPLICATION_JSON), + request -> repository.findById(request.pathVariable("id")) + .flatMap(person -> ok().contentType(APPLICATION_JSON).body(fromValue(person))) + .switchIfEmpty(notFound().build()) + ).build(); + } + + // Это пример хэндлера, который даже не бин + static class PersonHandler { + + private final PersonRepository repository; + + PersonHandler(PersonRepository repository) { + this.repository = repository; + } + + Mono list(ServerRequest request) { + // Обратите внимание на пример другого порядка создания response от Flux + return ok().contentType(APPLICATION_JSON).body(repository.findAll(), Person.class); + } + } +} + + diff --git a/2022-02/spring-22/spring-22-solution/src/main/java/ru/otus/spring/domain/Person.java b/2022-02/spring-22/spring-22-solution/src/main/java/ru/otus/spring/domain/Person.java new file mode 100644 index 00000000..d40218ec --- /dev/null +++ b/2022-02/spring-22/spring-22-solution/src/main/java/ru/otus/spring/domain/Person.java @@ -0,0 +1,55 @@ +package ru.otus.spring.domain; + +import com.fasterxml.jackson.annotation.JsonProperty; +import org.springframework.data.annotation.Id; +import org.springframework.data.mongodb.core.mapping.Document; +import org.springframework.data.mongodb.core.mapping.Field; + +@Document +public class Person { + + @Id + private String id; + + @JsonProperty("name") + @Field("name") + private String lastName; + + private int age; + + public Person() { + } + + public Person(String lastName) { + this.lastName = lastName; + } + + public Person(String lastName, int age) { + this.lastName = lastName; + this.age = age; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } +} diff --git a/2022-02/spring-22/spring-22-solution/src/main/java/ru/otus/spring/repository/PersonRepository.java b/2022-02/spring-22/spring-22-solution/src/main/java/ru/otus/spring/repository/PersonRepository.java new file mode 100644 index 00000000..0584f0cb --- /dev/null +++ b/2022-02/spring-22/spring-22-solution/src/main/java/ru/otus/spring/repository/PersonRepository.java @@ -0,0 +1,20 @@ +package ru.otus.spring.repository; + +import org.springframework.data.mongodb.repository.ReactiveMongoRepository; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; +import ru.otus.spring.domain.Person; + +public interface PersonRepository + extends ReactiveMongoRepository { + + Flux findAll(); + + Mono findById(String id); + + Mono save(Mono person); + + Flux findAllByLastName(String lastName); + + Flux findAllByAge(int age); +} diff --git a/2022-02/spring-22/spring-22-solution/src/main/java/ru/otus/spring/rest/AnnotatedController.java b/2022-02/spring-22/spring-22-solution/src/main/java/ru/otus/spring/rest/AnnotatedController.java new file mode 100644 index 00000000..184da872 --- /dev/null +++ b/2022-02/spring-22/spring-22-solution/src/main/java/ru/otus/spring/rest/AnnotatedController.java @@ -0,0 +1,34 @@ +package ru.otus.spring.rest; + +import org.springframework.http.MediaType; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +import java.time.Duration; + +@RestController +public class AnnotatedController { + + @GetMapping("/flux/one") + public Mono one() { + return Mono.just("one") + .map(String::toUpperCase); + } + + @GetMapping("/flux/ten") + public Flux list() { + return Flux.range(1, 10); + } + + @GetMapping(path = "/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE) + public Flux stream() { + return Flux.generate(() -> 0, (state, emitter) -> { + emitter.next(state); + return state + 1; + }) + .delayElements(Duration.ofSeconds(1L)) + .map(i -> "" + i); + } +} diff --git a/2022-02/spring-22/spring-22-solution/src/main/java/ru/otus/spring/rest/PersonController.java b/2022-02/spring-22/spring-22-solution/src/main/java/ru/otus/spring/rest/PersonController.java new file mode 100644 index 00000000..2edcaea9 --- /dev/null +++ b/2022-02/spring-22/spring-22-solution/src/main/java/ru/otus/spring/rest/PersonController.java @@ -0,0 +1,42 @@ +package ru.otus.spring.rest; + +import org.springframework.web.bind.annotation.*; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; +import ru.otus.spring.domain.Person; +import ru.otus.spring.repository.PersonRepository; + +@RestController +public class PersonController { + + private PersonRepository repository; + + public PersonController(PersonRepository repository) { + this.repository = repository; + } + + @GetMapping("/person") + public Flux all() { + return repository.findAll(); + } + + @GetMapping("/person/{id}") + public Mono byId(@PathVariable("id") String id) { + return repository.findById(id); + } + + @GetMapping("/person/byname") + public Flux byName(@RequestParam("name") String lastName) { + return repository.findAllByLastName(lastName); + } + + @GetMapping("/person/byage") + public Flux byAge(@RequestParam int age) { + return repository.findAllByAge(age); + } + + @PostMapping("/person") + public Mono save(@RequestBody Mono dto) { + return repository.save(dto); + } +} diff --git a/2022-02/spring-22/spring-22-solution/src/test/java/ru/otus/spring/repository/PersonRepositoryTest.java b/2022-02/spring-22/spring-22-solution/src/test/java/ru/otus/spring/repository/PersonRepositoryTest.java new file mode 100644 index 00000000..2f373b60 --- /dev/null +++ b/2022-02/spring-22/spring-22-solution/src/test/java/ru/otus/spring/repository/PersonRepositoryTest.java @@ -0,0 +1,28 @@ +package ru.otus.spring.repository; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest; +import reactor.core.publisher.Mono; +import reactor.test.StepVerifier; +import ru.otus.spring.domain.Person; + +import static org.junit.jupiter.api.Assertions.assertNotNull; + +@DataMongoTest +public class PersonRepositoryTest { + + @Autowired + private PersonRepository repository; + + @Test + public void shouldSetIdOnSave() { + Mono personMono = repository.save(new Person("Bill", 12)); + + StepVerifier + .create(personMono) + .assertNext(person -> assertNotNull(person.getId())) + .expectComplete() + .verify(); + } +} diff --git a/2022-02/spring-22/spring-22-solution/src/test/java/ru/otus/spring/rest/PersonControllerTest.java b/2022-02/spring-22/spring-22-solution/src/test/java/ru/otus/spring/rest/PersonControllerTest.java new file mode 100644 index 00000000..d1504547 --- /dev/null +++ b/2022-02/spring-22/spring-22-solution/src/test/java/ru/otus/spring/rest/PersonControllerTest.java @@ -0,0 +1,28 @@ +package ru.otus.spring.rest; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.web.reactive.server.WebTestClient; +import org.springframework.web.reactive.function.server.RouterFunction; +import org.springframework.web.reactive.function.server.ServerResponse; + +@SpringBootTest +public class PersonControllerTest { + + @Autowired + private RouterFunction route; + + @Test + public void testRoute() { + WebTestClient client = WebTestClient + .bindToRouterFunction(route) + .build(); + + client.get() + .uri("/func/person") + .exchange() + .expectStatus() + .isOk(); + } +} diff --git a/2022-05/spring-00/architecture-origins/.gitignore b/2022-05/spring-00/architecture-origins/.gitignore new file mode 100644 index 00000000..e62c33c2 --- /dev/null +++ b/2022-05/spring-00/architecture-origins/.gitignore @@ -0,0 +1,4 @@ +.idea/ +*.iml + +target/ diff --git a/2022-05/spring-00/architecture-origins/pom.xml b/2022-05/spring-00/architecture-origins/pom.xml new file mode 100644 index 00000000..0890067c --- /dev/null +++ b/2022-05/spring-00/architecture-origins/pom.xml @@ -0,0 +1,25 @@ + + + 4.0.0 + + ru.otus + architecture-origins + 1.0 + + pom + + + solution01 + solution02_codeface + solution03_kiss + solution04_kiss + solution05_dry + solution06_dry + solution07_srp + solution08_srp + solution09_dip + solution10_ocp_isp + + diff --git a/2022-05/spring-00/architecture-origins/solution01/.gitignore b/2022-05/spring-00/architecture-origins/solution01/.gitignore new file mode 100644 index 00000000..e62c33c2 --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution01/.gitignore @@ -0,0 +1,4 @@ +.idea/ +*.iml + +target/ diff --git a/2022-05/spring-00/architecture-origins/solution01/pom.xml b/2022-05/spring-00/architecture-origins/solution01/pom.xml new file mode 100644 index 00000000..c76439cc --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution01/pom.xml @@ -0,0 +1,19 @@ + + + 4.0.0 + + ru.otus + solution01 + 1.0 + + + 11 + 11 + UTF-8 + + + + + diff --git a/2022-05/spring-00/architecture-origins/solution01/src/main/java/ru/otus/Main.java b/2022-05/spring-00/architecture-origins/solution01/src/main/java/ru/otus/Main.java new file mode 100644 index 00000000..45b177a2 --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution01/src/main/java/ru/otus/Main.java @@ -0,0 +1,65 @@ +package ru.otus; + +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.List; +import java.util.Scanner; +import java.util.stream.IntStream; + +public class Main { + + public static void main(String[] args) { + List strings = new ArrayList<>(); + Scanner sc = new Scanner(System.in); + + while (true) { + System.out.println("Выберите одно из следующих действий..."); + System.out.println("1. Вывести все заметки"); + System.out.println("2. Добавить заметку"); + System.out.println("3. Изменить заметку"); + System.out.println("4. Удалить заметку"); + System.out.println("5. Выйти"); + + try { + int i = Integer.parseInt(sc.nextLine()); + + if (i == 1) { + System.out.println("Заметки:"); + IntStream.range(1, strings.size() + 1) + .mapToObj(k -> k + " | " + strings.get(k - 1)) + .forEach(System.out::println); + System.out.println(); + } else if (i == 2) { + System.out.println("Введите текст заметки..."); + String s = sc.nextLine(); + strings.add(LocalDateTime.now() + " | " + s); + } else if (i == 3) { + System.out.println("Введите номер изменяемой заметки..."); + int k = Integer.parseInt(sc.nextLine()); + ; + if (k > 0 && k <= strings.size()) { + System.out.println("Введите текст заметки..."); + String s = sc.nextLine(); + strings.set(k - 1, LocalDateTime.now() + " | " + s); + } else { + System.out.println("Введен несуществующий номер заметки"); + } + } else if (i == 4) { + System.out.println("Введите номер удаляемой заметки..."); + int k = Integer.parseInt(sc.nextLine()); + if (k > 0 && k <= strings.size()) { + strings.remove(k - 1); + } else { + System.out.println("Введен несуществующий номер заметки"); + } + } else if (i == 5) { + break; + } else { + System.out.println("Введен неверный номер опции"); + } + } catch (NumberFormatException e) { + System.out.println("Ошибка при вводе числа"); + } + } + } +} diff --git a/2022-05/spring-00/architecture-origins/solution02_codeface/.gitignore b/2022-05/spring-00/architecture-origins/solution02_codeface/.gitignore new file mode 100644 index 00000000..e62c33c2 --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution02_codeface/.gitignore @@ -0,0 +1,4 @@ +.idea/ +*.iml + +target/ diff --git a/2022-05/spring-00/architecture-origins/solution02_codeface/pom.xml b/2022-05/spring-00/architecture-origins/solution02_codeface/pom.xml new file mode 100644 index 00000000..85e56d77 --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution02_codeface/pom.xml @@ -0,0 +1,19 @@ + + + 4.0.0 + + ru.otus + solution02_codeface + 1.0 + + + 11 + 11 + UTF-8 + + + + + diff --git a/2022-05/spring-00/architecture-origins/solution02_codeface/src/main/java/ru/otus/Main.java b/2022-05/spring-00/architecture-origins/solution02_codeface/src/main/java/ru/otus/Main.java new file mode 100644 index 00000000..ea54bae3 --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution02_codeface/src/main/java/ru/otus/Main.java @@ -0,0 +1,79 @@ +package ru.otus; + +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.List; +import java.util.Scanner; +import java.util.stream.IntStream; + +// Имена переменных, константы, выпрямление кода +public class Main { + + private static final int MENU_OPTION_SHOW_ALL_NOTES = 1; + private static final int MENU_OPTION_ADD_NEW_NOTE = 2; + private static final int MENU_OPTION_UPDATE_NOTE = 3; + private static final int MENU_OPTION_DELETE_NOTE = 4; + private static final int MENU_OPTION_EXIT = 5; + + public static void main(String[] args) { + var notes = new ArrayList(); + var userInput = new Scanner(System.in); + + while (true) { + System.out.println("Выберите одно из следующих действий..."); + System.out.println("1. Вывести все заметки"); + System.out.println("2. Добавить заметку"); + System.out.println("3. Изменить заметку"); + System.out.println("4. Удалить заметку"); + System.out.println("5. Выйти"); + + try { + var selectedOptionNumber = Integer.parseInt(userInput.nextLine()); + + if (selectedOptionNumber == MENU_OPTION_SHOW_ALL_NOTES) { + System.out.println("Заметки:"); + IntStream.range(1, notes.size() + 1) + .mapToObj(k -> k + " | " + notes.get(k - 1)) + .forEach(System.out::println); + System.out.println(); + } else if (selectedOptionNumber == MENU_OPTION_ADD_NEW_NOTE) { + System.out.println("Введите текст заметки..."); + var noteText = userInput.nextLine(); + var finalNoteText = LocalDateTime.now() + " | " + noteText; + notes.add(finalNoteText); + } else if (selectedOptionNumber == MENU_OPTION_UPDATE_NOTE) { + System.out.println("Введите номер изменяемой заметки..."); + + var updatedNoteNumber = Integer.parseInt(userInput.nextLine()); + + if (updatedNoteNumber <= 0 || updatedNoteNumber > notes.size()) { + System.out.println("Введен несуществующий номер заметки"); + continue; + } + + System.out.println("Введите текст заметки..."); + var noteText = userInput.nextLine(); + var finalNoteText = LocalDateTime.now() + " | " + noteText; + notes.set(updatedNoteNumber - 1, finalNoteText); + } else if (selectedOptionNumber == MENU_OPTION_DELETE_NOTE) { + System.out.println("Введите номер удаляемой заметки..."); + + var deletedNoteNumber = Integer.parseInt(userInput.nextLine()); + if (deletedNoteNumber <= 0 || deletedNoteNumber > notes.size()) { + System.out.println("Введен несуществующий номер заметки"); + continue; + } + + notes.remove(deletedNoteNumber - 1); + } else if (selectedOptionNumber == MENU_OPTION_EXIT) { + break; + } else { + System.out.println("Введен неверный номер опции"); + } + } catch (NumberFormatException e) { + System.out.println("Ошибка при вводе числа"); + } + + } + } +} diff --git a/2022-05/spring-00/architecture-origins/solution03_kiss/.gitignore b/2022-05/spring-00/architecture-origins/solution03_kiss/.gitignore new file mode 100644 index 00000000..e62c33c2 --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution03_kiss/.gitignore @@ -0,0 +1,4 @@ +.idea/ +*.iml + +target/ diff --git a/2022-05/spring-00/architecture-origins/solution03_kiss/pom.xml b/2022-05/spring-00/architecture-origins/solution03_kiss/pom.xml new file mode 100644 index 00000000..08d5b82d --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution03_kiss/pom.xml @@ -0,0 +1,19 @@ + + + 4.0.0 + + ru.otus + solution03_kiss + 1.0 + + + 11 + 11 + UTF-8 + + + + + diff --git a/2022-05/spring-00/architecture-origins/solution03_kiss/src/main/java/ru/otus/Main.java b/2022-05/spring-00/architecture-origins/solution03_kiss/src/main/java/ru/otus/Main.java new file mode 100644 index 00000000..5365056a --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution03_kiss/src/main/java/ru/otus/Main.java @@ -0,0 +1,104 @@ +package ru.otus; + +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.List; +import java.util.Scanner; +import java.util.stream.IntStream; + +// Вынос печати меню, чтения пункта меню и выполнения команд в методы. +// - Убрали один уровень вложенности +// - Отделили что делает приложение от того, как оно это делает +public class Main { + + private static final int MENU_OPTION_SHOW_ALL_NOTES = 1; + private static final int MENU_OPTION_ADD_NEW_NOTE = 2; + private static final int MENU_OPTION_UPDATE_NOTE = 3; + private static final int MENU_OPTION_DELETE_NOTE = 4; + private static final int MENU_OPTION_EXIT = 5; + + public static void main(String[] args) { + var notes = new ArrayList(); + var userInput = new Scanner(System.in); + + while (true) { + outputMenu(); + try { + var selectedMenuItem = readSelectedOptionNumberFrom(userInput); + + if (selectedMenuItem == MENU_OPTION_SHOW_ALL_NOTES) { + showAllNotes(notes); + } else if (selectedMenuItem == MENU_OPTION_ADD_NEW_NOTE) { + addNewNote(userInput, notes); + } else if (selectedMenuItem == MENU_OPTION_UPDATE_NOTE) { + updateNote(userInput, notes); + } else if (selectedMenuItem == MENU_OPTION_DELETE_NOTE) { + deleteNote(userInput, notes); + } else if (selectedMenuItem == MENU_OPTION_EXIT){ + break; + } else { + System.out.println("Введен неверный номер опции"); + } + } catch (NumberFormatException e) { + System.out.println("Ошибка при вводе числа"); + } + + } + } + + private static void outputMenu(){ + System.out.println("Выберите одно из следующих действий..."); + System.out.println("1. Вывести все заметки"); + System.out.println("2. Добавить заметку"); + System.out.println("3. Изменить заметку"); + System.out.println("4. Удалить заметку"); + System.out.println("5. Выйти"); + } + + private static int readSelectedOptionNumberFrom(Scanner userInput) { + return Integer.parseInt(userInput.nextLine()); + } + + private static void showAllNotes(List notes) { + System.out.println("Заметки:"); + IntStream.range(1, notes.size() + 1) + .mapToObj(k -> k + " | " + notes.get(k - 1)) + .forEach(System.out::println); + System.out.println(); + } + + private static void addNewNote(Scanner userInput, List notes) { + System.out.println("Введите текст заметки..."); + var noteText = userInput.nextLine(); + var finalNoteText = LocalDateTime.now() + " | " + noteText; + notes.add(finalNoteText); + } + + private static void updateNote(Scanner userInput, List notes) { + System.out.println("Введите номер изменяемой заметки..."); + + var updatedNoteNumber = Integer.parseInt(userInput.nextLine());; + if (updatedNoteNumber <= 0 || updatedNoteNumber > notes.size()) { + System.out.println("Введен несуществующий номер заметки"); + return; + } + + System.out.println("Введите текст заметки..."); + var noteText = userInput.nextLine(); + var finalNoteText = LocalDateTime.now() + " | " + noteText; + notes.set(updatedNoteNumber - 1, finalNoteText); + } + + private static void deleteNote(Scanner userInput, List notes) { + System.out.println("Введите номер удаляемой заметки..."); + + var deletedNoteNumber = Integer.parseInt(userInput.nextLine()); + if (deletedNoteNumber <= 0 || deletedNoteNumber > notes.size()) { + System.out.println("Введен несуществующий номер заметки"); + return; + } + + notes.remove(deletedNoteNumber - 1); + } + +} diff --git a/2022-05/spring-00/architecture-origins/solution04_kiss/.gitignore b/2022-05/spring-00/architecture-origins/solution04_kiss/.gitignore new file mode 100644 index 00000000..e62c33c2 --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution04_kiss/.gitignore @@ -0,0 +1,4 @@ +.idea/ +*.iml + +target/ diff --git a/2022-05/spring-00/architecture-origins/solution04_kiss/pom.xml b/2022-05/spring-00/architecture-origins/solution04_kiss/pom.xml new file mode 100644 index 00000000..7f365752 --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution04_kiss/pom.xml @@ -0,0 +1,19 @@ + + + 4.0.0 + + ru.otus + solution04_kiss + 1.0 + + + 11 + 11 + UTF-8 + + + + + diff --git a/2022-05/spring-00/architecture-origins/solution04_kiss/src/main/java/ru/otus/Main.java b/2022-05/spring-00/architecture-origins/solution04_kiss/src/main/java/ru/otus/Main.java new file mode 100644 index 00000000..9420d5a4 --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution04_kiss/src/main/java/ru/otus/Main.java @@ -0,0 +1,107 @@ +package ru.otus; + +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.List; +import java.util.Scanner; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.stream.IntStream; + +// Уменьшение вложенности в main за счет выноса обработки команд в метод + executionFlag +public class Main { + + private static final int MENU_OPTION_SHOW_ALL_NOTES = 1; + private static final int MENU_OPTION_ADD_NEW_NOTE = 2; + private static final int MENU_OPTION_UPDATE_NOTE = 3; + private static final int MENU_OPTION_DELETE_NOTE = 4; + private static final int MENU_OPTION_EXIT = 5; + + public static void main(String[] args) { + var notes = new ArrayList(); + var userInput = new Scanner(System.in); + + var executionFlag = new AtomicBoolean(true); + while (executionFlag.get()) { + outputMenu(); + try { + var selectedMenuItem = readSelectedOptionNumberFrom(userInput); + processMenuCommand(selectedMenuItem, executionFlag, userInput, notes); + } catch (NumberFormatException e) { + System.out.println("Ошибка при вводе числа"); + } + } + } + + private static void outputMenu(){ + System.out.println("Выберите одно из следующих действий..."); + System.out.println("1. Вывести все заметки"); + System.out.println("2. Добавить заметку"); + System.out.println("3. Изменить заметку"); + System.out.println("4. Удалить заметку"); + System.out.println("5. Выйти"); + } + + private static void processMenuCommand(int selectedMenuItem, AtomicBoolean executionFlag, + Scanner userInput, List notes) { + if (selectedMenuItem == MENU_OPTION_SHOW_ALL_NOTES) { + showAllNotes(notes); + } else if (selectedMenuItem == MENU_OPTION_ADD_NEW_NOTE) { + addNewNote(userInput, notes); + } else if (selectedMenuItem == MENU_OPTION_UPDATE_NOTE) { + updateNote(userInput, notes); + } else if (selectedMenuItem == MENU_OPTION_DELETE_NOTE) { + deleteNote(userInput, notes); + } else if (selectedMenuItem == MENU_OPTION_EXIT){ + executionFlag.set(false); + } else { + System.out.println("Введен неверный номер опции"); + } + } + + private static int readSelectedOptionNumberFrom(Scanner userInput) { + return Integer.parseInt(userInput.nextLine()); + } + + private static void showAllNotes(List notes) { + System.out.println("Заметки:"); + IntStream.range(1, notes.size() + 1) + .mapToObj(k -> k + " | " + notes.get(k - 1)) + .forEach(System.out::println); + System.out.println(); + } + + private static void addNewNote(Scanner userInput, List notes) { + System.out.println("Введите текст заметки..."); + var noteText = userInput.nextLine(); + var finalNoteText = LocalDateTime.now() + " | " + noteText; + notes.add(finalNoteText); + } + + private static void updateNote(Scanner userInput, List notes) { + System.out.println("Введите номер изменяемой заметки..."); + + var updatedNoteNumber = Integer.parseInt(userInput.nextLine());; + if (updatedNoteNumber <= 0 || updatedNoteNumber > notes.size()) { + System.out.println("Введен несуществующий номер заметки"); + return; + } + + System.out.println("Введите текст заметки..."); + var noteText = userInput.nextLine(); + var finalNoteText = LocalDateTime.now() + " | " + noteText; + notes.set(updatedNoteNumber - 1, finalNoteText); + } + + private static void deleteNote(Scanner userInput, List notes) { + System.out.println("Введите номер удаляемой заметки..."); + + var deletedNoteNumber = Integer.parseInt(userInput.nextLine()); + if (deletedNoteNumber <= 0 || deletedNoteNumber > notes.size()) { + System.out.println("Введен несуществующий номер заметки"); + return; + } + + notes.remove(deletedNoteNumber - 1); + } + +} diff --git a/2022-05/spring-00/architecture-origins/solution05_dry/.gitignore b/2022-05/spring-00/architecture-origins/solution05_dry/.gitignore new file mode 100644 index 00000000..e62c33c2 --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution05_dry/.gitignore @@ -0,0 +1,4 @@ +.idea/ +*.iml + +target/ diff --git a/2022-05/spring-00/architecture-origins/solution05_dry/pom.xml b/2022-05/spring-00/architecture-origins/solution05_dry/pom.xml new file mode 100644 index 00000000..1eaafeec --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution05_dry/pom.xml @@ -0,0 +1,19 @@ + + + 4.0.0 + + ru.otus + solution05_dry + 1.0 + + + 11 + 11 + UTF-8 + + + + + diff --git a/2022-05/spring-00/architecture-origins/solution05_dry/src/main/java/ru/otus/Main.java b/2022-05/spring-00/architecture-origins/solution05_dry/src/main/java/ru/otus/Main.java new file mode 100644 index 00000000..bf81db2c --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution05_dry/src/main/java/ru/otus/Main.java @@ -0,0 +1,118 @@ +package ru.otus; + +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.List; +import java.util.Scanner; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.stream.IntStream; + +// Вынос логики ввода-вывода +public class Main { + + private static final int MENU_OPTION_SHOW_ALL_NOTES = 1; + private static final int MENU_OPTION_ADD_NEW_NOTE = 2; + private static final int MENU_OPTION_UPDATE_NOTE = 3; + private static final int MENU_OPTION_DELETE_NOTE = 4; + private static final int MENU_OPTION_EXIT = 5; + + public static void main(String[] args) { + var notes = new ArrayList(); + var userInput = new Scanner(System.in); + + var executionFlag = new AtomicBoolean(true); + while (executionFlag.get()) { + outputMenu(); + try { + var selectedMenuItem = readSelectedOptionNumberFrom(userInput); + processMenuCommand(selectedMenuItem, executionFlag, userInput, notes); + } catch (NumberFormatException e) { + outputString("Ошибка при вводе числа"); + } + } + } + + private static void outputMenu(){ + outputString("Выберите одно из следующих действий..."); + outputString("1. Вывести все заметки"); + outputString("2. Добавить заметку"); + outputString("3. Изменить заметку"); + outputString("4. Удалить заметку"); + outputString("5. Выйти"); + } + + private static void processMenuCommand(int selectedMenuItem, AtomicBoolean executionFlag, + Scanner userInput, List notes) { + if (selectedMenuItem == MENU_OPTION_SHOW_ALL_NOTES) { + showAllNotes(notes); + } else if (selectedMenuItem == MENU_OPTION_ADD_NEW_NOTE) { + addNewNote(userInput, notes); + } else if (selectedMenuItem == MENU_OPTION_UPDATE_NOTE) { + updateNote(userInput, notes); + } else if (selectedMenuItem == MENU_OPTION_DELETE_NOTE) { + deleteNote(userInput, notes); + } else if (selectedMenuItem == MENU_OPTION_EXIT){ + executionFlag.set(false); + } else { + outputString("Введен неверный номер опции"); + } + } + + private static int readSelectedOptionNumberFrom(Scanner userInput) { + return readInt(userInput); + } + + private static void showAllNotes(List notes) { + outputString("Заметки:"); + IntStream.range(1, notes.size() + 1) + .mapToObj(k -> k + " | " + notes.get(k - 1)) + .forEach(Main::outputString); + outputString(""); + } + + private static void addNewNote(Scanner userInput, List notes) { + var noteText = readStringWithPrompt(userInput, "Введите текст заметки..."); + var finalNoteText = LocalDateTime.now() + " | " + noteText; + notes.add(finalNoteText); + } + + private static void updateNote(Scanner userInput, List notes) { + int updatedNoteNumber = readIntWithPrompt(userInput, "Введите номер изменяемой заметки..."); + if (updatedNoteNumber <= 0 || updatedNoteNumber > notes.size()) { + outputString("Введен несуществующий номер заметки"); + return; + } + var noteText = readStringWithPrompt(userInput, "Введите текст заметки..."); + var finalNoteText = LocalDateTime.now() + " | " + noteText; + notes.set(updatedNoteNumber - 1, finalNoteText); + } + + private static void deleteNote(Scanner userInput, List notes) { + var deletedNoteNumber = readIntWithPrompt(userInput, "Введите номер удаляемой заметки..."); + if (deletedNoteNumber <= 0 || deletedNoteNumber > notes.size()) { + outputString("Введен несуществующий номер заметки"); + return; + } + + notes.remove(deletedNoteNumber - 1); + } + + private static void outputString(String s){ + System.out.println(s); + } + + private static int readInt(Scanner userInput){ + return Integer.parseInt(userInput.nextLine()); + } + + private static int readIntWithPrompt(Scanner userInput, String prompt){ + outputString(prompt); + return Integer.parseInt(userInput.nextLine()); + } + + private static String readStringWithPrompt(Scanner userInput, String prompt){ + outputString(prompt); + return userInput.nextLine(); + } + +} diff --git a/2022-05/spring-00/architecture-origins/solution06_dry/.gitignore b/2022-05/spring-00/architecture-origins/solution06_dry/.gitignore new file mode 100644 index 00000000..e62c33c2 --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution06_dry/.gitignore @@ -0,0 +1,4 @@ +.idea/ +*.iml + +target/ diff --git a/2022-05/spring-00/architecture-origins/solution06_dry/pom.xml b/2022-05/spring-00/architecture-origins/solution06_dry/pom.xml new file mode 100644 index 00000000..292cf7ec --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution06_dry/pom.xml @@ -0,0 +1,19 @@ + + + 4.0.0 + + ru.otus + solution06_dry + 1.0 + + + 11 + 11 + UTF-8 + + + + + diff --git a/2022-05/spring-00/architecture-origins/solution06_dry/src/main/java/ru/otus/Main.java b/2022-05/spring-00/architecture-origins/solution06_dry/src/main/java/ru/otus/Main.java new file mode 100644 index 00000000..d652ca12 --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution06_dry/src/main/java/ru/otus/Main.java @@ -0,0 +1,127 @@ +package ru.otus; + +import ru.otus.exceptions.MenuItemIndexOutOfBoundsException; +import ru.otus.exceptions.NoteIndexOutOfBoundsException; + +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.List; +import java.util.Scanner; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.stream.IntStream; + +// Вынос проверки существования выбранной команды в метод checkNoteNumber, +// централизованная обработка ошибок +public class Main { + + private static final int MENU_OPTION_SHOW_ALL_NOTES = 1; + private static final int MENU_OPTION_ADD_NEW_NOTE = 2; + private static final int MENU_OPTION_UPDATE_NOTE = 3; + private static final int MENU_OPTION_DELETE_NOTE = 4; + private static final int MENU_OPTION_EXIT = 5; + + public static void main(String[] args) { + var notes = new ArrayList(); + var userInput = new Scanner(System.in); + + var executionFlag = new AtomicBoolean(true); + while (executionFlag.get()) { + outputMenu(); + try { + var selectedMenuItem = readSelectedOptionNumberFrom(userInput); + processMenuCommand(selectedMenuItem, executionFlag, userInput, notes); + + } catch (NumberFormatException e) { + outputString("Ошибка при вводе числа"); + } catch (MenuItemIndexOutOfBoundsException e) { + outputString("Введен неверный номер опции"); + } catch (NoteIndexOutOfBoundsException e) { + outputString("Введен несуществующий номер заметки"); + } + } + } + + private static void outputMenu(){ + outputString("Выберите одно из следующих действий..."); + outputString("1. Вывести все заметки"); + outputString("2. Добавить заметку"); + outputString("3. Изменить заметку"); + outputString("4. Удалить заметку"); + outputString("5. Выйти"); + } + + private static void processMenuCommand(int selectedMenuItemIndex, AtomicBoolean executionFlag, + Scanner userInput, List notes) { + if (selectedMenuItemIndex == MENU_OPTION_SHOW_ALL_NOTES) { + showAllNotes(notes); + } else if (selectedMenuItemIndex == MENU_OPTION_ADD_NEW_NOTE) { + addNewNote(userInput, notes); + } else if (selectedMenuItemIndex == MENU_OPTION_UPDATE_NOTE) { + updateNote(userInput, notes); + } else if (selectedMenuItemIndex == MENU_OPTION_DELETE_NOTE) { + deleteNote(userInput, notes); + } else if (selectedMenuItemIndex == MENU_OPTION_EXIT){ + executionFlag.set(false); + } else { + throw new MenuItemIndexOutOfBoundsException("Given menu item index is out of range"); + } + } + + private static int readSelectedOptionNumberFrom(Scanner userInput) { + return readInt(userInput); + } + + private static void showAllNotes(List notes) { + outputString("Заметки:"); + IntStream.range(1, notes.size() + 1) + .mapToObj(k -> k + " | " + notes.get(k - 1)) + .forEach(Main::outputString); + outputString(""); + } + + private static void addNewNote(Scanner userInput, List notes) { + var noteText = readStringWithPrompt(userInput, "Введите текст заметки..."); + var finalNoteText = LocalDateTime.now() + " | " + noteText; + notes.add(finalNoteText); + } + + private static void checkNoteNumber(int noteNumber, List notes) { + if (noteNumber <= 0 || noteNumber > notes.size()) { + throw new NoteIndexOutOfBoundsException("Given number of note is out of range"); + } + } + + private static void updateNote(Scanner userInput, List notes) { + var updatedNoteNumber = readIntWithPrompt(userInput, "Введите номер изменяемой заметки..."); + checkNoteNumber(updatedNoteNumber, notes); + + var noteText = readStringWithPrompt(userInput, "Введите текст заметки..."); + var finalNoteText = LocalDateTime.now() + " | " + noteText; + notes.set(updatedNoteNumber - 1, finalNoteText); + } + + private static void deleteNote(Scanner userInput, List notes) { + var deletedNoteNumber = readIntWithPrompt(userInput, "Введите номер удаляемой заметки..."); + checkNoteNumber(deletedNoteNumber, notes); + + notes.remove(deletedNoteNumber - 1); + } + + private static void outputString(String s){ + System.out.println(s); + } + + private static int readInt(Scanner userInput){ + return Integer.parseInt(userInput.nextLine()); + } + + private static int readIntWithPrompt(Scanner userInput, String prompt){ + outputString(prompt); + return Integer.parseInt(userInput.nextLine()); + } + + private static String readStringWithPrompt(Scanner userInput, String prompt){ + outputString(prompt); + return userInput.nextLine(); + } +} diff --git a/2022-05/spring-00/architecture-origins/solution06_dry/src/main/java/ru/otus/exceptions/MenuItemIndexOutOfBoundsException.java b/2022-05/spring-00/architecture-origins/solution06_dry/src/main/java/ru/otus/exceptions/MenuItemIndexOutOfBoundsException.java new file mode 100644 index 00000000..5fa79742 --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution06_dry/src/main/java/ru/otus/exceptions/MenuItemIndexOutOfBoundsException.java @@ -0,0 +1,7 @@ +package ru.otus.exceptions; + +public class MenuItemIndexOutOfBoundsException extends IndexOutOfBoundsException { + public MenuItemIndexOutOfBoundsException(String s) { + super(s); + } +} diff --git a/2022-05/spring-00/architecture-origins/solution06_dry/src/main/java/ru/otus/exceptions/NoteIndexOutOfBoundsException.java b/2022-05/spring-00/architecture-origins/solution06_dry/src/main/java/ru/otus/exceptions/NoteIndexOutOfBoundsException.java new file mode 100644 index 00000000..2c9592f6 --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution06_dry/src/main/java/ru/otus/exceptions/NoteIndexOutOfBoundsException.java @@ -0,0 +1,7 @@ +package ru.otus.exceptions; + +public class NoteIndexOutOfBoundsException extends IndexOutOfBoundsException { + public NoteIndexOutOfBoundsException(String s) { + super(s); + } +} diff --git a/2022-05/spring-00/architecture-origins/solution07_srp/.gitignore b/2022-05/spring-00/architecture-origins/solution07_srp/.gitignore new file mode 100644 index 00000000..e62c33c2 --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution07_srp/.gitignore @@ -0,0 +1,4 @@ +.idea/ +*.iml + +target/ diff --git a/2022-05/spring-00/architecture-origins/solution07_srp/pom.xml b/2022-05/spring-00/architecture-origins/solution07_srp/pom.xml new file mode 100644 index 00000000..4f3ab886 --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution07_srp/pom.xml @@ -0,0 +1,19 @@ + + + 4.0.0 + + ru.otus + solution07_srp + 1.0 + + + 11 + 11 + UTF-8 + + + + + diff --git a/2022-05/spring-00/architecture-origins/solution07_srp/src/main/java/ru/otus/Main.java b/2022-05/spring-00/architecture-origins/solution07_srp/src/main/java/ru/otus/Main.java new file mode 100644 index 00000000..99416733 --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution07_srp/src/main/java/ru/otus/Main.java @@ -0,0 +1,109 @@ +package ru.otus; + +import ru.otus.exceptions.NoteIndexOutOfBoundsException; +import ru.otus.exceptions.MenuItemIndexOutOfBoundsException; +import ru.otus.model.Note; +import ru.otus.services.ConsoleIOService; +import ru.otus.services.NoteConverter; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.stream.IntStream; + +// Note, ConsoleIOService, NoteConverter +public class Main { + + private static final int MENU_OPTION_SHOW_ALL_NOTES = 1; + private static final int MENU_OPTION_ADD_NEW_NOTE = 2; + private static final int MENU_OPTION_UPDATE_NOTE = 3; + private static final int MENU_OPTION_DELETE_NOTE = 4; + private static final int MENU_OPTION_EXIT = 5; + + public static void main(String[] args) { + var notes = new ArrayList(); + var ioService = new ConsoleIOService(); + + var executionFlag = new AtomicBoolean(true); + while (executionFlag.get()) { + outputMenu(ioService); + try { + var selectedMenuItem = readSelectedOptionNumberFrom(ioService); + processMenuCommand(selectedMenuItem, executionFlag, ioService, notes); + + } catch (NumberFormatException e) { + ioService.outputString("Ошибка при вводе числа"); + } catch (MenuItemIndexOutOfBoundsException e) { + ioService.outputString("Введен неверный номер опции"); + } catch (NoteIndexOutOfBoundsException e) { + ioService.outputString("Введен несуществующий номер заметки"); + } + } + } + + private static void outputMenu(ConsoleIOService ioService){ + ioService.outputString("Выберите одно из следующих действий..."); + ioService.outputString("1. Вывести все заметки"); + ioService.outputString("2. Добавить заметку"); + ioService.outputString("3. Изменить заметку"); + ioService.outputString("4. Удалить заметку"); + ioService.outputString("5. Выйти"); + } + + private static void processMenuCommand(int selectedMenuItemIndex, AtomicBoolean executionFlag, + ConsoleIOService ioService, List notes) { + if (selectedMenuItemIndex == MENU_OPTION_SHOW_ALL_NOTES) { + showAllNotes(ioService, notes); + } else if (selectedMenuItemIndex == MENU_OPTION_ADD_NEW_NOTE) { + addNewNote(ioService, notes); + } else if (selectedMenuItemIndex == MENU_OPTION_UPDATE_NOTE) { + updateNote(ioService, notes); + } else if (selectedMenuItemIndex == MENU_OPTION_DELETE_NOTE) { + deleteNote(ioService, notes); + } else if (selectedMenuItemIndex == MENU_OPTION_EXIT){ + executionFlag.set(false); + } else { + throw new MenuItemIndexOutOfBoundsException("Given menu item index is out of range"); + } + } + + private static int readSelectedOptionNumberFrom(ConsoleIOService ioService) { + return ioService.readInt(); + } + + private static void showAllNotes(ConsoleIOService ioService, List notes) { + var noteConverter = new NoteConverter(); + ioService.outputString("Заметки:"); + IntStream.range(1, notes.size() + 1) + .mapToObj(k -> noteConverter.convertNoteToString(k, notes.get(k - 1))) + .forEach(ioService::outputString); + ioService.outputString(""); + } + + private static void addNewNote(ConsoleIOService ioService, List notes) { + var noteText = ioService.readStringWithPrompt("Введите текст заметки..."); + notes.add( Note.of(noteText)); + } + + private static void checkNoteNumber(int noteNumber, List notes) { + if (noteNumber <= 0 || noteNumber > notes.size()) { + throw new NoteIndexOutOfBoundsException("Given number of note is out of range"); + } + } + + private static void updateNote(ConsoleIOService ioService, List notes) { + var updatedNoteNumber = ioService.readIntWithPrompt("Введите номер изменяемой заметки..."); + checkNoteNumber(updatedNoteNumber, notes); + + var noteText = ioService.readStringWithPrompt("Введите текст заметки..."); + notes.set(updatedNoteNumber - 1, Note.of(noteText)); + } + + private static void deleteNote(ConsoleIOService ioService, List notes) { + var deletedNoteNumber = ioService.readIntWithPrompt("Введите номер удаляемой заметки..."); + checkNoteNumber(deletedNoteNumber, notes); + + notes.remove(deletedNoteNumber - 1); + } + +} diff --git a/2022-05/spring-00/architecture-origins/solution07_srp/src/main/java/ru/otus/exceptions/MenuItemIndexOutOfBoundsException.java b/2022-05/spring-00/architecture-origins/solution07_srp/src/main/java/ru/otus/exceptions/MenuItemIndexOutOfBoundsException.java new file mode 100644 index 00000000..5fa79742 --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution07_srp/src/main/java/ru/otus/exceptions/MenuItemIndexOutOfBoundsException.java @@ -0,0 +1,7 @@ +package ru.otus.exceptions; + +public class MenuItemIndexOutOfBoundsException extends IndexOutOfBoundsException { + public MenuItemIndexOutOfBoundsException(String s) { + super(s); + } +} diff --git a/2022-05/spring-00/architecture-origins/solution07_srp/src/main/java/ru/otus/exceptions/NoteIndexOutOfBoundsException.java b/2022-05/spring-00/architecture-origins/solution07_srp/src/main/java/ru/otus/exceptions/NoteIndexOutOfBoundsException.java new file mode 100644 index 00000000..2c9592f6 --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution07_srp/src/main/java/ru/otus/exceptions/NoteIndexOutOfBoundsException.java @@ -0,0 +1,7 @@ +package ru.otus.exceptions; + +public class NoteIndexOutOfBoundsException extends IndexOutOfBoundsException { + public NoteIndexOutOfBoundsException(String s) { + super(s); + } +} diff --git a/2022-05/spring-00/architecture-origins/solution07_srp/src/main/java/ru/otus/model/Note.java b/2022-05/spring-00/architecture-origins/solution07_srp/src/main/java/ru/otus/model/Note.java new file mode 100644 index 00000000..e8dea623 --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution07_srp/src/main/java/ru/otus/model/Note.java @@ -0,0 +1,26 @@ +package ru.otus.model; + +import java.time.LocalDateTime; + +public class Note { + private final LocalDateTime creationTime; + private final String text; + + public Note(String text) { + this.creationTime = LocalDateTime.now(); + this.text = text; + } + + public static Note of(String text) { + return new Note(text); + } + + public LocalDateTime getCreationTime() { + return creationTime; + } + + public String getText() { + return text; + } + +} diff --git a/2022-05/spring-00/architecture-origins/solution07_srp/src/main/java/ru/otus/services/ConsoleIOService.java b/2022-05/spring-00/architecture-origins/solution07_srp/src/main/java/ru/otus/services/ConsoleIOService.java new file mode 100644 index 00000000..bf773074 --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution07_srp/src/main/java/ru/otus/services/ConsoleIOService.java @@ -0,0 +1,29 @@ +package ru.otus.services; + +import java.util.Scanner; + +public class ConsoleIOService { + private final Scanner userInput; + + public ConsoleIOService() { + userInput = new Scanner(System.in); + } + + public void outputString(String s){ + System.out.println(s); + } + + public int readInt(){ + return Integer.parseInt(userInput.nextLine()); + } + + public int readIntWithPrompt(String prompt){ + outputString(prompt); + return Integer.parseInt(userInput.nextLine()); + } + + public String readStringWithPrompt(String prompt){ + outputString(prompt); + return userInput.nextLine(); + } +} diff --git a/2022-05/spring-00/architecture-origins/solution07_srp/src/main/java/ru/otus/services/NoteConverter.java b/2022-05/spring-00/architecture-origins/solution07_srp/src/main/java/ru/otus/services/NoteConverter.java new file mode 100644 index 00000000..d8f8445b --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution07_srp/src/main/java/ru/otus/services/NoteConverter.java @@ -0,0 +1,9 @@ +package ru.otus.services; + +import ru.otus.model.Note; + +public class NoteConverter { + public String convertNoteToString(int noteNumber, Note note) { + return noteNumber + " | " + note.getCreationTime() + " | " + note.getText(); + } +} diff --git a/2022-05/spring-00/architecture-origins/solution08_srp/.gitignore b/2022-05/spring-00/architecture-origins/solution08_srp/.gitignore new file mode 100644 index 00000000..e62c33c2 --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution08_srp/.gitignore @@ -0,0 +1,4 @@ +.idea/ +*.iml + +target/ diff --git a/2022-05/spring-00/architecture-origins/solution08_srp/pom.xml b/2022-05/spring-00/architecture-origins/solution08_srp/pom.xml new file mode 100644 index 00000000..f462ae91 --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution08_srp/pom.xml @@ -0,0 +1,19 @@ + + + 4.0.0 + + ru.otus + solution08_srp + 1.0 + + + 11 + 11 + UTF-8 + + + + + diff --git a/2022-05/spring-00/architecture-origins/solution08_srp/src/main/java/ru/otus/Main.java b/2022-05/spring-00/architecture-origins/solution08_srp/src/main/java/ru/otus/Main.java new file mode 100644 index 00000000..1dd7742a --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution08_srp/src/main/java/ru/otus/Main.java @@ -0,0 +1,10 @@ +package ru.otus; + +import ru.otus.services.ApplicationRunner; + +// ApplicationRunner, MenuCommandsProcessor, NotesService +public class Main { + public static void main(String[] args) { + new ApplicationRunner().run(); + } +} diff --git a/2022-05/spring-00/architecture-origins/solution08_srp/src/main/java/ru/otus/exceptions/MenuItemIndexOutOfBoundsException.java b/2022-05/spring-00/architecture-origins/solution08_srp/src/main/java/ru/otus/exceptions/MenuItemIndexOutOfBoundsException.java new file mode 100644 index 00000000..5fa79742 --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution08_srp/src/main/java/ru/otus/exceptions/MenuItemIndexOutOfBoundsException.java @@ -0,0 +1,7 @@ +package ru.otus.exceptions; + +public class MenuItemIndexOutOfBoundsException extends IndexOutOfBoundsException { + public MenuItemIndexOutOfBoundsException(String s) { + super(s); + } +} diff --git a/2022-05/spring-00/architecture-origins/solution08_srp/src/main/java/ru/otus/exceptions/NoteIndexOutOfBoundsException.java b/2022-05/spring-00/architecture-origins/solution08_srp/src/main/java/ru/otus/exceptions/NoteIndexOutOfBoundsException.java new file mode 100644 index 00000000..2c9592f6 --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution08_srp/src/main/java/ru/otus/exceptions/NoteIndexOutOfBoundsException.java @@ -0,0 +1,7 @@ +package ru.otus.exceptions; + +public class NoteIndexOutOfBoundsException extends IndexOutOfBoundsException { + public NoteIndexOutOfBoundsException(String s) { + super(s); + } +} diff --git a/2022-05/spring-00/architecture-origins/solution08_srp/src/main/java/ru/otus/model/Note.java b/2022-05/spring-00/architecture-origins/solution08_srp/src/main/java/ru/otus/model/Note.java new file mode 100644 index 00000000..10d3b8ee --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution08_srp/src/main/java/ru/otus/model/Note.java @@ -0,0 +1,53 @@ +package ru.otus.model; + +import java.time.LocalDateTime; +import java.util.UUID; + +public class Note { + private final String id; + private final LocalDateTime creationTime; + private final String text; + + public Note(String text) { + this.id = UUID.randomUUID().toString(); + this.creationTime = LocalDateTime.now(); + this.text = text; + } + + public Note(String id, String text) { + this.id = id; + this.creationTime = LocalDateTime.now(); + this.text = text; + } + + public Note(String id, LocalDateTime creationTime, String text) { + this.id = id; + this.creationTime = creationTime; + this.text = text; + } + + public static Note of(String text) { + return new Note(text); + } + + public static Note of(String id, String text) { + return new Note(id, text); + } + + public String getId() { + return id; + } + + public LocalDateTime getCreationTime() { + return creationTime; + } + + public String getText() { + return text; + } + + + public Note copy() { + return new Note(id, creationTime, text); + } +} diff --git a/2022-05/spring-00/architecture-origins/solution08_srp/src/main/java/ru/otus/services/ApplicationRunner.java b/2022-05/spring-00/architecture-origins/solution08_srp/src/main/java/ru/otus/services/ApplicationRunner.java new file mode 100644 index 00000000..21aa98b1 --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution08_srp/src/main/java/ru/otus/services/ApplicationRunner.java @@ -0,0 +1,72 @@ +package ru.otus.services; + +import ru.otus.exceptions.MenuItemIndexOutOfBoundsException; +import ru.otus.exceptions.NoteIndexOutOfBoundsException; + +import java.util.concurrent.atomic.AtomicBoolean; + +public class ApplicationRunner { + private static final int MENU_OPTION_SHOW_ALL_NOTES = 1; + private static final int MENU_OPTION_ADD_NEW_NOTE = 2; + private static final int MENU_OPTION_UPDATE_NOTE = 3; + private static final int MENU_OPTION_DELETE_NOTE = 4; + private static final int MENU_OPTION_EXIT = 5; + + private final ConsoleIOService ioService; + private final AtomicBoolean executionFlag; + private final MenuCommandsProcessor commandsProcessor; + + + public ApplicationRunner() { + ioService = new ConsoleIOService(); + executionFlag = new AtomicBoolean(true); + commandsProcessor = new MenuCommandsProcessor(); + + } + + public void run() { + while (executionFlag.get()) { + outputMenu(); + try { + var selectedMenuItem = readSelectedOptionNumber(); + processMenuCommand(selectedMenuItem); + + } catch (NumberFormatException e) { + ioService.outputString("Ошибка при вводе числа"); + } catch (MenuItemIndexOutOfBoundsException e) { + ioService.outputString("Введен неверный номер опции"); + } catch (NoteIndexOutOfBoundsException e) { + ioService.outputString("Введен несуществующий номер заметки"); + } + } + } + + private void outputMenu(){ + ioService.outputString("Выберите одно из следующих действий..."); + ioService.outputString("1. Вывести все заметки"); + ioService.outputString("2. Добавить заметку"); + ioService.outputString("3. Изменить заметку"); + ioService.outputString("4. Удалить заметку"); + ioService.outputString("5. Выйти"); + } + + private void processMenuCommand(int selectedMenuItemIndex) { + if (selectedMenuItemIndex == MENU_OPTION_SHOW_ALL_NOTES) { + commandsProcessor.showAllNotes(ioService); + } else if (selectedMenuItemIndex == MENU_OPTION_ADD_NEW_NOTE) { + commandsProcessor.addNewNote(ioService); + } else if (selectedMenuItemIndex == MENU_OPTION_UPDATE_NOTE) { + commandsProcessor.updateNote(ioService); + } else if (selectedMenuItemIndex == MENU_OPTION_DELETE_NOTE) { + commandsProcessor.deleteNote(ioService); + } else if (selectedMenuItemIndex == MENU_OPTION_EXIT){ + executionFlag.set(false); + } else { + throw new MenuItemIndexOutOfBoundsException("Given menu item index is out of range"); + } + } + + private int readSelectedOptionNumber() { + return ioService.readInt(); + } +} diff --git a/2022-05/spring-00/architecture-origins/solution08_srp/src/main/java/ru/otus/services/ConsoleIOService.java b/2022-05/spring-00/architecture-origins/solution08_srp/src/main/java/ru/otus/services/ConsoleIOService.java new file mode 100644 index 00000000..bf773074 --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution08_srp/src/main/java/ru/otus/services/ConsoleIOService.java @@ -0,0 +1,29 @@ +package ru.otus.services; + +import java.util.Scanner; + +public class ConsoleIOService { + private final Scanner userInput; + + public ConsoleIOService() { + userInput = new Scanner(System.in); + } + + public void outputString(String s){ + System.out.println(s); + } + + public int readInt(){ + return Integer.parseInt(userInput.nextLine()); + } + + public int readIntWithPrompt(String prompt){ + outputString(prompt); + return Integer.parseInt(userInput.nextLine()); + } + + public String readStringWithPrompt(String prompt){ + outputString(prompt); + return userInput.nextLine(); + } +} diff --git a/2022-05/spring-00/architecture-origins/solution08_srp/src/main/java/ru/otus/services/MenuCommandsProcessor.java b/2022-05/spring-00/architecture-origins/solution08_srp/src/main/java/ru/otus/services/MenuCommandsProcessor.java new file mode 100644 index 00000000..b9541d8b --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution08_srp/src/main/java/ru/otus/services/MenuCommandsProcessor.java @@ -0,0 +1,58 @@ +package ru.otus.services; + +import ru.otus.model.Note; +import ru.otus.exceptions.NoteIndexOutOfBoundsException; + +import java.util.stream.IntStream; + +public class MenuCommandsProcessor { + private final NotesService notesService; + + public MenuCommandsProcessor() { + notesService = new NotesService(); + } + + public void showAllNotes(ConsoleIOService ioService) { + var noteConverter = new NoteConverter(); + var notes = notesService.getAll(); + ioService.outputString("Заметки:"); + IntStream.range(1, notes.size() + 1) + .mapToObj(k -> noteConverter.convertNoteToString(k, notes.get(k - 1))) + .forEach(ioService::outputString); + ioService.outputString(""); + } + + public void addNewNote(ConsoleIOService ioService) { + var noteText = ioService.readStringWithPrompt("Введите текст заметки..."); + notesService.save(Note.of(noteText)); + } + + public void updateNote(ConsoleIOService ioService) { + var notes = notesService.getAll(); + + var updatedNoteNumber = ioService.readIntWithPrompt("Введите номер изменяемой заметки..."); + checkNoteNumber(updatedNoteNumber, notes.size()); + + var noteText = ioService.readStringWithPrompt("Введите текст заметки..."); + + var updatedNote = notes.get(updatedNoteNumber - 1); + notesService.save(Note.of(updatedNote.getId(), noteText)); + } + + public void deleteNote(ConsoleIOService ioService) { + var notes = notesService.getAll(); + + var deletedNoteNumber = ioService.readIntWithPrompt("Введите номер удаляемой заметки..."); + checkNoteNumber(deletedNoteNumber, notes.size()); + + var updatedNote = notes.get(deletedNoteNumber - 1); + notesService.remove(updatedNote.getId()); + } + + private static void checkNoteNumber(int noteNumber, int notesCount) { + if (noteNumber <= 0 || noteNumber > notesCount) { + throw new NoteIndexOutOfBoundsException("Given number of note is out of range"); + } + } + +} diff --git a/2022-05/spring-00/architecture-origins/solution08_srp/src/main/java/ru/otus/services/NoteConverter.java b/2022-05/spring-00/architecture-origins/solution08_srp/src/main/java/ru/otus/services/NoteConverter.java new file mode 100644 index 00000000..d8f8445b --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution08_srp/src/main/java/ru/otus/services/NoteConverter.java @@ -0,0 +1,9 @@ +package ru.otus.services; + +import ru.otus.model.Note; + +public class NoteConverter { + public String convertNoteToString(int noteNumber, Note note) { + return noteNumber + " | " + note.getCreationTime() + " | " + note.getText(); + } +} diff --git a/2022-05/spring-00/architecture-origins/solution08_srp/src/main/java/ru/otus/services/NotesService.java b/2022-05/spring-00/architecture-origins/solution08_srp/src/main/java/ru/otus/services/NotesService.java new file mode 100644 index 00000000..8d899f25 --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution08_srp/src/main/java/ru/otus/services/NotesService.java @@ -0,0 +1,26 @@ +package ru.otus.services; + +import ru.otus.model.Note; + +import java.util.*; +import java.util.stream.Collectors; + +public class NotesService { + private final Map notes; + + public NotesService() { + notes = new HashMap<>(); + } + + public List getAll() { + return notes.values().stream().map(Note::copy).collect(Collectors.toList()); + } + + public void save(Note note) { + notes.put(note.getId(), note); + } + + public void remove(String id) { + notes.remove(id); + } +} diff --git a/2022-05/spring-00/architecture-origins/solution09_dip/.gitignore b/2022-05/spring-00/architecture-origins/solution09_dip/.gitignore new file mode 100644 index 00000000..e62c33c2 --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution09_dip/.gitignore @@ -0,0 +1,4 @@ +.idea/ +*.iml + +target/ diff --git a/2022-05/spring-00/architecture-origins/solution09_dip/pom.xml b/2022-05/spring-00/architecture-origins/solution09_dip/pom.xml new file mode 100644 index 00000000..2e3b18f9 --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution09_dip/pom.xml @@ -0,0 +1,19 @@ + + + 4.0.0 + + ru.otus + solution09_dip + 1.0 + + + 11 + 11 + UTF-8 + + + + + diff --git a/2022-05/spring-00/architecture-origins/solution09_dip/src/main/java/ru/otus/Main.java b/2022-05/spring-00/architecture-origins/solution09_dip/src/main/java/ru/otus/Main.java new file mode 100644 index 00000000..a27f1448 --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution09_dip/src/main/java/ru/otus/Main.java @@ -0,0 +1,20 @@ +package ru.otus; + +import ru.otus.config.AppSettings; +import ru.otus.services.*; + +// +AppSettings, +ApplicationStopService, IOService стал Streams, методы MenuCommandsProcessor очистились от IOService +public class Main { + public static void main(String[] args) { + var appSettings = new AppSettings(true, "dd.mm.YYYY HH:mm:ss"); + var ioService = new IOServiceStreams(System.out, System.in); + var applicationStopService = new ApplicationStopServiceImpl(ioService, appSettings); + var notesService = new NotesServiceImpl(); + var noteConverter = new NoteConverterImpl(appSettings); + var menuCommandsProcessor = new MenuCommandsProcessorImpl(ioService, notesService, + noteConverter, applicationStopService); + + new ApplicationRunner(ioService, applicationStopService, menuCommandsProcessor) + .run(); + } +} diff --git a/2022-05/spring-00/architecture-origins/solution09_dip/src/main/java/ru/otus/config/AppSettings.java b/2022-05/spring-00/architecture-origins/solution09_dip/src/main/java/ru/otus/config/AppSettings.java new file mode 100644 index 00000000..b2344ece --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution09_dip/src/main/java/ru/otus/config/AppSettings.java @@ -0,0 +1,19 @@ +package ru.otus.config; + +public class AppSettings { + private final boolean confirmExit; + private final String dateTimeFormat; + + public AppSettings(boolean confirmExit, String dateTimeFormat) { + this.confirmExit = confirmExit; + this.dateTimeFormat = dateTimeFormat; + } + + public boolean isConfirmExit() { + return confirmExit; + } + + public String getDateTimeFormat() { + return dateTimeFormat; + } +} diff --git a/2022-05/spring-00/architecture-origins/solution09_dip/src/main/java/ru/otus/exceptions/MenuItemIndexOutOfBoundsException.java b/2022-05/spring-00/architecture-origins/solution09_dip/src/main/java/ru/otus/exceptions/MenuItemIndexOutOfBoundsException.java new file mode 100644 index 00000000..5fa79742 --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution09_dip/src/main/java/ru/otus/exceptions/MenuItemIndexOutOfBoundsException.java @@ -0,0 +1,7 @@ +package ru.otus.exceptions; + +public class MenuItemIndexOutOfBoundsException extends IndexOutOfBoundsException { + public MenuItemIndexOutOfBoundsException(String s) { + super(s); + } +} diff --git a/2022-05/spring-00/architecture-origins/solution09_dip/src/main/java/ru/otus/exceptions/NoteIndexOutOfBoundsException.java b/2022-05/spring-00/architecture-origins/solution09_dip/src/main/java/ru/otus/exceptions/NoteIndexOutOfBoundsException.java new file mode 100644 index 00000000..2c9592f6 --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution09_dip/src/main/java/ru/otus/exceptions/NoteIndexOutOfBoundsException.java @@ -0,0 +1,7 @@ +package ru.otus.exceptions; + +public class NoteIndexOutOfBoundsException extends IndexOutOfBoundsException { + public NoteIndexOutOfBoundsException(String s) { + super(s); + } +} diff --git a/2022-05/spring-00/architecture-origins/solution09_dip/src/main/java/ru/otus/model/Note.java b/2022-05/spring-00/architecture-origins/solution09_dip/src/main/java/ru/otus/model/Note.java new file mode 100644 index 00000000..10d3b8ee --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution09_dip/src/main/java/ru/otus/model/Note.java @@ -0,0 +1,53 @@ +package ru.otus.model; + +import java.time.LocalDateTime; +import java.util.UUID; + +public class Note { + private final String id; + private final LocalDateTime creationTime; + private final String text; + + public Note(String text) { + this.id = UUID.randomUUID().toString(); + this.creationTime = LocalDateTime.now(); + this.text = text; + } + + public Note(String id, String text) { + this.id = id; + this.creationTime = LocalDateTime.now(); + this.text = text; + } + + public Note(String id, LocalDateTime creationTime, String text) { + this.id = id; + this.creationTime = creationTime; + this.text = text; + } + + public static Note of(String text) { + return new Note(text); + } + + public static Note of(String id, String text) { + return new Note(id, text); + } + + public String getId() { + return id; + } + + public LocalDateTime getCreationTime() { + return creationTime; + } + + public String getText() { + return text; + } + + + public Note copy() { + return new Note(id, creationTime, text); + } +} diff --git a/2022-05/spring-00/architecture-origins/solution09_dip/src/main/java/ru/otus/services/ApplicationRunner.java b/2022-05/spring-00/architecture-origins/solution09_dip/src/main/java/ru/otus/services/ApplicationRunner.java new file mode 100644 index 00000000..e10ac8c9 --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution09_dip/src/main/java/ru/otus/services/ApplicationRunner.java @@ -0,0 +1,71 @@ +package ru.otus.services; + +import ru.otus.exceptions.MenuItemIndexOutOfBoundsException; +import ru.otus.exceptions.NoteIndexOutOfBoundsException; + +public class ApplicationRunner { + private static final int MENU_OPTION_SHOW_ALL_NOTES = 1; + private static final int MENU_OPTION_ADD_NEW_NOTE = 2; + private static final int MENU_OPTION_UPDATE_NOTE = 3; + private static final int MENU_OPTION_DELETE_NOTE = 4; + private static final int MENU_OPTION_EXIT = 5; + + private final IOService ioService; + private final ApplicationStopService applicationStopService; + private final MenuCommandsProcessor commandsProcessor; + + + public ApplicationRunner(IOService ioService, + ApplicationStopService applicationStopService, + MenuCommandsProcessor commandsProcessor) { + this.ioService = ioService; + this.applicationStopService = applicationStopService; + this.commandsProcessor = commandsProcessor; + } + + public void run() { + while (applicationStopService.isApplicationRunning()) { + outputMenu(); + try { + var selectedMenuItem = readSelectedOptionNumber(); + processMenuCommand(selectedMenuItem); + + } catch (NumberFormatException e) { + ioService.outputString("Ошибка при вводе числа"); + } catch (MenuItemIndexOutOfBoundsException e) { + ioService.outputString("Введен неверный номер опции"); + } catch (NoteIndexOutOfBoundsException e) { + ioService.outputString("Введен несуществующий номер заметки"); + } + } + } + + private void outputMenu(){ + ioService.outputString("Выберите одно из следующих действий..."); + ioService.outputString("1. Вывести все заметки"); + ioService.outputString("2. Добавить заметку"); + ioService.outputString("3. Изменить заметку"); + ioService.outputString("4. Удалить заметку"); + ioService.outputString("5. Выйти"); + } + + private void processMenuCommand(int selectedMenuItemIndex) { + if (selectedMenuItemIndex == MENU_OPTION_SHOW_ALL_NOTES) { + commandsProcessor.showAllNotes(); + } else if (selectedMenuItemIndex == MENU_OPTION_ADD_NEW_NOTE) { + commandsProcessor.addNewNote(); + } else if (selectedMenuItemIndex == MENU_OPTION_UPDATE_NOTE) { + commandsProcessor.updateNote(); + } else if (selectedMenuItemIndex == MENU_OPTION_DELETE_NOTE) { + commandsProcessor.deleteNote(); + } else if (selectedMenuItemIndex == MENU_OPTION_EXIT){ + commandsProcessor.stopApplication(); + } else { + throw new MenuItemIndexOutOfBoundsException("Given menu item index is out of range"); + } + } + + private int readSelectedOptionNumber() { + return ioService.readInt(); + } +} diff --git a/2022-05/spring-00/architecture-origins/solution09_dip/src/main/java/ru/otus/services/ApplicationStopService.java b/2022-05/spring-00/architecture-origins/solution09_dip/src/main/java/ru/otus/services/ApplicationStopService.java new file mode 100644 index 00000000..31d612f9 --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution09_dip/src/main/java/ru/otus/services/ApplicationStopService.java @@ -0,0 +1,6 @@ +package ru.otus.services; + +public interface ApplicationStopService { + boolean isApplicationRunning(); + void stopApplication(); +} diff --git a/2022-05/spring-00/architecture-origins/solution09_dip/src/main/java/ru/otus/services/ApplicationStopServiceImpl.java b/2022-05/spring-00/architecture-origins/solution09_dip/src/main/java/ru/otus/services/ApplicationStopServiceImpl.java new file mode 100644 index 00000000..4a99b272 --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution09_dip/src/main/java/ru/otus/services/ApplicationStopServiceImpl.java @@ -0,0 +1,34 @@ +package ru.otus.services; + +import ru.otus.config.AppSettings; + +import java.util.concurrent.atomic.AtomicBoolean; + +public class ApplicationStopServiceImpl implements ApplicationStopService { + + private final IOService ioService; + private final AppSettings appSettings; + private final AtomicBoolean executionFlag; + + public ApplicationStopServiceImpl(IOService ioService, AppSettings appSettings) { + this.ioService = ioService; + this.appSettings = appSettings; + this.executionFlag = new AtomicBoolean(true); + } + + @Override + public boolean isApplicationRunning() { + return executionFlag.get(); + } + + @Override + public void stopApplication() { + if (appSettings.isConfirmExit()) { + var exitConfirmation = ioService.readStringWithPrompt("Действительно выйти? (да/нет)"); + if (exitConfirmation.equalsIgnoreCase("нет")) { + return; + } + } + executionFlag.set(false); + } +} diff --git a/2022-05/spring-00/architecture-origins/solution09_dip/src/main/java/ru/otus/services/IOService.java b/2022-05/spring-00/architecture-origins/solution09_dip/src/main/java/ru/otus/services/IOService.java new file mode 100644 index 00000000..5247912b --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution09_dip/src/main/java/ru/otus/services/IOService.java @@ -0,0 +1,11 @@ +package ru.otus.services; + +public interface IOService { + void outputString(String s); + + int readInt(); + + int readIntWithPrompt(String prompt); + + String readStringWithPrompt(String prompt); +} diff --git a/2022-05/spring-00/architecture-origins/solution09_dip/src/main/java/ru/otus/services/IOServiceStreams.java b/2022-05/spring-00/architecture-origins/solution09_dip/src/main/java/ru/otus/services/IOServiceStreams.java new file mode 100644 index 00000000..ca7dff21 --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution09_dip/src/main/java/ru/otus/services/IOServiceStreams.java @@ -0,0 +1,37 @@ +package ru.otus.services; + +import java.io.InputStream; +import java.io.PrintStream; +import java.util.Scanner; + +public class IOServiceStreams implements IOService { + private final PrintStream output; + private final Scanner input; + + public IOServiceStreams(PrintStream outputStream, InputStream inputStream) { + output = outputStream; + input = new Scanner(inputStream); + } + + @Override + public void outputString(String s){ + output.println(s); + } + + @Override + public int readInt(){ + return Integer.parseInt(input.nextLine()); + } + + @Override + public int readIntWithPrompt(String prompt){ + outputString(prompt); + return Integer.parseInt(input.nextLine()); + } + + @Override + public String readStringWithPrompt(String prompt){ + outputString(prompt); + return input.nextLine(); + } +} diff --git a/2022-05/spring-00/architecture-origins/solution09_dip/src/main/java/ru/otus/services/MenuCommandsProcessor.java b/2022-05/spring-00/architecture-origins/solution09_dip/src/main/java/ru/otus/services/MenuCommandsProcessor.java new file mode 100644 index 00000000..3ce09c81 --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution09_dip/src/main/java/ru/otus/services/MenuCommandsProcessor.java @@ -0,0 +1,13 @@ +package ru.otus.services; + +public interface MenuCommandsProcessor { + void showAllNotes(); + + void addNewNote(); + + void updateNote(); + + void deleteNote(); + + void stopApplication(); +} diff --git a/2022-05/spring-00/architecture-origins/solution09_dip/src/main/java/ru/otus/services/MenuCommandsProcessorImpl.java b/2022-05/spring-00/architecture-origins/solution09_dip/src/main/java/ru/otus/services/MenuCommandsProcessorImpl.java new file mode 100644 index 00000000..374e472e --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution09_dip/src/main/java/ru/otus/services/MenuCommandsProcessorImpl.java @@ -0,0 +1,74 @@ +package ru.otus.services; + +import ru.otus.model.Note; +import ru.otus.exceptions.NoteIndexOutOfBoundsException; + +import java.util.stream.IntStream; + +public class MenuCommandsProcessorImpl implements MenuCommandsProcessor { + private final IOService ioService; + private final NotesService notesService; + private final NoteConverter noteConverter; + private final ApplicationStopService applicationStopService; + + public MenuCommandsProcessorImpl(IOService ioService, NotesService notesService, + NoteConverter noteConverter, + ApplicationStopService applicationStopService) { + this.ioService = ioService; + this.notesService = notesService; + this.noteConverter = noteConverter; + this.applicationStopService = applicationStopService; + } + + @Override + public void showAllNotes() { + var notes = notesService.getAll(); + ioService.outputString("Заметки:"); + IntStream.range(1, notes.size() + 1) + .mapToObj(k -> noteConverter.convertNoteToString(k, notes.get(k - 1))) + .forEach(ioService::outputString); + ioService.outputString(""); + } + + @Override + public void addNewNote() { + var noteText = ioService.readStringWithPrompt("Введите текст заметки..."); + notesService.save(Note.of(noteText)); + } + + @Override + public void updateNote() { + var notes = notesService.getAll(); + + var updatedNoteNumber = ioService.readIntWithPrompt("Введите номер изменяемой заметки..."); + checkNoteNumber(updatedNoteNumber, notes.size()); + + var noteText = ioService.readStringWithPrompt("Введите текст заметки..."); + + var updatedNote = notes.get(updatedNoteNumber - 1); + notesService.save(Note.of(updatedNote.getId(), noteText)); + } + + @Override + public void deleteNote() { + var notes = notesService.getAll(); + + var deletedNoteNumber = ioService.readIntWithPrompt("Введите номер удаляемой заметки..."); + checkNoteNumber(deletedNoteNumber, notes.size()); + + var updatedNote = notes.get(deletedNoteNumber - 1); + notesService.remove(updatedNote.getId()); + } + + @Override + public void stopApplication() { + applicationStopService.stopApplication(); + } + + private static void checkNoteNumber(int noteNumber, int notesCount) { + if (noteNumber <= 0 || noteNumber > notesCount) { + throw new NoteIndexOutOfBoundsException("Given number of note is out of range"); + } + } + +} diff --git a/2022-05/spring-00/architecture-origins/solution09_dip/src/main/java/ru/otus/services/NoteConverter.java b/2022-05/spring-00/architecture-origins/solution09_dip/src/main/java/ru/otus/services/NoteConverter.java new file mode 100644 index 00000000..7dfe1e57 --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution09_dip/src/main/java/ru/otus/services/NoteConverter.java @@ -0,0 +1,7 @@ +package ru.otus.services; + +import ru.otus.model.Note; + +public interface NoteConverter { + String convertNoteToString(int noteNumber, Note note); +} diff --git a/2022-05/spring-00/architecture-origins/solution09_dip/src/main/java/ru/otus/services/NoteConverterImpl.java b/2022-05/spring-00/architecture-origins/solution09_dip/src/main/java/ru/otus/services/NoteConverterImpl.java new file mode 100644 index 00000000..1b351c82 --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution09_dip/src/main/java/ru/otus/services/NoteConverterImpl.java @@ -0,0 +1,21 @@ +package ru.otus.services; + +import ru.otus.config.AppSettings; +import ru.otus.model.Note; + + +import java.time.format.DateTimeFormatter; + +public class NoteConverterImpl implements NoteConverter { + private final AppSettings appSettings; + + public NoteConverterImpl(AppSettings appSettings) { + this.appSettings = appSettings; + } + + @Override + public String convertNoteToString(int noteNumber, Note note) { + var dateTimeFormatter = DateTimeFormatter.ofPattern(appSettings.getDateTimeFormat()); + return noteNumber + " | " + dateTimeFormatter.format(note.getCreationTime()) + " | " + note.getText(); + } +} diff --git a/2022-05/spring-00/architecture-origins/solution09_dip/src/main/java/ru/otus/services/NotesService.java b/2022-05/spring-00/architecture-origins/solution09_dip/src/main/java/ru/otus/services/NotesService.java new file mode 100644 index 00000000..019c6cd7 --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution09_dip/src/main/java/ru/otus/services/NotesService.java @@ -0,0 +1,13 @@ +package ru.otus.services; + +import ru.otus.model.Note; + +import java.util.List; + +public interface NotesService { + List getAll(); + + void save(Note note); + + void remove(String id); +} diff --git a/2022-05/spring-00/architecture-origins/solution09_dip/src/main/java/ru/otus/services/NotesServiceImpl.java b/2022-05/spring-00/architecture-origins/solution09_dip/src/main/java/ru/otus/services/NotesServiceImpl.java new file mode 100644 index 00000000..b8c15298 --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution09_dip/src/main/java/ru/otus/services/NotesServiceImpl.java @@ -0,0 +1,31 @@ +package ru.otus.services; + +import ru.otus.model.Note; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +public class NotesServiceImpl implements NotesService { + private final Map notes; + + public NotesServiceImpl() { + notes = new HashMap<>(); + } + + @Override + public List getAll() { + return notes.values().stream().map(Note::copy).collect(Collectors.toList()); + } + + @Override + public void save(Note note) { + notes.put(note.getId(), note); + } + + @Override + public void remove(String id) { + notes.remove(id); + } +} diff --git a/2022-05/spring-00/architecture-origins/solution10_ocp_isp/.gitignore b/2022-05/spring-00/architecture-origins/solution10_ocp_isp/.gitignore new file mode 100644 index 00000000..e62c33c2 --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution10_ocp_isp/.gitignore @@ -0,0 +1,4 @@ +.idea/ +*.iml + +target/ diff --git a/2022-05/spring-00/architecture-origins/solution10_ocp_isp/pom.xml b/2022-05/spring-00/architecture-origins/solution10_ocp_isp/pom.xml new file mode 100644 index 00000000..3ce8c35e --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution10_ocp_isp/pom.xml @@ -0,0 +1,65 @@ + + + 4.0.0 + + ru.otus + solution10_ocp_isp + 1.0 + + + 11 + 11 + UTF-8 + 5.8.2 + 4.1.0 + 3.21.0 + + + + + org.junit.jupiter + junit-jupiter-api + ${junit.jupiter.version} + test + + + + org.junit.jupiter + junit-jupiter-engine + ${junit.jupiter.version} + test + + + + org.junit.jupiter + junit-jupiter-params + ${junit.jupiter.version} + test + + + + + org.mockito + mockito-core + ${mockito.version} + test + + + + org.mockito + mockito-junit-jupiter + ${mockito.version} + test + + + + + org.assertj + assertj-core + ${assertj.version} + test + + + diff --git a/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/Main.java b/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/Main.java new file mode 100644 index 00000000..46efea5d --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/Main.java @@ -0,0 +1,46 @@ +package ru.otus; + +import ru.otus.config.AppSettings; +import ru.otus.services.*; +import ru.otus.services.processors.*; +import ru.otus.services.menu.MenuOption; +import ru.otus.services.menu.MenuOptionsRegistryImpl; + + +import java.util.List; + +// OCP + ISP (AppSettings + IOService) + тесты +public class Main { + + public static void main(String[] args) { + var appSettings = new AppSettings(true, "dd.mm.YYYY HH:mm:ss"); + var ioService = new IOServiceStreams(System.out, System.in); + var applicationStopService = new ApplicationStopServiceImpl(ioService, appSettings); + var notesService = new NotesServiceImpl(); + var noteConverter = new NoteConverterImpl(appSettings); + + var showAllNotesMenuOption = new MenuOption(1, "Вывести все заметки"); + var addNewNoteMenuOption = new MenuOption(2, "Добавить заметку"); + var updateNoteMenuOption = new MenuOption(3, "Изменить заметку"); + var deleteNoteMenuOption = new MenuOption(4, "Удалить заметку"); + var stopApplicationMenuOption = new MenuOption(5, "Выйти"); + + var menuOptions = List.of(showAllNotesMenuOption, addNewNoteMenuOption, + updateNoteMenuOption, deleteNoteMenuOption, stopApplicationMenuOption + ); + var menuOptionsRegistry = new MenuOptionsRegistryImpl(menuOptions); + + var processors = List.of( + new ShowAllNotesSingleCommandProcessor(ioService, notesService, noteConverter, showAllNotesMenuOption), + new AddNewNoteSingleCommandProcessor(ioService, notesService, addNewNoteMenuOption), + new UpdateNoteSingleCommandProcessor(ioService, notesService, updateNoteMenuOption), + new DeleteNoteSingleCommandProcessor(ioService, notesService, deleteNoteMenuOption), + new StopApplicationSingleCommandProcessor(applicationStopService, stopApplicationMenuOption) + ); + + var menuCommandsProcessor = new MenuCommandsProcessorImpl(processors); + + new ApplicationRunner(ioService, applicationStopService, menuOptionsRegistry, menuCommandsProcessor) + .run(); + } +} diff --git a/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/config/AppSettings.java b/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/config/AppSettings.java new file mode 100644 index 00000000..15d18038 --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/config/AppSettings.java @@ -0,0 +1,21 @@ +package ru.otus.config; + +public class AppSettings implements DateTimeFormatProvider, ApplicationStopServiceSettingsProvider{ + private final boolean confirmExit; + private final String dateTimeFormat; + + public AppSettings(boolean confirmExit, String dateTimeFormat) { + this.confirmExit = confirmExit; + this.dateTimeFormat = dateTimeFormat; + } + + @Override + public boolean isConfirmExit() { + return confirmExit; + } + + @Override + public String getDateTimeFormat() { + return dateTimeFormat; + } +} diff --git a/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/config/ApplicationStopServiceSettingsProvider.java b/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/config/ApplicationStopServiceSettingsProvider.java new file mode 100644 index 00000000..fe5d2ed7 --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/config/ApplicationStopServiceSettingsProvider.java @@ -0,0 +1,5 @@ +package ru.otus.config; + +public interface ApplicationStopServiceSettingsProvider { + boolean isConfirmExit(); +} diff --git a/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/config/DateTimeFormatProvider.java b/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/config/DateTimeFormatProvider.java new file mode 100644 index 00000000..9f864dc7 --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/config/DateTimeFormatProvider.java @@ -0,0 +1,5 @@ +package ru.otus.config; + +public interface DateTimeFormatProvider { + String getDateTimeFormat(); +} diff --git a/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/exceptions/MenuCommandProcessorNotFound.java b/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/exceptions/MenuCommandProcessorNotFound.java new file mode 100644 index 00000000..b9b89316 --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/exceptions/MenuCommandProcessorNotFound.java @@ -0,0 +1,7 @@ +package ru.otus.exceptions; + +public class MenuCommandProcessorNotFound extends RuntimeException { + public MenuCommandProcessorNotFound(String message) { + super(message); + } +} diff --git a/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/exceptions/MenuItemIndexOutOfBoundsException.java b/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/exceptions/MenuItemIndexOutOfBoundsException.java new file mode 100644 index 00000000..5fa79742 --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/exceptions/MenuItemIndexOutOfBoundsException.java @@ -0,0 +1,7 @@ +package ru.otus.exceptions; + +public class MenuItemIndexOutOfBoundsException extends IndexOutOfBoundsException { + public MenuItemIndexOutOfBoundsException(String s) { + super(s); + } +} diff --git a/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/exceptions/NoteIndexOutOfBoundsException.java b/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/exceptions/NoteIndexOutOfBoundsException.java new file mode 100644 index 00000000..2c9592f6 --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/exceptions/NoteIndexOutOfBoundsException.java @@ -0,0 +1,7 @@ +package ru.otus.exceptions; + +public class NoteIndexOutOfBoundsException extends IndexOutOfBoundsException { + public NoteIndexOutOfBoundsException(String s) { + super(s); + } +} diff --git a/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/model/Note.java b/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/model/Note.java new file mode 100644 index 00000000..10d3b8ee --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/model/Note.java @@ -0,0 +1,53 @@ +package ru.otus.model; + +import java.time.LocalDateTime; +import java.util.UUID; + +public class Note { + private final String id; + private final LocalDateTime creationTime; + private final String text; + + public Note(String text) { + this.id = UUID.randomUUID().toString(); + this.creationTime = LocalDateTime.now(); + this.text = text; + } + + public Note(String id, String text) { + this.id = id; + this.creationTime = LocalDateTime.now(); + this.text = text; + } + + public Note(String id, LocalDateTime creationTime, String text) { + this.id = id; + this.creationTime = creationTime; + this.text = text; + } + + public static Note of(String text) { + return new Note(text); + } + + public static Note of(String id, String text) { + return new Note(id, text); + } + + public String getId() { + return id; + } + + public LocalDateTime getCreationTime() { + return creationTime; + } + + public String getText() { + return text; + } + + + public Note copy() { + return new Note(id, creationTime, text); + } +} diff --git a/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/services/ApplicationRunner.java b/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/services/ApplicationRunner.java new file mode 100644 index 00000000..57a93b66 --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/services/ApplicationRunner.java @@ -0,0 +1,66 @@ +package ru.otus.services; + +import ru.otus.exceptions.MenuCommandProcessorNotFound; +import ru.otus.exceptions.MenuItemIndexOutOfBoundsException; +import ru.otus.exceptions.NoteIndexOutOfBoundsException; +import ru.otus.services.menu.MenuOption; +import ru.otus.services.menu.MenuOptionsRegistry; +import ru.otus.services.processors.MenuCommandsProcessor; + +import java.util.Comparator; + +public class ApplicationRunner { + private final IOService ioService; + private final ApplicationStopService applicationStopService; + private final MenuOptionsRegistry menuOptionsRegistry; + private final MenuCommandsProcessor commandsProcessor; + + + public ApplicationRunner(IOService ioService, + ApplicationStopService applicationStopService, + MenuOptionsRegistry menuOptionsRegistry, + MenuCommandsProcessor commandsProcessor) { + this.ioService = ioService; + this.applicationStopService = applicationStopService; + this.menuOptionsRegistry = menuOptionsRegistry; + this.commandsProcessor = commandsProcessor; + } + + public void run() { + while (applicationStopService.isApplicationRunning()) { + outputMenu(); + try { + var selectedMenuItem = readSelectedOptionNumber(); + processMenuCommand(selectedMenuItem); + + } catch (NumberFormatException e) { + ioService.outputString("Ошибка при вводе числа"); + } catch (MenuItemIndexOutOfBoundsException e) { + ioService.outputString("Введен неверный номер опции"); + } catch (NoteIndexOutOfBoundsException e) { + ioService.outputString("Введен несуществующий номер заметки"); + } catch (MenuCommandProcessorNotFound e) { + ioService.outputString("Не найден обработчик для выбранного пункта меню"); + } + } + } + + private void outputMenu() { + ioService.outputString("Выберите одно из следующих действий..."); + menuOptionsRegistry.getAvailableMenuOptions().stream() + .sorted(Comparator.comparingInt(MenuOption::getId)) + .map(m -> m.getId() + ". " + m.getDescription()) + .forEach(ioService::outputString); + } + + private void processMenuCommand(int selectedMenuItemId) { + var selectedMenuOption = menuOptionsRegistry.getMenuOptionById(selectedMenuItemId) + .orElseThrow(() -> new MenuItemIndexOutOfBoundsException("Given menu item index is out of range")); + + commandsProcessor.processMenuCommand(selectedMenuOption); + } + + private int readSelectedOptionNumber() { + return ioService.readInt(); + } +} diff --git a/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/services/ApplicationStopService.java b/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/services/ApplicationStopService.java new file mode 100644 index 00000000..31d612f9 --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/services/ApplicationStopService.java @@ -0,0 +1,6 @@ +package ru.otus.services; + +public interface ApplicationStopService { + boolean isApplicationRunning(); + void stopApplication(); +} diff --git a/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/services/ApplicationStopServiceImpl.java b/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/services/ApplicationStopServiceImpl.java new file mode 100644 index 00000000..efd4d67c --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/services/ApplicationStopServiceImpl.java @@ -0,0 +1,36 @@ +package ru.otus.services; + +import ru.otus.config.ApplicationStopServiceSettingsProvider; +import ru.otus.services.processors.InputService; + +import java.util.concurrent.atomic.AtomicBoolean; + +public class ApplicationStopServiceImpl implements ApplicationStopService { + + private final InputService inputService; + private final ApplicationStopServiceSettingsProvider settingsProvider; + private final AtomicBoolean executionFlag; + + public ApplicationStopServiceImpl(InputService inputService, + ApplicationStopServiceSettingsProvider settingsProvider) { + this.inputService = inputService; + this.settingsProvider = settingsProvider; + this.executionFlag = new AtomicBoolean(true); + } + + @Override + public boolean isApplicationRunning() { + return executionFlag.get(); + } + + @Override + public void stopApplication() { + if (settingsProvider.isConfirmExit()) { + var exitConfirmation = inputService.readStringWithPrompt("Действительно выйти? (да/нет)"); + if (exitConfirmation.equalsIgnoreCase("нет")) { + return; + } + } + executionFlag.set(false); + } +} diff --git a/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/services/IOService.java b/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/services/IOService.java new file mode 100644 index 00000000..5e8cd764 --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/services/IOService.java @@ -0,0 +1,9 @@ +package ru.otus.services; + +import ru.otus.services.processors.InputService; +import ru.otus.services.processors.OutputService; + +public interface IOService extends InputService, OutputService { + + +} diff --git a/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/services/IOServiceStreams.java b/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/services/IOServiceStreams.java new file mode 100644 index 00000000..ca7dff21 --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/services/IOServiceStreams.java @@ -0,0 +1,37 @@ +package ru.otus.services; + +import java.io.InputStream; +import java.io.PrintStream; +import java.util.Scanner; + +public class IOServiceStreams implements IOService { + private final PrintStream output; + private final Scanner input; + + public IOServiceStreams(PrintStream outputStream, InputStream inputStream) { + output = outputStream; + input = new Scanner(inputStream); + } + + @Override + public void outputString(String s){ + output.println(s); + } + + @Override + public int readInt(){ + return Integer.parseInt(input.nextLine()); + } + + @Override + public int readIntWithPrompt(String prompt){ + outputString(prompt); + return Integer.parseInt(input.nextLine()); + } + + @Override + public String readStringWithPrompt(String prompt){ + outputString(prompt); + return input.nextLine(); + } +} diff --git a/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/services/NoteConverter.java b/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/services/NoteConverter.java new file mode 100644 index 00000000..7dfe1e57 --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/services/NoteConverter.java @@ -0,0 +1,7 @@ +package ru.otus.services; + +import ru.otus.model.Note; + +public interface NoteConverter { + String convertNoteToString(int noteNumber, Note note); +} diff --git a/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/services/NoteConverterImpl.java b/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/services/NoteConverterImpl.java new file mode 100644 index 00000000..5ff2c79f --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/services/NoteConverterImpl.java @@ -0,0 +1,20 @@ +package ru.otus.services; + +import ru.otus.config.DateTimeFormatProvider; +import ru.otus.model.Note; + +import java.time.format.DateTimeFormatter; + +public class NoteConverterImpl implements NoteConverter { + private final DateTimeFormatProvider dateTimeFormatProvider; + + public NoteConverterImpl(DateTimeFormatProvider dateTimeFormatProvider) { + this.dateTimeFormatProvider = dateTimeFormatProvider; + } + + @Override + public String convertNoteToString(int noteNumber, Note note) { + var dateTimeFormatter = DateTimeFormatter.ofPattern(dateTimeFormatProvider.getDateTimeFormat()); + return noteNumber + " | " + dateTimeFormatter.format(note.getCreationTime()) + " | " + note.getText(); + } +} diff --git a/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/services/NotesService.java b/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/services/NotesService.java new file mode 100644 index 00000000..019c6cd7 --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/services/NotesService.java @@ -0,0 +1,13 @@ +package ru.otus.services; + +import ru.otus.model.Note; + +import java.util.List; + +public interface NotesService { + List getAll(); + + void save(Note note); + + void remove(String id); +} diff --git a/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/services/NotesServiceImpl.java b/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/services/NotesServiceImpl.java new file mode 100644 index 00000000..b8c15298 --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/services/NotesServiceImpl.java @@ -0,0 +1,31 @@ +package ru.otus.services; + +import ru.otus.model.Note; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +public class NotesServiceImpl implements NotesService { + private final Map notes; + + public NotesServiceImpl() { + notes = new HashMap<>(); + } + + @Override + public List getAll() { + return notes.values().stream().map(Note::copy).collect(Collectors.toList()); + } + + @Override + public void save(Note note) { + notes.put(note.getId(), note); + } + + @Override + public void remove(String id) { + notes.remove(id); + } +} diff --git a/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/services/menu/MenuOption.java b/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/services/menu/MenuOption.java new file mode 100644 index 00000000..2514200b --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/services/menu/MenuOption.java @@ -0,0 +1,34 @@ +package ru.otus.services.menu; + +public class MenuOption { + private final int id; + private final String description; + + public MenuOption(int id, String description) { + this.id = id; + this.description = description; + } + + public int getId() { + return id; + } + + public String getDescription() { + return description; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + MenuOption that = (MenuOption) o; + + return id == that.id; + } + + @Override + public int hashCode() { + return id; + } +} diff --git a/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/services/menu/MenuOptionsRegistry.java b/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/services/menu/MenuOptionsRegistry.java new file mode 100644 index 00000000..cd5c86cb --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/services/menu/MenuOptionsRegistry.java @@ -0,0 +1,9 @@ +package ru.otus.services.menu; + +import java.util.List; +import java.util.Optional; + +public interface MenuOptionsRegistry { + List getAvailableMenuOptions(); + Optional getMenuOptionById(int id); +} diff --git a/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/services/menu/MenuOptionsRegistryImpl.java b/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/services/menu/MenuOptionsRegistryImpl.java new file mode 100644 index 00000000..30fca79d --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/services/menu/MenuOptionsRegistryImpl.java @@ -0,0 +1,26 @@ +package ru.otus.services.menu; + +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.function.Function; +import java.util.stream.Collectors; + +public class MenuOptionsRegistryImpl implements MenuOptionsRegistry { + private final Map options; + + public MenuOptionsRegistryImpl(List options) { + this.options = options.stream() + .collect(Collectors.toUnmodifiableMap(MenuOption::getId, Function.identity())); + } + + @Override + public List getAvailableMenuOptions() { + return options.values().stream().collect(Collectors.toUnmodifiableList()); + } + + @Override + public Optional getMenuOptionById(int id) { + return Optional.ofNullable(options.get(id)); + } +} diff --git a/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/services/processors/AddNewNoteSingleCommandProcessor.java b/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/services/processors/AddNewNoteSingleCommandProcessor.java new file mode 100644 index 00000000..7649900f --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/services/processors/AddNewNoteSingleCommandProcessor.java @@ -0,0 +1,30 @@ +package ru.otus.services.processors; + +import ru.otus.model.Note; +import ru.otus.services.NotesService; +import ru.otus.services.menu.MenuOption; + +public class AddNewNoteSingleCommandProcessor implements MenuSingleCommandProcessor { + private final MenuOption processedCommandOption; + private final InputService inputService; + private final NotesService notesService; + + public AddNewNoteSingleCommandProcessor(InputService inputService, NotesService notesService, + MenuOption processedCommandOption) { + this.inputService = inputService; + this.notesService = notesService; + this.processedCommandOption = processedCommandOption; + } + + @Override + public void processCommand() { + var noteText = inputService.readStringWithPrompt("Введите текст заметки..."); + notesService.save(Note.of(noteText)); + + } + + @Override + public MenuOption getProcessedCommandOption() { + return processedCommandOption; + } +} diff --git a/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/services/processors/DeleteNoteSingleCommandProcessor.java b/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/services/processors/DeleteNoteSingleCommandProcessor.java new file mode 100644 index 00000000..43898f61 --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/services/processors/DeleteNoteSingleCommandProcessor.java @@ -0,0 +1,37 @@ +package ru.otus.services.processors; + +import ru.otus.services.NotesService; +import ru.otus.services.menu.MenuOption; + + +import static ru.otus.services.processors.utils.NotesListUtil.checkNoteNumber; + +public class DeleteNoteSingleCommandProcessor implements MenuSingleCommandProcessor { + private final MenuOption processedCommandOption; + private final InputService inputService; + private final NotesService notesService; + + public DeleteNoteSingleCommandProcessor(InputService inputService, NotesService notesService, + MenuOption processedCommandOption) { + this.inputService = inputService; + this.notesService = notesService; + this.processedCommandOption = processedCommandOption; + } + + @Override + public void processCommand() { + var notes = notesService.getAll(); + + var deletedNoteNumber = inputService.readIntWithPrompt("Введите номер удаляемой заметки..."); + checkNoteNumber(deletedNoteNumber, notes.size()); + + var updatedNote = notes.get(deletedNoteNumber - 1); + notesService.remove(updatedNote.getId()); + } + + @Override + public MenuOption getProcessedCommandOption() { + return processedCommandOption; + } + +} diff --git a/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/services/processors/InputService.java b/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/services/processors/InputService.java new file mode 100644 index 00000000..52079551 --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/services/processors/InputService.java @@ -0,0 +1,9 @@ +package ru.otus.services.processors; + +public interface InputService { + int readInt(); + + int readIntWithPrompt(String prompt); + + String readStringWithPrompt(String prompt); +} diff --git a/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/services/processors/MenuCommandsProcessor.java b/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/services/processors/MenuCommandsProcessor.java new file mode 100644 index 00000000..68f7f77a --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/services/processors/MenuCommandsProcessor.java @@ -0,0 +1,7 @@ +package ru.otus.services.processors; + +import ru.otus.services.menu.MenuOption; + +public interface MenuCommandsProcessor { + void processMenuCommand(MenuOption selectedMenuOption); +} diff --git a/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/services/processors/MenuCommandsProcessorImpl.java b/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/services/processors/MenuCommandsProcessorImpl.java new file mode 100644 index 00000000..495841cf --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/services/processors/MenuCommandsProcessorImpl.java @@ -0,0 +1,27 @@ +package ru.otus.services.processors; + +import ru.otus.exceptions.MenuCommandProcessorNotFound; +import ru.otus.services.menu.MenuOption; + +import java.util.List; +import java.util.Map; +import java.util.function.Function; +import java.util.stream.Collectors; + +public class MenuCommandsProcessorImpl implements MenuCommandsProcessor { + private final Map processors; + + public MenuCommandsProcessorImpl(List processors) { + this.processors = processors.stream() + .collect(Collectors.toMap(MenuSingleCommandProcessor::getProcessedCommandOption, Function.identity())); + } + + @Override + public void processMenuCommand(MenuOption selectedMenuOption) { + var commandProcessor = processors.get(selectedMenuOption); + if (commandProcessor == null) { + throw new MenuCommandProcessorNotFound("Menu command processor for given option does not registered"); + } + commandProcessor.processCommand(); + } +} diff --git a/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/services/processors/MenuSingleCommandProcessor.java b/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/services/processors/MenuSingleCommandProcessor.java new file mode 100644 index 00000000..fb5f7245 --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/services/processors/MenuSingleCommandProcessor.java @@ -0,0 +1,8 @@ +package ru.otus.services.processors; + +import ru.otus.services.menu.MenuOption; + +public interface MenuSingleCommandProcessor { + void processCommand(); + MenuOption getProcessedCommandOption(); +} diff --git a/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/services/processors/OutputService.java b/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/services/processors/OutputService.java new file mode 100644 index 00000000..dd68ad88 --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/services/processors/OutputService.java @@ -0,0 +1,5 @@ +package ru.otus.services.processors; + +public interface OutputService { + void outputString(String s); +} diff --git a/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/services/processors/ShowAllNotesSingleCommandProcessor.java b/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/services/processors/ShowAllNotesSingleCommandProcessor.java new file mode 100644 index 00000000..8d902e69 --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/services/processors/ShowAllNotesSingleCommandProcessor.java @@ -0,0 +1,38 @@ +package ru.otus.services.processors; + +import ru.otus.services.NoteConverter; +import ru.otus.services.NotesService; +import ru.otus.services.menu.MenuOption; + +import java.util.stream.IntStream; + +public class ShowAllNotesSingleCommandProcessor implements MenuSingleCommandProcessor { + private final MenuOption processedCommandOption; + + private final OutputService outputService; + private final NotesService notesService; + private final NoteConverter noteConverter; + + public ShowAllNotesSingleCommandProcessor(OutputService outputService, NotesService notesService, + NoteConverter noteConverter, MenuOption processedCommandOption) { + this.outputService = outputService; + this.notesService = notesService; + this.noteConverter = noteConverter; + this.processedCommandOption = processedCommandOption; + } + + @Override + public void processCommand() { + var notes = notesService.getAll(); + outputService.outputString("Заметки:"); + IntStream.range(1, notes.size() + 1) + .mapToObj(k -> noteConverter.convertNoteToString(k, notes.get(k - 1))) + .forEach(outputService::outputString); + outputService.outputString(""); + } + + @Override + public MenuOption getProcessedCommandOption() { + return processedCommandOption; + } +} diff --git a/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/services/processors/StopApplicationSingleCommandProcessor.java b/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/services/processors/StopApplicationSingleCommandProcessor.java new file mode 100644 index 00000000..4fbef62c --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/services/processors/StopApplicationSingleCommandProcessor.java @@ -0,0 +1,25 @@ +package ru.otus.services.processors; + +import ru.otus.services.ApplicationStopService; +import ru.otus.services.menu.MenuOption; + +public class StopApplicationSingleCommandProcessor implements MenuSingleCommandProcessor { + private final MenuOption processedCommandOption; + private final ApplicationStopService applicationStopService; + + public StopApplicationSingleCommandProcessor(ApplicationStopService applicationStopService, + MenuOption processedCommandOption) { + this.applicationStopService = applicationStopService; + this.processedCommandOption = processedCommandOption; + } + + @Override + public void processCommand() { + applicationStopService.stopApplication(); + } + + @Override + public MenuOption getProcessedCommandOption() { + return processedCommandOption; + } +} diff --git a/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/services/processors/UpdateNoteSingleCommandProcessor.java b/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/services/processors/UpdateNoteSingleCommandProcessor.java new file mode 100644 index 00000000..85116a15 --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/services/processors/UpdateNoteSingleCommandProcessor.java @@ -0,0 +1,41 @@ +package ru.otus.services.processors; + +import ru.otus.model.Note; +import ru.otus.services.menu.MenuOption; +import ru.otus.services.NotesService; + +import java.util.List; + +import static ru.otus.services.processors.utils.NotesListUtil.checkNoteNumber; + +public class UpdateNoteSingleCommandProcessor implements MenuSingleCommandProcessor { + private final MenuOption processedCommandOption; + private final InputService inputService; + private final NotesService notesService; + + public UpdateNoteSingleCommandProcessor(InputService inputService, NotesService notesService, + MenuOption processedCommandOption) { + this.inputService = inputService; + this.notesService = notesService; + this.processedCommandOption = processedCommandOption; + } + + @Override + public void processCommand() { + var notes = notesService.getAll(); + + var updatedNoteNumber = inputService.readIntWithPrompt("Введите номер изменяемой заметки..."); + checkNoteNumber(updatedNoteNumber, notes.size()); + + var noteText = inputService.readStringWithPrompt("Введите текст заметки..."); + + var updatedNote = notes.get(updatedNoteNumber - 1); + notesService.save(Note.of(updatedNote.getId(), noteText)); } + + @Override + public MenuOption getProcessedCommandOption() { + return processedCommandOption; + } + + +} diff --git a/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/services/processors/utils/NotesListUtil.java b/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/services/processors/utils/NotesListUtil.java new file mode 100644 index 00000000..0f19e3cf --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/main/java/ru/otus/services/processors/utils/NotesListUtil.java @@ -0,0 +1,11 @@ +package ru.otus.services.processors.utils; + +import ru.otus.exceptions.NoteIndexOutOfBoundsException; + +public class NotesListUtil { + public static void checkNoteNumber(int noteNumber, int notesCount) { + if (noteNumber <= 0 || noteNumber > notesCount) { + throw new NoteIndexOutOfBoundsException("Given number of note is out of range"); + } + } +} diff --git a/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/test/java/ru/otus/services/ApplicationStopServiceImplTest.java b/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/test/java/ru/otus/services/ApplicationStopServiceImplTest.java new file mode 100644 index 00000000..71ddf850 --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/test/java/ru/otus/services/ApplicationStopServiceImplTest.java @@ -0,0 +1,33 @@ +package ru.otus.services; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import ru.otus.config.ApplicationStopServiceSettingsProvider; +import ru.otus.services.processors.InputService; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.*; + +@DisplayName("Сервис остановки приложения ") +class ApplicationStopServiceImplTest { + + @DisplayName("должен возвращать корректный статус работы приложения") + @ParameterizedTest(name = "остановить приложение: {0}, ожидаемый результат: {1}") + @CsvSource({"false, true", "true, false"}) + void shouldReturnCorrectApplicationExecutionStatus(boolean shouldStopApplication, boolean expectedStatus) { + var inputService = mock(InputService.class); + var settingsProvider = mock(ApplicationStopServiceSettingsProvider.class); + given(settingsProvider.isConfirmExit()).willReturn(false); + var applicationStopService = new ApplicationStopServiceImpl(inputService, settingsProvider); + + if (shouldStopApplication) { + applicationStopService.stopApplication(); + verify(settingsProvider, times(1)).isConfirmExit(); + } + var actualStatus = applicationStopService.isApplicationRunning(); + assertThat(actualStatus).isEqualTo(expectedStatus); + verify(inputService, never()).readStringWithPrompt(any()); + } +} \ No newline at end of file diff --git a/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/test/java/ru/otus/services/menu/MenuOptionsRegistryImplTest.java b/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/test/java/ru/otus/services/menu/MenuOptionsRegistryImplTest.java new file mode 100644 index 00000000..21c13cd5 --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/test/java/ru/otus/services/menu/MenuOptionsRegistryImplTest.java @@ -0,0 +1,44 @@ +package ru.otus.services.menu; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.*; + +@DisplayName("Реестр опций меню ") +class MenuOptionsRegistryImplTest { + + private List options; + private MenuOptionsRegistryImpl menuOptionsRegistry; + + @BeforeEach + void setUp() { + options = List.of(new MenuOption(1, "opt1"), new MenuOption(2, "opt2")); + menuOptionsRegistry = new MenuOptionsRegistryImpl(options); + } + + @DisplayName("должен возвращать список ожидаемых опций ") + @Test + void shouldReturnExpectedAvailableMenuOptions() { + var actualOptions = menuOptionsRegistry.getAvailableMenuOptions(); + assertThat(actualOptions) + .usingRecursiveFieldByFieldElementComparator() + .containsExactlyInAnyOrderElementsOf(options); + } + + // Обратить внимание на работу с Optional + @DisplayName("должен корректно возвращать опцию меню по ее идентификатору ") + @Test + void shouldReturnExpectedMenuOptionById() { + var expectedOption = options.get(0); + var actualOption = menuOptionsRegistry.getMenuOptionById(expectedOption.getId()); + assertThat(actualOption).isNotEmpty() + .get() + .usingRecursiveComparison() + .isEqualTo(expectedOption); + } +} \ No newline at end of file diff --git a/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/test/java/ru/otus/services/processors/AddNewNoteSingleCommandProcessorTest.java b/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/test/java/ru/otus/services/processors/AddNewNoteSingleCommandProcessorTest.java new file mode 100644 index 00000000..d5f5b32d --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/test/java/ru/otus/services/processors/AddNewNoteSingleCommandProcessorTest.java @@ -0,0 +1,59 @@ +package ru.otus.services.processors; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentCaptor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import ru.otus.model.Note; +import ru.otus.services.NotesService; +import ru.otus.services.menu.MenuOption; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +@DisplayName("Процессор команды добавления новой заметки ") +@ExtendWith(MockitoExtension.class) +class AddNewNoteSingleCommandProcessorTest { + + @Mock + private MenuOption processedCommandOption; + + @Mock + private InputService inputService; + + @Mock + private NotesService notesService; + + @InjectMocks + private AddNewNoteSingleCommandProcessor processor; + + @DisplayName("должен корректно добавлять новой заметки ") + @Test + void shouldCorrectAddExpectedNoteUseExpectedServicesMethods() { + var expectedNoteText = "Expected Note Text"; + given(inputService.readStringWithPrompt(anyString())) + .willReturn(expectedNoteText); + + processor.processCommand(); + + verify(inputService, times(1)).readStringWithPrompt(any()); + + var captor = ArgumentCaptor.forClass(Note.class); + verify(notesService).save(captor.capture()); + var actualNote = captor.getValue(); + assertThat(actualNote).extracting(Note::getText).isEqualTo(expectedNoteText); + } + + @DisplayName("должен возвращает ожидаемый тип обрабатываемой команды") + @Test + void shouldReturnExpectedProcessedCommandOption() { + assertThat(processor.getProcessedCommandOption()).isEqualTo(processedCommandOption); + } +} \ No newline at end of file diff --git a/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/test/java/ru/otus/services/processors/MenuCommandsProcessorImplTest.java b/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/test/java/ru/otus/services/processors/MenuCommandsProcessorImplTest.java new file mode 100644 index 00000000..f18a7562 --- /dev/null +++ b/2022-05/spring-00/architecture-origins/solution10_ocp_isp/src/test/java/ru/otus/services/processors/MenuCommandsProcessorImplTest.java @@ -0,0 +1,50 @@ +package ru.otus.services.processors; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import ru.otus.exceptions.MenuCommandProcessorNotFound; +import ru.otus.services.menu.MenuOption; + +import java.util.ArrayList; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.*; + +@DisplayName("Процессор команд меню ") +class MenuCommandsProcessorImplTest { + + private List singleCommandProcessors; + private MenuCommandsProcessorImpl processor; + + @BeforeEach + void setUp() { + singleCommandProcessors = new ArrayList<>(3); + for (int i = 1; i < 4; i++) { + var opt = new MenuOption(i, "opt" + i); + var singleCommandProcessor = mock(MenuSingleCommandProcessor.class); + given(singleCommandProcessor.getProcessedCommandOption()).willReturn(opt); + singleCommandProcessors.add(singleCommandProcessor); + } + processor = new MenuCommandsProcessorImpl(singleCommandProcessors); + } + + @DisplayName("должен корректно обрабатывать команду если для нее есть процессор") + @Test + void shouldCorrectProcessMenuCommandWhenProcessorForGivenCommandExists() { + for (var singleCommandProcessor: singleCommandProcessors) { + processor.processMenuCommand(singleCommandProcessor.getProcessedCommandOption()); + verify(singleCommandProcessor, times(1)).processCommand(); + } + } + + @DisplayName("должен кидать ожидаемое исключение если процессор для заданной команды отсутствует") + @Test + void shouldThrowExpectedExceptionWhenProcessorForGivenCommandDoesNotExists() { + var commandOptionWithNotExistingProcessor = new MenuOption(4, "opt4"); + assertThatCode(() -> processor.processMenuCommand(commandOptionWithNotExistingProcessor)) + .isInstanceOf(MenuCommandProcessorNotFound.class); + } +} \ No newline at end of file diff --git a/2022-05/spring-01/.gitignore b/2022-05/spring-01/.gitignore new file mode 100644 index 00000000..4ea52072 --- /dev/null +++ b/2022-05/spring-01/.gitignore @@ -0,0 +1,24 @@ +target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/build/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ diff --git a/2022-05/spring-01/pom.xml b/2022-05/spring-01/pom.xml new file mode 100644 index 00000000..6658aaa0 --- /dev/null +++ b/2022-05/spring-01/pom.xml @@ -0,0 +1,17 @@ + + + 4.0.0 + + ru.otus + spring-01 + 1.0 + + pom + + + spring-01-exercise + spring-01-solution + + diff --git a/2022-05/spring-01/spring-01-exercise/pom.xml b/2022-05/spring-01/spring-01-exercise/pom.xml new file mode 100644 index 00000000..e3aa2772 --- /dev/null +++ b/2022-05/spring-01/spring-01-exercise/pom.xml @@ -0,0 +1,20 @@ + + + 4.0.0 + + ru.otus + spring-01-exercise + 1.0 + + + 11 + 11 + UTF-8 + + + + + + diff --git a/2022-05/spring-01/spring-01-exercise/src/main/java/ru/otus/spring/Main.java b/2022-05/spring-01/spring-01-exercise/src/main/java/ru/otus/spring/Main.java new file mode 100644 index 00000000..e3201a16 --- /dev/null +++ b/2022-05/spring-01/spring-01-exercise/src/main/java/ru/otus/spring/Main.java @@ -0,0 +1,17 @@ +package ru.otus.spring; + +//import org.springframework.context.support.ClassPathXmlApplicationContext; +import ru.otus.spring.domain.Person; + +public class Main { + + public static void main(String[] args) { + // TODO: создайте здесь класс контекста + + // TODO: Получите Person Service + + // Получите Person "Ivan" + Person ivan = null; + System.out.println("name: " + ivan.getName() + " age: " + ivan.getAge()); + } +} diff --git a/2022-05/spring-01/spring-01-exercise/src/main/java/ru/otus/spring/dao/PersonDao.java b/2022-05/spring-01/spring-01-exercise/src/main/java/ru/otus/spring/dao/PersonDao.java new file mode 100644 index 00000000..d33939bd --- /dev/null +++ b/2022-05/spring-01/spring-01-exercise/src/main/java/ru/otus/spring/dao/PersonDao.java @@ -0,0 +1,8 @@ +package ru.otus.spring.dao; + +import ru.otus.spring.domain.Person; + +public interface PersonDao { + + Person findByName(String name); +} diff --git a/2022-05/spring-01/spring-01-exercise/src/main/java/ru/otus/spring/dao/PersonDaoSimple.java b/2022-05/spring-01/spring-01-exercise/src/main/java/ru/otus/spring/dao/PersonDaoSimple.java new file mode 100644 index 00000000..7f7c97c6 --- /dev/null +++ b/2022-05/spring-01/spring-01-exercise/src/main/java/ru/otus/spring/dao/PersonDaoSimple.java @@ -0,0 +1,10 @@ +package ru.otus.spring.dao; + +import ru.otus.spring.domain.Person; + +public class PersonDaoSimple implements PersonDao { + + public Person findByName(String name) { + return new Person(name, 18); + } +} diff --git a/2022-05/spring-01/spring-01-exercise/src/main/java/ru/otus/spring/domain/Person.java b/2022-05/spring-01/spring-01-exercise/src/main/java/ru/otus/spring/domain/Person.java new file mode 100644 index 00000000..c23be0c6 --- /dev/null +++ b/2022-05/spring-01/spring-01-exercise/src/main/java/ru/otus/spring/domain/Person.java @@ -0,0 +1,20 @@ +package ru.otus.spring.domain; + +public class Person { + + private final String name; + private final int age; + + public Person(String name, int age) { + this.name = name; + this.age = age; + } + + public String getName() { + return name; + } + + public int getAge() { + return age; + } +} diff --git a/2022-05/spring-01/spring-01-exercise/src/main/java/ru/otus/spring/service/PersonService.java b/2022-05/spring-01/spring-01-exercise/src/main/java/ru/otus/spring/service/PersonService.java new file mode 100644 index 00000000..9b83e7de --- /dev/null +++ b/2022-05/spring-01/spring-01-exercise/src/main/java/ru/otus/spring/service/PersonService.java @@ -0,0 +1,8 @@ +package ru.otus.spring.service; + +import ru.otus.spring.domain.Person; + +public interface PersonService { + + Person getByName(String name); +} diff --git a/2022-05/spring-01/spring-01-exercise/src/main/java/ru/otus/spring/service/PersonServiceImpl.java b/2022-05/spring-01/spring-01-exercise/src/main/java/ru/otus/spring/service/PersonServiceImpl.java new file mode 100644 index 00000000..794c29dd --- /dev/null +++ b/2022-05/spring-01/spring-01-exercise/src/main/java/ru/otus/spring/service/PersonServiceImpl.java @@ -0,0 +1,17 @@ +package ru.otus.spring.service; + +import ru.otus.spring.dao.PersonDao; +import ru.otus.spring.domain.Person; + +public class PersonServiceImpl implements PersonService { + + private final PersonDao dao; + + public PersonServiceImpl(PersonDao dao) { + this.dao = dao; + } + + public Person getByName(String name) { + return dao.findByName(name); + } +} diff --git a/2022-05/spring-01/spring-01-exercise/src/main/resources/spring-context.xml b/2022-05/spring-01/spring-01-exercise/src/main/resources/spring-context.xml new file mode 100644 index 00000000..2cb9eabe --- /dev/null +++ b/2022-05/spring-01/spring-01-exercise/src/main/resources/spring-context.xml @@ -0,0 +1,11 @@ + + + + + + + + diff --git a/2022-05/spring-01/spring-01-solution/pom.xml b/2022-05/spring-01/spring-01-solution/pom.xml new file mode 100644 index 00000000..124886be --- /dev/null +++ b/2022-05/spring-01/spring-01-solution/pom.xml @@ -0,0 +1,26 @@ + + + 4.0.0 + + ru.otus + spring-01-solution + 1.0 + + + 11 + 11 + UTF-8 + + + + + + org.springframework + spring-context + 5.3.20 + + + diff --git a/2022-05/spring-01/spring-01-solution/src/main/java/ru/otus/spring/Main.java b/2022-05/spring-01/spring-01-solution/src/main/java/ru/otus/spring/Main.java new file mode 100644 index 00000000..f5b2fafb --- /dev/null +++ b/2022-05/spring-01/spring-01-solution/src/main/java/ru/otus/spring/Main.java @@ -0,0 +1,20 @@ +package ru.otus.spring; + +import org.springframework.context.support.ClassPathXmlApplicationContext; +import ru.otus.spring.domain.Person; +import ru.otus.spring.service.PersonService; + +public class Main { + + public static void main(String[] args) { + ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("/spring-context.xml"); + PersonService service = context.getBean(PersonService.class); + Person ivan = service.getByName("Ivan"); + System.out.println("name: " + ivan.getName() + " age: " + ivan.getAge()); + + // Данная операция, в принципе не нужна. + // Мы не работаем пока что с БД, а Spring Boot сделает закрытие за нас + // Подробности - через пару занятий + context.close(); + } +} diff --git a/2022-05/spring-01/spring-01-solution/src/main/java/ru/otus/spring/dao/PersonDao.java b/2022-05/spring-01/spring-01-solution/src/main/java/ru/otus/spring/dao/PersonDao.java new file mode 100644 index 00000000..d33939bd --- /dev/null +++ b/2022-05/spring-01/spring-01-solution/src/main/java/ru/otus/spring/dao/PersonDao.java @@ -0,0 +1,8 @@ +package ru.otus.spring.dao; + +import ru.otus.spring.domain.Person; + +public interface PersonDao { + + Person findByName(String name); +} diff --git a/2022-05/spring-01/spring-01-solution/src/main/java/ru/otus/spring/dao/PersonDaoSimple.java b/2022-05/spring-01/spring-01-solution/src/main/java/ru/otus/spring/dao/PersonDaoSimple.java new file mode 100644 index 00000000..7f7c97c6 --- /dev/null +++ b/2022-05/spring-01/spring-01-solution/src/main/java/ru/otus/spring/dao/PersonDaoSimple.java @@ -0,0 +1,10 @@ +package ru.otus.spring.dao; + +import ru.otus.spring.domain.Person; + +public class PersonDaoSimple implements PersonDao { + + public Person findByName(String name) { + return new Person(name, 18); + } +} diff --git a/2022-05/spring-01/spring-01-solution/src/main/java/ru/otus/spring/domain/Person.java b/2022-05/spring-01/spring-01-solution/src/main/java/ru/otus/spring/domain/Person.java new file mode 100644 index 00000000..c23be0c6 --- /dev/null +++ b/2022-05/spring-01/spring-01-solution/src/main/java/ru/otus/spring/domain/Person.java @@ -0,0 +1,20 @@ +package ru.otus.spring.domain; + +public class Person { + + private final String name; + private final int age; + + public Person(String name, int age) { + this.name = name; + this.age = age; + } + + public String getName() { + return name; + } + + public int getAge() { + return age; + } +} diff --git a/2022-05/spring-01/spring-01-solution/src/main/java/ru/otus/spring/service/PersonService.java b/2022-05/spring-01/spring-01-solution/src/main/java/ru/otus/spring/service/PersonService.java new file mode 100644 index 00000000..9b83e7de --- /dev/null +++ b/2022-05/spring-01/spring-01-solution/src/main/java/ru/otus/spring/service/PersonService.java @@ -0,0 +1,8 @@ +package ru.otus.spring.service; + +import ru.otus.spring.domain.Person; + +public interface PersonService { + + Person getByName(String name); +} diff --git a/2022-05/spring-01/spring-01-solution/src/main/java/ru/otus/spring/service/PersonServiceImpl.java b/2022-05/spring-01/spring-01-solution/src/main/java/ru/otus/spring/service/PersonServiceImpl.java new file mode 100644 index 00000000..794c29dd --- /dev/null +++ b/2022-05/spring-01/spring-01-solution/src/main/java/ru/otus/spring/service/PersonServiceImpl.java @@ -0,0 +1,17 @@ +package ru.otus.spring.service; + +import ru.otus.spring.dao.PersonDao; +import ru.otus.spring.domain.Person; + +public class PersonServiceImpl implements PersonService { + + private final PersonDao dao; + + public PersonServiceImpl(PersonDao dao) { + this.dao = dao; + } + + public Person getByName(String name) { + return dao.findByName(name); + } +} diff --git a/2022-05/spring-01/spring-01-solution/src/main/resources/spring-context.xml b/2022-05/spring-01/spring-01-solution/src/main/resources/spring-context.xml new file mode 100644 index 00000000..c3541cec --- /dev/null +++ b/2022-05/spring-01/spring-01-solution/src/main/resources/spring-context.xml @@ -0,0 +1,14 @@ + + + + + + + + + + +