diff --git a/lab-04-spring/.gitignore b/lab-04-spring/.gitignore new file mode 100644 index 0000000..c2065bc --- /dev/null +++ b/lab-04-spring/.gitignore @@ -0,0 +1,37 @@ +HELP.md +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ diff --git a/lab-04-spring/README.md b/lab-04-spring/README.md index cc62ab6..c7c9c6d 100644 --- a/lab-04-spring/README.md +++ b/lab-04-spring/README.md @@ -5,8 +5,10 @@ **Проект обязателен для всех студентов, 25.11.2021 вы будете показывать его одногруппникам.** ## Требования к реализации: + * **Java** + **Spring boot** -* Использование базы данных. Попробуйте использовать серверную базу данных (**Postgres**, **MySQL**). В крайнем случае можно использовать встраиваемые - **H2** или **SQLite**. +* Использование базы данных. Попробуйте использовать серверную базу данных (**Postgres**, **MySQL**). В крайнем случае + можно использовать встраиваемые - **H2** или **SQLite**. * Использование **Spring Security** для страницы администратора. * **Thymeleaf** или другой шаблонизатор. * Поддержка **REST api** в json формате для основного функционала. @@ -15,41 +17,74 @@ ## Дополнительно -При желании идею можно расширять. Например, добавить регистрацию пользователей, сделать красивый дизайн или анализировать посещаемость сайта. +При желании идею можно расширять. Например, добавить регистрацию пользователей, сделать красивый дизайн или +анализировать посещаемость сайта. ## Информация -Дедлайн - пара **25.11.2021**. Реализовывать проект нужно в директории **lab-04-spring**. К началу пары скрипт загрузит ваше приложение на **ovi.by**, чтобы оно было доступно для просмотра. +Дедлайн - пара **25.11.2021**. Реализовывать проект нужно в директории **lab-04-spring**. К началу пары скрипт загрузит +ваше приложение на **ovi.by**, чтобы оно было доступно для просмотра. -Во время презентации своего проекта можете рассказать с какими трудностями вы столкнулись, а так же показать интересные фрагменты кода, рассказать про архитектуру, идеи. +Во время презентации своего проекта можете рассказать с какими трудностями вы столкнулись, а так же показать интересные +фрагменты кода, рассказать про архитектуру, идеи. ## Условия -* _Мехович_. -Вы опытный автолюбитель. Поэтому ваши приятели нередко просят вас подкинуть. На своем сайте вы хотите выкладывать ваши ближайшие поездки. Поездки можно сортировать по дате, искать по точке назначения и отправления. Пользователи могут оставлять заявки. В админке можно добавлять поездки, а также просматривать заявки. -* _Шавнев_. -Вы эрудированный математик. Два раза в неделю вы делитесь знаниями со школьниками. К сожалению, у вас уходит много времени на то, чтобы выложить им домашнее задание. На своей странице вы будете выкладывать условия домашних работ, которые состоят из множества задач. Должен быть предусмотрен поиск по условию задачи. Домашние работы с заданиями добавляются в админке. У каждой домашней работы есть deadline. -* _Максимов_. -Вы первоклассный фотограф. На своей странице вы выкладываете фотосеты. Каждый фотосет состоит из нескольких фотографий, описания, места съемки. Искать фотосеты можно по названию. На главной странице можно посмотреть список всех фотосетов, а также выбрать несколько случайных фотографий. В админке можно добавлять фотосеты и загружать фотографии. -* _Лицкевич_. -Вы амбициозный сотрудник заморской компании. Поэтому, вы недолго думая принялись учить китайский язык. На своем сайте собираете интересные переводы с китайского на русский и наоборот. Каждому слову может соответствовать несколько переводов. На сайте слова можно искать по буквам и переходить по переводам. Новые слова можно добавлять в админке. -* _Тылецкий_. -Вы всезнающий студент. Ваши одногруппники нередко обращаются к вам за помощью. На вашем сайте вам можно задавать вопросы на самые различные темы от интегрального представления производной аналитичной ФКП до любовных советов. Есть поиск по вопросам. В админке вы может отвечать на вопросы, пользователи могут оставлять комментарии. -* _Альперин_. -Вы профессионал в настольном теннисе. В свободное от работы время вы решили проводить турниры. На вашем сайте можно следить за уже идущими турнирами и просматривать результаты завершенных. В админке можно создать турнир, указав его описание, количество и фамилии участников, формат стычек (best of X). После создания на главной странице турнир будет отображаться в списке текущих. На странице этого турнира должны отображаться текущие игры с возможностью указать кто победил и с каким счетом. После завершения игры, она попадает в историю турнира. Когда все игры турнира сыграны, турнир завершается и на странице этого турнира отображается рейтинг участников (их места), а турнир из списка текущих переходит в список завершенных. На главной странице можно посмотреть статистику по фамилии игрока (список турниров, в которых он участвовал, места в каждом из турниров). -* _Желткевич_. -Вы известный музыкант. На своем сайте вы выкладываете тексты своих песен, пользователи могут оставлять оценки и искать по словам в тексте. -* _Баранов_. -Вы трудолюбивый студент ШАД. В одном из своих домашек вы реализовали интерпретатор LISP. На вашем сайте пользователи могут писать программы на LISP и запускать их. В админке вы можете выкладывать примеры программ, с которыми пользователи могут начать работать. -* _Ходасевич_. -Вы водитель беспилотного автомобиля. Суть вашей работы заключается - обучать нейронные сети. Вы водите автомобиль и он обучается. На своем сайте вы логируете свои поездки, состоящие из нескольких последовательных маневров. Ваши коллеги могут оставлять комментарий к каждому из них и оценивать их точность. В админке добавляются поездки с маневрами. -* _Храпко_. -Вы профессиональный волейболист. На пике вашей карьеры вы занялись прибыльным делом - стали продавать насосы для накачки мячиков. На вашем сайте можно посмотреть каталог насосов и список торговых точек, для каждой точки увидеть список продаваемых насосов, а для каждого насоса список точек, в котором он продается. Насосы можно сортировать по цене и другим параметрам, искать по названию. В админке добавляются новые насосы. -* _Кровш_. -Вы начинающий гонщик. На вашем сайте показываются ваши попытки прохождения трасс. В админке можно добавить новую трассу с фотографией и попытку их прохождения. Попытка - время прохождения, дата, модель машины и описание. Можно посмотреть список всех машин, на которых вы участвовали в гонках, для каждой машины и трассы посмотреть все попытки, связанные с ними. В админке добавляются машины, трассы, попытки их прохождения. -* _Черникова_. -Вы многократная победительница олимпиад. И вот вы решили организовать свою олимпиаду. Вы столкнулись с проблемой рассадки участников. На вашем сайте участники смогут увидеть рассадку и найти себя. В админке вы добавляете список учеников - фамилия, школа. Каждый кабинет имеет 3 ряда по 5 парт. Рассадка генерируется автоматически каждый раз заново при добавлении нового ученика или удалении, причем ученики из одной школы не сидят рядом. На главной странице фамилии учеников отображаются в таблицах 3x5, которые соответствуют рассадке. Возможен поиск по фамилии и школе. -* _Шишков_. -Вы ответственный человек. Заведующая общежитием попросила вас написать программу для подсчета отработок студентов. На главной странице можно видеть сколько осталось отработать каждому студенту, а также лог его отработок - описание, количество часов. Так же есть поиск по фамилии студента, возможность отсортировать в порядке возрастания, убывания часов и фамилии студента. В админке можно добавить определенное количество часов для отработки всем или определенному студенту, добавить запись об отработке, указав фамилию студента, количество часов, описание. -* _Олешко_. -Вы типичный формошлеп. Вам нужно наформошлепить сервис, который позволит запускать приложение на Spring boot, указав репозиторий и директорию с исходным кодом в нем. Исходный код сначала должен быть получен из указанного репозитория, затем при необходимости исходный код должен быть обработан (подменена БД), собран, в итоге приложение запускается в docker-контейнере. +* _Мехович_. Вы опытный автолюбитель. Поэтому ваши приятели нередко просят вас подкинуть. На своем сайте вы хотите + выкладывать ваши ближайшие поездки. Поездки можно сортировать по дате, искать по точке назначения и отправления. + Пользователи могут оставлять заявки. В админке можно добавлять поездки, а также просматривать заявки. +* _Шавнев_. Вы эрудированный математик. Два раза в неделю вы делитесь знаниями со школьниками. К сожалению, у вас уходит + много времени на то, чтобы выложить им домашнее задание. На своей странице вы будете выкладывать условия домашних + работ, которые состоят из множества задач. Должен быть предусмотрен поиск по условию задачи. Домашние работы с + заданиями добавляются в админке. У каждой домашней работы есть deadline. +* _Максимов_. Вы первоклассный фотограф. На своей странице вы выкладываете фотосеты. Каждый фотосет состоит из + нескольких фотографий, описания, места съемки. Искать фотосеты можно по названию. На главной странице можно посмотреть + список всех фотосетов, а также выбрать несколько случайных фотографий. В админке можно добавлять фотосеты и загружать + фотографии. +* _Лицкевич_. Вы амбициозный сотрудник заморской компании. Поэтому, вы недолго думая принялись учить китайский язык. На + своем сайте собираете интересные переводы с китайского на русский и наоборот. Каждому слову может соответствовать + несколько переводов. На сайте слова можно искать по буквам и переходить по переводам. Новые слова можно добавлять в + админке. +* _Тылецкий_. Вы всезнающий студент. Ваши одногруппники нередко обращаются к вам за помощью. На вашем сайте вам можно + задавать вопросы на самые различные темы от интегрального представления производной аналитичной ФКП до любовных + советов. Есть поиск по вопросам. В админке вы может отвечать на вопросы, пользователи могут оставлять комментарии. +* _Альперин_. Вы профессионал в настольном теннисе. В свободное от работы время вы решили проводить турниры. На вашем + сайте можно следить за уже идущими турнирами и просматривать результаты завершенных. В админке можно создать турнир, + указав его описание, количество и фамилии участников, формат стычек (best of X). После создания на главной странице + турнир будет отображаться в списке текущих. На странице этого турнира должны отображаться текущие игры с возможностью + указать кто победил и с каким счетом. После завершения игры, она попадает в историю турнира. Когда все игры турнира + сыграны, турнир завершается и на странице этого турнира отображается рейтинг участников (их места), а турнир из списка + текущих переходит в список завершенных. На главной странице можно посмотреть статистику по фамилии игрока (список + турниров, в которых он участвовал, места в каждом из турниров). +* _Желткевич_. Вы известный музыкант. На своем сайте вы выкладываете тексты своих песен, пользователи могут оставлять + оценки и искать по словам в тексте. +* _Баранов_. Вы трудолюбивый студент ШАД. В одном из своих домашек вы реализовали интерпретатор LISP. На вашем сайте + пользователи могут писать программы на LISP и запускать их. В админке вы можете выкладывать примеры программ, с + которыми пользователи могут начать работать. +* _Ходасевич_. Вы водитель беспилотного автомобиля. Суть вашей работы заключается - обучать нейронные сети. Вы водите + автомобиль и он обучается. На своем сайте вы логируете свои поездки, состоящие из нескольких последовательных + маневров. Ваши коллеги могут оставлять комментарий к каждому из них и оценивать их точность. В админке добавляются + поездки с маневрами. +* _Храпко_. Вы профессиональный волейболист. На пике вашей карьеры вы занялись прибыльным делом - стали продавать насосы + для накачки мячиков. На вашем сайте можно посмотреть каталог насосов и список торговых точек, для каждой точки увидеть + список продаваемых насосов, а для каждого насоса список точек, в котором он продается. Насосы можно сортировать по + цене и другим параметрам, искать по названию. В админке добавляются новые насосы. +* _Кровш_. Вы начинающий гонщик. На вашем сайте показываются ваши попытки прохождения трасс. В админке можно добавить + новую трассу с фотографией и попытку их прохождения. Попытка - время прохождения, дата, модель машины и описание. + Можно посмотреть список всех машин, на которых вы участвовали в гонках, для каждой машины и трассы посмотреть все + попытки, связанные с ними. В админке добавляются машины, трассы, попытки их прохождения. +* _Черникова_. Вы многократная победительница олимпиад. И вот вы решили организовать свою олимпиаду. Вы столкнулись с + проблемой рассадки участников. На вашем сайте участники смогут увидеть рассадку и найти себя. В админке вы добавляете + список учеников - фамилия, школа. Каждый кабинет имеет 3 ряда по 5 парт. Рассадка генерируется автоматически каждый + раз заново при добавлении нового ученика или удалении, причем ученики из одной школы не сидят рядом. На главной + странице фамилии учеников отображаются в таблицах 3x5, которые соответствуют рассадке. Возможен поиск по фамилии и + школе. +* _Шишков_. Вы ответственный человек. Заведующая общежитием попросила вас написать программу для подсчета отработок + студентов. На главной странице можно видеть сколько осталось отработать каждому студенту, а также лог его отработок - + описание, количество часов. Так же есть поиск по фамилии студента, возможность отсортировать в порядке возрастания, + убывания часов и фамилии студента. В админке можно добавить определенное количество часов для отработки всем или + определенному студенту, добавить запись об отработке, указав фамилию студента, количество часов, описание. +* _Олешко_. Вы типичный формошлеп. Вам нужно наформошлепить сервис, который позволит запускать приложение на Spring + boot, указав репозиторий и директорию с исходным кодом в нем. Исходный код сначала должен быть получен из указанного + репозитория, затем при необходимости исходный код должен быть обработан (подменена БД), собран, в итоге приложение + запускается в docker-контейнере. diff --git a/lab-04-spring/build.gradle b/lab-04-spring/build.gradle new file mode 100644 index 0000000..7972bdf --- /dev/null +++ b/lab-04-spring/build.gradle @@ -0,0 +1,36 @@ +plugins { + id 'org.springframework.boot' version '2.6.0' + id 'io.spring.dependency-management' version '1.0.11.RELEASE' + id 'java' +} + +group = 'com.Khody31' +version = '0.0.1-SNAPSHOT' +sourceCompatibility = '11' + +configurations { + compileOnly { + extendsFrom annotationProcessor + } +} + +repositories { + mavenCentral() +} + +dependencies { + implementation 'org.springframework.boot:spring-boot-starter-thymeleaf:2.5.6' + implementation 'org.springframework.boot:spring-boot-starter-web:2.5.6' + implementation 'org.springframework.boot:spring-boot-starter-web-services:2.5.6' + implementation 'org.springframework.boot:spring-boot-starter-data-jpa:2.5.6' + implementation 'org.springframework.boot:spring-boot-starter-data-jpa:2.5.6' + implementation 'org.springframework.boot:spring-boot-starter-security' + compileOnly 'org.projectlombok:lombok:1.18.22' + runtimeOnly 'org.postgresql:postgresql:42.3.1' + annotationProcessor 'org.projectlombok:lombok:1.18.22' + testImplementation 'org.springframework.boot:spring-boot-starter-test:2.5.6' +} + +test { + useJUnitPlatform() +} diff --git a/lab-04-spring/gradle/wrapper/gradle-wrapper.jar b/lab-04-spring/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..7454180 Binary files /dev/null and b/lab-04-spring/gradle/wrapper/gradle-wrapper.jar differ diff --git a/lab-04-spring/gradle/wrapper/gradle-wrapper.properties b/lab-04-spring/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..ffed3a2 --- /dev/null +++ b/lab-04-spring/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-7.2-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/lab-04-spring/gradlew b/lab-04-spring/gradlew new file mode 100755 index 0000000..1b6c787 --- /dev/null +++ b/lab-04-spring/gradlew @@ -0,0 +1,234 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${0##*/} + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/lab-04-spring/gradlew.bat b/lab-04-spring/gradlew.bat new file mode 100644 index 0000000..ac1b06f --- /dev/null +++ b/lab-04-spring/gradlew.bat @@ -0,0 +1,89 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/lab-04-spring/settings.gradle b/lab-04-spring/settings.gradle new file mode 100644 index 0000000..1edd9d5 --- /dev/null +++ b/lab-04-spring/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'self-driving-database' diff --git a/lab-04-spring/src/main/java/com/Khody31/selfdrivingdatabase/MainController.java b/lab-04-spring/src/main/java/com/Khody31/selfdrivingdatabase/MainController.java new file mode 100644 index 0000000..73d831e --- /dev/null +++ b/lab-04-spring/src/main/java/com/Khody31/selfdrivingdatabase/MainController.java @@ -0,0 +1,126 @@ +package com.Khody31.selfdrivingdatabase; + +import com.Khody31.selfdrivingdatabase.model.Comment; +import com.Khody31.selfdrivingdatabase.model.Maneuver; +import com.Khody31.selfdrivingdatabase.model.Ride; +import com.Khody31.selfdrivingdatabase.repositories.CommentsRepository; +import com.Khody31.selfdrivingdatabase.repositories.ManeuverRepository; +import com.Khody31.selfdrivingdatabase.repositories.RidesRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.format.annotation.DateTimeFormat; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestParam; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Optional; + +@Controller +public class MainController { + + @Autowired + RidesRepository ridesRepository; + + @Autowired + ManeuverRepository maneuverRepository; + + @Autowired + CommentsRepository commentsRepository; + + List maneuvers; + + @GetMapping("/") + String mainPage(Model model) { + model.addAttribute("rides", ridesRepository.findAll()); + return "main_page"; + } + + @PostMapping("/clear") + String clear() { + ridesRepository.deleteAll(); + maneuverRepository.deleteAll(); + maneuvers = null; + return "redirect:/"; + } + + @GetMapping("/admin") + String adminPage(Model model) { + model.addAttribute("maneuvers", maneuvers); + return "admin_page"; + } + + @PostMapping(value = "/add_ride") + String addRide( + @RequestParam String carName, + @RequestParam String location, + @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") Date date) { + Ride ride = new Ride(); + ride.setCarName(carName); + ride.setLocation(location); + ride.setDate(date); + + ride.setManeuverList(maneuvers); + maneuvers = null; + + ridesRepository.save(ride); + System.out.println(ride.getId()); + return "redirect:/admin"; + } + + @PostMapping(value = "/add_maneuver") + String addManeuver( + @RequestParam String name, + @RequestParam Integer duration) { + if (maneuvers == null) { + maneuvers = new ArrayList<>(); + } + + Maneuver maneuver = new Maneuver(); + maneuver.setName(name); + maneuver.setDuration(duration); + + maneuvers.add(maneuver); + maneuverRepository.save(maneuver); + + return "redirect:/admin"; + } + + @GetMapping("/ride") + String ride(Model model, @RequestParam Integer id) { + model.addAttribute("rides", ridesRepository.findAllById(List.of(id))); + return "ride_page"; + } + + @PostMapping("/rate") + String rate( + Model model, + @RequestParam Double score, + @RequestParam Integer maneuverId, + @RequestParam Integer rideId) { + Optional maneuver = maneuverRepository.findById(maneuverId); + maneuver.ifPresent(value -> value.addScore(score)); + maneuver.ifPresent(value -> maneuverRepository.save(value)); + return ride(model, rideId); + } + + @PostMapping("/add_comment") + String addComment( + Model model, + @RequestParam String commentBody, + @RequestParam Integer rideId) { + Comment comment = new Comment(); + comment.setComment(commentBody); + commentsRepository.save(comment); + + System.out.println(comment.getId()); + + Ride cur_ride = ridesRepository.findById(rideId).get(); + cur_ride.addComment(comment); + + return ride(model, rideId); + } +} diff --git a/lab-04-spring/src/main/java/com/Khody31/selfdrivingdatabase/MainRestController.java b/lab-04-spring/src/main/java/com/Khody31/selfdrivingdatabase/MainRestController.java new file mode 100644 index 0000000..08ff473 --- /dev/null +++ b/lab-04-spring/src/main/java/com/Khody31/selfdrivingdatabase/MainRestController.java @@ -0,0 +1,53 @@ +package com.Khody31.selfdrivingdatabase; + +import com.Khody31.selfdrivingdatabase.model.Comment; +import com.Khody31.selfdrivingdatabase.repositories.CommentsRepository; +import com.Khody31.selfdrivingdatabase.repositories.ManeuverRepository; +import com.Khody31.selfdrivingdatabase.repositories.RidesRepository; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import java.util.NoSuchElementException; + +@RestController +@RequestMapping("/rest") +public class MainRestController { + + @Autowired + CommentsRepository commentsRepository; + + @Autowired + RidesRepository ridesRepository; + @Autowired + ManeuverRepository maneuverRepository; + + @Autowired + ObjectMapper objectMapper; + + @GetMapping(value="/comment", produces="application/json") + public String getComments(@RequestParam Integer id) { + try { + return objectMapper.writeValueAsString(commentsRepository.findById(id).get()); + } catch (NoSuchElementException err) { + return "there is no comment with such id"; + } catch (JsonProcessingException err) { + return "somethng went wrong"; + } + } + + @GetMapping(value="/ride", produces="application/json") + public String getRide(@RequestParam Integer id) { + try { + return objectMapper.writeValueAsString(ridesRepository.findById(id).get()); + } catch (NoSuchElementException err) { + return "there is no ride with such id"; + } catch (JsonProcessingException err) { + return "somethng went wrong"; + } + } +} \ No newline at end of file diff --git a/lab-04-spring/src/main/java/com/Khody31/selfdrivingdatabase/SecurityConfig.java b/lab-04-spring/src/main/java/com/Khody31/selfdrivingdatabase/SecurityConfig.java new file mode 100644 index 0000000..a053cec --- /dev/null +++ b/lab-04-spring/src/main/java/com/Khody31/selfdrivingdatabase/SecurityConfig.java @@ -0,0 +1,48 @@ +package com.Khody31.selfdrivingdatabase; + + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.core.userdetails.User; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.provisioning.InMemoryUserDetailsManager; + +@Configuration +@EnableWebSecurity +public class SecurityConfig extends WebSecurityConfigurerAdapter { + @Override + protected void configure(HttpSecurity http) throws Exception { + http + .csrf().disable() + .authorizeRequests() + .antMatchers("/admin").hasRole("ADMIN") + .antMatchers("/add_ride").hasRole("ADMIN") + .antMatchers("/add_maneuver").hasRole("ADMIN") + .antMatchers("/clear").hasRole("ADMIN") + .and() + .formLogin() + .permitAll() + .and() + .logout() + .permitAll() + .disable().cors(); + } + + @Bean + @Override + public UserDetailsService userDetailsService() { + UserDetails user = + User.withDefaultPasswordEncoder() + .username("roman") + .password("moysaonelove") + .roles("ADMIN") + .build(); + + return new InMemoryUserDetailsManager(user); + } +} \ No newline at end of file diff --git a/lab-04-spring/src/main/java/com/Khody31/selfdrivingdatabase/SelfDrivingDatabaseApplication.java b/lab-04-spring/src/main/java/com/Khody31/selfdrivingdatabase/SelfDrivingDatabaseApplication.java new file mode 100644 index 0000000..7c2cfaa --- /dev/null +++ b/lab-04-spring/src/main/java/com/Khody31/selfdrivingdatabase/SelfDrivingDatabaseApplication.java @@ -0,0 +1,13 @@ +package com.Khody31.selfdrivingdatabase; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SelfDrivingDatabaseApplication { + + public static void main(String[] args) { + SpringApplication.run(SelfDrivingDatabaseApplication.class, args); + } + +} diff --git a/lab-04-spring/src/main/java/com/Khody31/selfdrivingdatabase/model/Comment.java b/lab-04-spring/src/main/java/com/Khody31/selfdrivingdatabase/model/Comment.java new file mode 100644 index 0000000..66ee532 --- /dev/null +++ b/lab-04-spring/src/main/java/com/Khody31/selfdrivingdatabase/model/Comment.java @@ -0,0 +1,21 @@ +package com.Khody31.selfdrivingdatabase.model; + +import lombok.*; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Data +@Getter +@Setter +@NoArgsConstructor +@Entity +public class Comment { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + Integer id; + + String comment; +} diff --git a/lab-04-spring/src/main/java/com/Khody31/selfdrivingdatabase/model/Maneuver.java b/lab-04-spring/src/main/java/com/Khody31/selfdrivingdatabase/model/Maneuver.java new file mode 100644 index 0000000..72b5e54 --- /dev/null +++ b/lab-04-spring/src/main/java/com/Khody31/selfdrivingdatabase/model/Maneuver.java @@ -0,0 +1,27 @@ +package com.Khody31.selfdrivingdatabase.model; + +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.persistence.*; +import java.util.List; + +@Data +@Entity +@NoArgsConstructor +public class Maneuver { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + Integer id; + + Integer duration; + String name; + + Double averageScore; + Integer scoreCnt; + + public void addScore(double score) { + averageScore = (averageScore * scoreCnt + score) / (scoreCnt + 1); + scoreCnt += 1; + } +} diff --git a/lab-04-spring/src/main/java/com/Khody31/selfdrivingdatabase/model/Ride.java b/lab-04-spring/src/main/java/com/Khody31/selfdrivingdatabase/model/Ride.java new file mode 100644 index 0000000..3857ecf --- /dev/null +++ b/lab-04-spring/src/main/java/com/Khody31/selfdrivingdatabase/model/Ride.java @@ -0,0 +1,33 @@ +package com.Khody31.selfdrivingdatabase.model; + +import lombok.*; + +import javax.persistence.*; +import java.util.Date; +import java.util.List; + +@Data +@Getter +@Setter +@AllArgsConstructor +@NoArgsConstructor +@Entity +public class Ride { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + Integer Id; + + String location; + String carName; + Date date; + + @OneToMany + List maneuverList; + + @OneToMany + List commentsList; + + public void addComment(Comment comment) { + commentsList.add(comment); + } +} diff --git a/lab-04-spring/src/main/java/com/Khody31/selfdrivingdatabase/repositories/CommentsRepository.java b/lab-04-spring/src/main/java/com/Khody31/selfdrivingdatabase/repositories/CommentsRepository.java new file mode 100644 index 0000000..4da232a --- /dev/null +++ b/lab-04-spring/src/main/java/com/Khody31/selfdrivingdatabase/repositories/CommentsRepository.java @@ -0,0 +1,8 @@ +package com.Khody31.selfdrivingdatabase.repositories; + +import com.Khody31.selfdrivingdatabase.model.Comment; +import com.Khody31.selfdrivingdatabase.model.Maneuver; +import org.springframework.data.repository.CrudRepository; + +public interface CommentsRepository extends CrudRepository { +} diff --git a/lab-04-spring/src/main/java/com/Khody31/selfdrivingdatabase/repositories/ManeuverRepository.java b/lab-04-spring/src/main/java/com/Khody31/selfdrivingdatabase/repositories/ManeuverRepository.java new file mode 100644 index 0000000..96e03a6 --- /dev/null +++ b/lab-04-spring/src/main/java/com/Khody31/selfdrivingdatabase/repositories/ManeuverRepository.java @@ -0,0 +1,7 @@ +package com.Khody31.selfdrivingdatabase.repositories; + +import com.Khody31.selfdrivingdatabase.model.Maneuver; +import org.springframework.data.repository.CrudRepository; + +public interface ManeuverRepository extends CrudRepository { +} diff --git a/lab-04-spring/src/main/java/com/Khody31/selfdrivingdatabase/repositories/RidesRepository.java b/lab-04-spring/src/main/java/com/Khody31/selfdrivingdatabase/repositories/RidesRepository.java new file mode 100644 index 0000000..2dfad79 --- /dev/null +++ b/lab-04-spring/src/main/java/com/Khody31/selfdrivingdatabase/repositories/RidesRepository.java @@ -0,0 +1,8 @@ +package com.Khody31.selfdrivingdatabase.repositories; + +import com.Khody31.selfdrivingdatabase.model.Ride; +import org.springframework.data.repository.CrudRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface RidesRepository extends CrudRepository {} diff --git a/lab-04-spring/src/main/resources/application.properties b/lab-04-spring/src/main/resources/application.properties new file mode 100644 index 0000000..5e4a175 --- /dev/null +++ b/lab-04-spring/src/main/resources/application.properties @@ -0,0 +1,6 @@ +spring.datasource.url=jdbc:postgresql://localhost:5432/self-driving-database +spring.datasource.username=postgres +spring.datasource.password=lizaonelove +spring.datasource.driver-class-name=org.postgresql.Driver +spring.jpa.hibernate.ddl-auto=update +server.port=8081 diff --git a/lab-04-spring/src/main/resources/templates/admin_page.html b/lab-04-spring/src/main/resources/templates/admin_page.html new file mode 100644 index 0000000..b83cde2 --- /dev/null +++ b/lab-04-spring/src/main/resources/templates/admin_page.html @@ -0,0 +1,140 @@ + + + + + AdminPage + + + + + +
+ + + + + + + + +
+
+ + +
+
+
+ + + +
+
+ +
+ + + +
+ +
+ + + +
+ +
+ +
+
+ + + \ No newline at end of file diff --git a/lab-04-spring/src/main/resources/templates/main_page.html b/lab-04-spring/src/main/resources/templates/main_page.html new file mode 100644 index 0000000..d75159c --- /dev/null +++ b/lab-04-spring/src/main/resources/templates/main_page.html @@ -0,0 +1,49 @@ + + + + + + MainPage + + + + + + + + + + +
+
+ + + + +
+
+ +
+ +
+
+ +
+ + + \ No newline at end of file diff --git a/lab-04-spring/src/main/resources/templates/ride_page.html b/lab-04-spring/src/main/resources/templates/ride_page.html new file mode 100644 index 0000000..d644c5d --- /dev/null +++ b/lab-04-spring/src/main/resources/templates/ride_page.html @@ -0,0 +1,78 @@ + + + + + RidePage + + + + + + + + +
+ + + + + + +
+ + + + +
+ + + + +
+
+ + + +
+ + + +
+ +
+ +
+
+ + + + + \ No newline at end of file diff --git a/lab-04-spring/src/test/java/com/Khody31/selfdrivingdatabase/SelfDrivingDatabaseApplicationTests.java b/lab-04-spring/src/test/java/com/Khody31/selfdrivingdatabase/SelfDrivingDatabaseApplicationTests.java new file mode 100644 index 0000000..f4b26d6 --- /dev/null +++ b/lab-04-spring/src/test/java/com/Khody31/selfdrivingdatabase/SelfDrivingDatabaseApplicationTests.java @@ -0,0 +1,13 @@ +package com.Khody31.selfdrivingdatabase; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class SelfDrivingDatabaseApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/self-driving-database/.gitignore b/self-driving-database/.gitignore new file mode 100644 index 0000000..c2065bc --- /dev/null +++ b/self-driving-database/.gitignore @@ -0,0 +1,37 @@ +HELP.md +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ diff --git a/self-driving-database/build.gradle b/self-driving-database/build.gradle new file mode 100644 index 0000000..64e4e85 --- /dev/null +++ b/self-driving-database/build.gradle @@ -0,0 +1,33 @@ +plugins { + id 'org.springframework.boot' version '2.6.0' + id 'io.spring.dependency-management' version '1.0.11.RELEASE' + id 'java' +} + +group = 'com.example' +version = '0.0.1-SNAPSHOT' +sourceCompatibility = '17' + +configurations { + compileOnly { + extendsFrom annotationProcessor + } +} + +repositories { + mavenCentral() +} + +dependencies { + implementation 'org.springframework.boot:spring-boot-starter-thymeleaf' + implementation 'org.springframework.boot:spring-boot-starter-web' + implementation 'org.springframework.boot:spring-boot-starter-web-services' + compileOnly 'org.projectlombok:lombok' + runtimeOnly 'org.postgresql:postgresql' + annotationProcessor 'org.projectlombok:lombok' + testImplementation 'org.springframework.boot:spring-boot-starter-test' +} + +test { + useJUnitPlatform() +} diff --git a/self-driving-database/gradle/wrapper/gradle-wrapper.jar b/self-driving-database/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..7454180 Binary files /dev/null and b/self-driving-database/gradle/wrapper/gradle-wrapper.jar differ diff --git a/self-driving-database/gradle/wrapper/gradle-wrapper.properties b/self-driving-database/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..ffed3a2 --- /dev/null +++ b/self-driving-database/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-7.2-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/self-driving-database/gradlew b/self-driving-database/gradlew new file mode 100755 index 0000000..1b6c787 --- /dev/null +++ b/self-driving-database/gradlew @@ -0,0 +1,234 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${0##*/} + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/self-driving-database/gradlew.bat b/self-driving-database/gradlew.bat new file mode 100644 index 0000000..ac1b06f --- /dev/null +++ b/self-driving-database/gradlew.bat @@ -0,0 +1,89 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/self-driving-database/settings.gradle b/self-driving-database/settings.gradle new file mode 100644 index 0000000..1edd9d5 --- /dev/null +++ b/self-driving-database/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'self-driving-database' diff --git a/self-driving-database/src/main/java/com/example/selfdrivingdatabase/MainController.java b/self-driving-database/src/main/java/com/example/selfdrivingdatabase/MainController.java new file mode 100644 index 0000000..29ac2ed --- /dev/null +++ b/self-driving-database/src/main/java/com/example/selfdrivingdatabase/MainController.java @@ -0,0 +1,13 @@ +package com.example.selfdrivingdatabase; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; + +@Controller +public class MainController { + + @GetMapping("/") + String mainPage() { + return "main_page"; + } +} diff --git a/self-driving-database/src/main/java/com/example/selfdrivingdatabase/SelfDrivingDatabaseApplication.java b/self-driving-database/src/main/java/com/example/selfdrivingdatabase/SelfDrivingDatabaseApplication.java new file mode 100644 index 0000000..395d134 --- /dev/null +++ b/self-driving-database/src/main/java/com/example/selfdrivingdatabase/SelfDrivingDatabaseApplication.java @@ -0,0 +1,13 @@ +package com.example.selfdrivingdatabase; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SelfDrivingDatabaseApplication { + + public static void main(String[] args) { + SpringApplication.run(SelfDrivingDatabaseApplication.class, args); + } + +} diff --git a/self-driving-database/src/main/resources/application.properties b/self-driving-database/src/main/resources/application.properties new file mode 100644 index 0000000..13c4771 --- /dev/null +++ b/self-driving-database/src/main/resources/application.properties @@ -0,0 +1,6 @@ +spring.datasource.url=jdbc:postgresql://localhost:5432/self-driving-database +spring.datasource.username=postgres +spring.datasource.password=lizaonelove +spring.datasource.driver-class-name=org.postgresql.Driver +spring.jpa.hibernate.ddl-auto=update +server.port=8081 \ No newline at end of file diff --git a/self-driving-database/src/main/resources/templates/main_page.html b/self-driving-database/src/main/resources/templates/main_page.html new file mode 100644 index 0000000..88d4a64 --- /dev/null +++ b/self-driving-database/src/main/resources/templates/main_page.html @@ -0,0 +1,10 @@ + + + + + MainPage + + +MainPage + + \ No newline at end of file diff --git a/self-driving-database/src/test/java/com/example/selfdrivingdatabase/SelfDrivingDatabaseApplicationTests.java b/self-driving-database/src/test/java/com/example/selfdrivingdatabase/SelfDrivingDatabaseApplicationTests.java new file mode 100644 index 0000000..d739e55 --- /dev/null +++ b/self-driving-database/src/test/java/com/example/selfdrivingdatabase/SelfDrivingDatabaseApplicationTests.java @@ -0,0 +1,13 @@ +package com.example.selfdrivingdatabase; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class SelfDrivingDatabaseApplicationTests { + + @Test + void contextLoads() { + } + +}