diff --git a/.gitignore b/.gitignore index a1c2a23..667aaef 100644 --- a/.gitignore +++ b/.gitignore @@ -1,23 +1,33 @@ -# Compiled class file -*.class +HELP.md +target/ +.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ -# Log file -*.log +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache -# BlueJ files -*.ctxt +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr -# Mobile Tools for Java (J2ME) -.mtj.tmp/ +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ -# Package Files # -*.jar -*.war -*.nar -*.ear -*.zip -*.tar.gz -*.rar - -# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml -hs_err_pid* +### VS Code ### +.vscode/ diff --git a/.idea/compiler.xml b/.idea/compiler.xml new file mode 100644 index 0000000..4651d2b --- /dev/null +++ b/.idea/compiler.xml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/encodings.xml b/.idea/encodings.xml new file mode 100644 index 0000000..f5bc3e7 --- /dev/null +++ b/.idea/encodings.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/jarRepositories.xml b/.idea/jarRepositories.xml new file mode 100644 index 0000000..712ab9d --- /dev/null +++ b/.idea/jarRepositories.xml @@ -0,0 +1,20 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml index a9182a4..a0e1fc4 100644 --- a/.idea/misc.xml +++ b/.idea/misc.xml @@ -1,6 +1,14 @@ - + + + + + \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml index 354f839..93698a5 100644 --- a/.idea/modules.xml +++ b/.idea/modules.xml @@ -2,7 +2,7 @@ - + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml index 8306744..35eb1dd 100644 --- a/.idea/vcs.xml +++ b/.idea/vcs.xml @@ -2,6 +2,5 @@ - \ No newline at end of file diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..c0bcafe --- /dev/null +++ b/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,3 @@ +wrapperVersion=3.3.4 +distributionType=only-script +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.11/apache-maven-3.9.11-bin.zip diff --git a/README.md b/README.md index 353a9b5..a62a63c 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,2 @@ # java-kanban -Repository for homework project. +Repository for homework project. diff --git a/java-kanban.iml b/java-kanban.iml deleted file mode 100644 index 66c15d2..0000000 --- a/java-kanban.iml +++ /dev/null @@ -1,28 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/lib/apiguardian-api-1.1.2.jar b/lib/apiguardian-api-1.1.2.jar new file mode 100644 index 0000000..2b678e1 Binary files /dev/null and b/lib/apiguardian-api-1.1.2.jar differ diff --git a/lib/junit-jupiter-5.8.1.jar b/lib/junit-jupiter-5.8.1.jar new file mode 100644 index 0000000..730b9ae Binary files /dev/null and b/lib/junit-jupiter-5.8.1.jar differ diff --git a/lib/junit-jupiter-api-5.8.1.jar b/lib/junit-jupiter-api-5.8.1.jar new file mode 100644 index 0000000..8424eca Binary files /dev/null and b/lib/junit-jupiter-api-5.8.1.jar differ diff --git a/lib/junit-jupiter-engine-5.8.1.jar b/lib/junit-jupiter-engine-5.8.1.jar new file mode 100644 index 0000000..cfa38d2 Binary files /dev/null and b/lib/junit-jupiter-engine-5.8.1.jar differ diff --git a/lib/junit-jupiter-params-5.8.1.jar b/lib/junit-jupiter-params-5.8.1.jar new file mode 100644 index 0000000..1e4d0ec Binary files /dev/null and b/lib/junit-jupiter-params-5.8.1.jar differ diff --git a/lib/junit-platform-commons-1.8.1.jar b/lib/junit-platform-commons-1.8.1.jar new file mode 100644 index 0000000..20185cd Binary files /dev/null and b/lib/junit-platform-commons-1.8.1.jar differ diff --git a/lib/junit-platform-engine-1.8.1.jar b/lib/junit-platform-engine-1.8.1.jar new file mode 100644 index 0000000..54ce076 Binary files /dev/null and b/lib/junit-platform-engine-1.8.1.jar differ diff --git a/lib/opentest4j-1.2.0.jar b/lib/opentest4j-1.2.0.jar new file mode 100644 index 0000000..d500636 Binary files /dev/null and b/lib/opentest4j-1.2.0.jar differ diff --git a/mvnw b/mvnw new file mode 100644 index 0000000..bd8896b --- /dev/null +++ b/mvnw @@ -0,0 +1,295 @@ +#!/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 +# +# http://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. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Apache Maven Wrapper startup batch script, version 3.3.4 +# +# Optional ENV vars +# ----------------- +# JAVA_HOME - location of a JDK home dir, required when download maven via java source +# MVNW_REPOURL - repo url base for downloading maven distribution +# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output +# ---------------------------------------------------------------------------- + +set -euf +[ "${MVNW_VERBOSE-}" != debug ] || set -x + +# OS specific support. +native_path() { printf %s\\n "$1"; } +case "$(uname)" in +CYGWIN* | MINGW*) + [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")" + native_path() { cygpath --path --windows "$1"; } + ;; +esac + +# set JAVACMD and JAVACCMD +set_java_home() { + # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched + 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" + JAVACCMD="$JAVA_HOME/jre/sh/javac" + else + JAVACMD="$JAVA_HOME/bin/java" + JAVACCMD="$JAVA_HOME/bin/javac" + + if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then + echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2 + echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2 + return 1 + fi + fi + else + JAVACMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v java + )" || : + JAVACCMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v javac + )" || : + + if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then + echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2 + return 1 + fi + fi +} + +# hash string like Java String::hashCode +hash_string() { + str="${1:-}" h=0 + while [ -n "$str" ]; do + char="${str%"${str#?}"}" + h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296)) + str="${str#?}" + done + printf %x\\n $h +} + +verbose() { :; } +[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; } + +die() { + printf %s\\n "$1" >&2 + exit 1 +} + +trim() { + # MWRAPPER-139: + # Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds. + # Needed for removing poorly interpreted newline sequences when running in more + # exotic environments such as mingw bash on Windows. + printf "%s" "${1}" | tr -d '[:space:]' +} + +scriptDir="$(dirname "$0")" +scriptName="$(basename "$0")" + +# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties +while IFS="=" read -r key value; do + case "${key-}" in + distributionUrl) distributionUrl=$(trim "${value-}") ;; + distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;; + esac +done <"$scriptDir/.mvn/wrapper/maven-wrapper.properties" +[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" + +case "${distributionUrl##*/}" in +maven-mvnd-*bin.*) + MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ + case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in + *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;; + :Darwin*x86_64) distributionPlatform=darwin-amd64 ;; + :Darwin*arm64) distributionPlatform=darwin-aarch64 ;; + :Linux*x86_64*) distributionPlatform=linux-amd64 ;; + *) + echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2 + distributionPlatform=linux-amd64 + ;; + esac + distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip" + ;; +maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;; +*) MVN_CMD="mvn${scriptName#mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;; +esac + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}" +distributionUrlName="${distributionUrl##*/}" +distributionUrlNameMain="${distributionUrlName%.*}" +distributionUrlNameMain="${distributionUrlNameMain%-bin}" +MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}" +MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")" + +exec_maven() { + unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || : + exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD" +} + +if [ -d "$MAVEN_HOME" ]; then + verbose "found existing MAVEN_HOME at $MAVEN_HOME" + exec_maven "$@" +fi + +case "${distributionUrl-}" in +*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;; +*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;; +esac + +# prepare tmp dir +if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then + clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; } + trap clean HUP INT TERM EXIT +else + die "cannot create temp dir" +fi + +mkdir -p -- "${MAVEN_HOME%/*}" + +# Download and Install Apache Maven +verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +verbose "Downloading from: $distributionUrl" +verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +# select .zip or .tar.gz +if ! command -v unzip >/dev/null; then + distributionUrl="${distributionUrl%.zip}.tar.gz" + distributionUrlName="${distributionUrl##*/}" +fi + +# verbose opt +__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR='' +[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v + +# normalize http auth +case "${MVNW_PASSWORD:+has-password}" in +'') MVNW_USERNAME='' MVNW_PASSWORD='' ;; +has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;; +esac + +if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then + verbose "Found wget ... using wget" + wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl" +elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then + verbose "Found curl ... using curl" + curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl" +elif set_java_home; then + verbose "Falling back to use Java to download" + javaSource="$TMP_DOWNLOAD_DIR/Downloader.java" + targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName" + cat >"$javaSource" <<-END + public class Downloader extends java.net.Authenticator + { + protected java.net.PasswordAuthentication getPasswordAuthentication() + { + return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() ); + } + public static void main( String[] args ) throws Exception + { + setDefault( new Downloader() ); + java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() ); + } + } + END + # For Cygwin/MinGW, switch paths to Windows format before running javac and java + verbose " - Compiling Downloader.java ..." + "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java" + verbose " - Running Downloader.java ..." + "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")" +fi + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +if [ -n "${distributionSha256Sum-}" ]; then + distributionSha256Result=false + if [ "$MVN_CMD" = mvnd.sh ]; then + echo "Checksum validation is not supported for maven-mvnd." >&2 + echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + elif command -v sha256sum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c - >/dev/null 2>&1; then + distributionSha256Result=true + fi + elif command -v shasum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + else + echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2 + echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + fi + if [ $distributionSha256Result = false ]; then + echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2 + echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2 + exit 1 + fi +fi + +# unzip and move +if command -v unzip >/dev/null; then + unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip" +else + tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar" +fi + +# Find the actual extracted directory name (handles snapshots where filename != directory name) +actualDistributionDir="" + +# First try the expected directory name (for regular distributions) +if [ -d "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" ]; then + if [ -f "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/bin/$MVN_CMD" ]; then + actualDistributionDir="$distributionUrlNameMain" + fi +fi + +# If not found, search for any directory with the Maven executable (for snapshots) +if [ -z "$actualDistributionDir" ]; then + # enable globbing to iterate over items + set +f + for dir in "$TMP_DOWNLOAD_DIR"/*; do + if [ -d "$dir" ]; then + if [ -f "$dir/bin/$MVN_CMD" ]; then + actualDistributionDir="$(basename "$dir")" + break + fi + fi + done + set -f +fi + +if [ -z "$actualDistributionDir" ]; then + verbose "Contents of $TMP_DOWNLOAD_DIR:" + verbose "$(ls -la "$TMP_DOWNLOAD_DIR")" + die "Could not find Maven distribution directory in extracted archive" +fi + +verbose "Found extracted Maven distribution directory: $actualDistributionDir" +printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$actualDistributionDir/mvnw.url" +mv -- "$TMP_DOWNLOAD_DIR/$actualDistributionDir" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" + +clean || : +exec_maven "$@" diff --git a/mvnw.cmd b/mvnw.cmd new file mode 100644 index 0000000..92450f9 --- /dev/null +++ b/mvnw.cmd @@ -0,0 +1,189 @@ +<# : batch portion +@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 http://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 Apache Maven Wrapper startup batch script, version 3.3.4 +@REM +@REM Optional ENV vars +@REM MVNW_REPOURL - repo url base for downloading maven distribution +@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output +@REM ---------------------------------------------------------------------------- + +@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) +@SET __MVNW_CMD__= +@SET __MVNW_ERROR__= +@SET __MVNW_PSMODULEP_SAVE=%PSModulePath% +@SET PSModulePath= +@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( + IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) +) +@SET PSModulePath=%__MVNW_PSMODULEP_SAVE% +@SET __MVNW_PSMODULEP_SAVE= +@SET __MVNW_ARG0_NAME__= +@SET MVNW_USERNAME= +@SET MVNW_PASSWORD= +@IF NOT "%__MVNW_CMD__%"=="" ("%__MVNW_CMD__%" %*) +@echo Cannot start maven from wrapper >&2 && exit /b 1 +@GOTO :EOF +: end batch / begin powershell #> + +$ErrorActionPreference = "Stop" +if ($env:MVNW_VERBOSE -eq "true") { + $VerbosePreference = "Continue" +} + +# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties +$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl +if (!$distributionUrl) { + Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" +} + +switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { + "maven-mvnd-*" { + $USE_MVND = $true + $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" + $MVN_CMD = "mvnd.cmd" + break + } + default { + $USE_MVND = $false + $MVN_CMD = $script -replace '^mvnw','mvn' + break + } +} + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +if ($env:MVNW_REPOURL) { + $MVNW_REPO_PATTERN = if ($USE_MVND -eq $False) { "/org/apache/maven/" } else { "/maven/mvnd/" } + $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace "^.*$MVNW_REPO_PATTERN",'')" +} +$distributionUrlName = $distributionUrl -replace '^.*/','' +$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' + +$MAVEN_M2_PATH = "$HOME/.m2" +if ($env:MAVEN_USER_HOME) { + $MAVEN_M2_PATH = "$env:MAVEN_USER_HOME" +} + +if (-not (Test-Path -Path $MAVEN_M2_PATH)) { + New-Item -Path $MAVEN_M2_PATH -ItemType Directory | Out-Null +} + +$MAVEN_WRAPPER_DISTS = $null +if ((Get-Item $MAVEN_M2_PATH).Target[0] -eq $null) { + $MAVEN_WRAPPER_DISTS = "$MAVEN_M2_PATH/wrapper/dists" +} else { + $MAVEN_WRAPPER_DISTS = (Get-Item $MAVEN_M2_PATH).Target[0] + "/wrapper/dists" +} + +$MAVEN_HOME_PARENT = "$MAVEN_WRAPPER_DISTS/$distributionUrlNameMain" +$MAVEN_HOME_NAME = ([System.Security.Cryptography.SHA256]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' +$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" + +if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { + Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" + Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" + exit $? +} + +if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { + Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" +} + +# prepare tmp dir +$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile +$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" +$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null +trap { + if ($TMP_DOWNLOAD_DIR.Exists) { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } + } +} + +New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null + +# Download and Install Apache Maven +Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +Write-Verbose "Downloading from: $distributionUrl" +Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +$webclient = New-Object System.Net.WebClient +if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { + $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) +} +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 +$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum +if ($distributionSha256Sum) { + if ($USE_MVND) { + Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." + } + Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash + if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { + Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." + } +} + +# unzip and move +Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null + +# Find the actual extracted directory name (handles snapshots where filename != directory name) +$actualDistributionDir = "" + +# First try the expected directory name (for regular distributions) +$expectedPath = Join-Path "$TMP_DOWNLOAD_DIR" "$distributionUrlNameMain" +$expectedMvnPath = Join-Path "$expectedPath" "bin/$MVN_CMD" +if ((Test-Path -Path $expectedPath -PathType Container) -and (Test-Path -Path $expectedMvnPath -PathType Leaf)) { + $actualDistributionDir = $distributionUrlNameMain +} + +# If not found, search for any directory with the Maven executable (for snapshots) +if (!$actualDistributionDir) { + Get-ChildItem -Path "$TMP_DOWNLOAD_DIR" -Directory | ForEach-Object { + $testPath = Join-Path $_.FullName "bin/$MVN_CMD" + if (Test-Path -Path $testPath -PathType Leaf) { + $actualDistributionDir = $_.Name + } + } +} + +if (!$actualDistributionDir) { + Write-Error "Could not find Maven distribution directory in extracted archive" +} + +Write-Verbose "Found extracted Maven distribution directory: $actualDistributionDir" +Rename-Item -Path "$TMP_DOWNLOAD_DIR/$actualDistributionDir" -NewName $MAVEN_HOME_NAME | Out-Null +try { + Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null +} catch { + if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { + Write-Error "fail to move MAVEN_HOME" + } +} finally { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } +} + +Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..d8eb988 --- /dev/null +++ b/pom.xml @@ -0,0 +1,43 @@ + + + 4.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 2.7.12 + + + + ru.yandex.practicum + filmorate + 1.0.0 + + + 11 + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + \ No newline at end of file diff --git a/src/Main.java b/src/Main.java deleted file mode 100644 index c49ce75..0000000 --- a/src/Main.java +++ /dev/null @@ -1,40 +0,0 @@ -import manager.Managers; -import manager.TaskManager; -import model.Task; -import model.Epic; -import model.Subtask; -import model.Status; - -public class Main { - public static void main(String[] args) { - TaskManager taskManager = Managers.getDefault(); - - System.out.println("=== Создание задач ===ее"); - - Task task1 = taskManager.createTask(new Task("Задача 1", "Описание задачи 1", Status.NEW)); - Task task2 = taskManager.createTask(new Task("Задача 2", "Описание задачи 2", Status.NEW)); - - Epic epic1 = taskManager.createEpic(new Epic("Эпик 1", "Описание эпика 1")); - Subtask subtask1 = taskManager.createSubtask(new Subtask("Подзадача 1", "Описание подзадачи 1", Status.NEW, epic1.getId())); - Subtask subtask2 = taskManager.createSubtask(new Subtask("Подзадача 2", "Описание подзадачи 2", Status.NEW, epic1.getId())); - - // Просматриваем задачи - taskManager.getTaskById(task1.getId()); - taskManager.getEpicById(epic1.getId()); - taskManager.getSubtaskById(subtask1.getId()); - - System.out.println("История просмотров:"); - for (Task task : taskManager.getHistory()) { - System.out.println(task); - } - - System.out.println("=== Просматриваем еще задачи ==="); - taskManager.getTaskById(task2.getId()); - taskManager.getSubtaskById(subtask2.getId()); - - System.out.println("Обновленная история:"); - for (Task task : taskManager.getHistory()) { - System.out.println(task); - } - } -} \ No newline at end of file diff --git a/src/main/java/FilmorateApplication.java b/src/main/java/FilmorateApplication.java new file mode 100644 index 0000000..4a13108 --- /dev/null +++ b/src/main/java/FilmorateApplication.java @@ -0,0 +1,11 @@ +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.ComponentScan; + +@SpringBootApplication +@ComponentScan(basePackages = {"controllers", "model", "exception"}) +public class FilmorateApplication { + public static void main(String[] args) { + SpringApplication.run(FilmorateApplication.class, args); + } +} \ No newline at end of file diff --git a/src/main/java/controllers/ErrorHandler.java b/src/main/java/controllers/ErrorHandler.java new file mode 100644 index 0000000..d933453 --- /dev/null +++ b/src/main/java/controllers/ErrorHandler.java @@ -0,0 +1,24 @@ +package controllers; + +import exception.ValidationException; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestControllerAdvice; +import java.util.Map; + +@RestControllerAdvice +public class ErrorHandler { + + @ExceptionHandler + @ResponseStatus(HttpStatus.BAD_REQUEST) + public Map handleValidation(final ValidationException e) { + return Map.of("error", e.getMessage()); + } + + @ExceptionHandler + @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) + public Map handleRuntime(final RuntimeException e) { + return Map.of("error", "Произошла непредвиденная ошибка."); + } +} \ No newline at end of file diff --git a/src/main/java/controllers/FilmController.java b/src/main/java/controllers/FilmController.java new file mode 100644 index 0000000..f2067bc --- /dev/null +++ b/src/main/java/controllers/FilmController.java @@ -0,0 +1,64 @@ +package controllers; + +import exception.ValidationException; +import model.Film; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.web.bind.annotation.*; + +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@RestController +@RequestMapping("/films") +public class FilmController { + private static final Logger log = LoggerFactory.getLogger(FilmController.class); + + private final Map films = new HashMap<>(); + private int idCounter = 1; + private static final LocalDate MIN_RELEASE_DATE = LocalDate.of(1895, 12, 28); + + @GetMapping + public List findAll() { + return new ArrayList<>(films.values()); + } + + @PostMapping + public Film create(@RequestBody Film film) { + validate(film); + film.setId(idCounter++); + films.put(film.getId(), film); + log.info("Добавлен фильм: {}", film); + return film; + } + + @PutMapping + public Film update(@RequestBody Film film) { + validate(film); + if (!films.containsKey(film.getId())) { + log.warn("Попытка обновления несуществующего фильма с id {}", film.getId()); + throw new ValidationException("Фильм с таким id не найден"); + } + films.put(film.getId(), film); + log.info("Обновлен фильм: {}", film); + return film; + } + + private void validate(Film film) { + if (film.getName() == null || film.getName().isBlank()) { + throw new ValidationException("Название не может быть пустым"); + } + if (film.getDescription() != null && film.getDescription().length() > 200) { + throw new ValidationException("Максимальная длина описания — 200 символов"); + } + if (film.getReleaseDate() == null || film.getReleaseDate().isBefore(MIN_RELEASE_DATE)) { + throw new ValidationException("Дата релиза — не раньше 28 декабря 1895 года"); + } + if (film.getDuration() <= 0) { + throw new ValidationException("Продолжительность фильма должна быть положительной"); + } + } +} \ No newline at end of file diff --git a/src/main/java/controllers/UserController.java b/src/main/java/controllers/UserController.java new file mode 100644 index 0000000..08cfa46 --- /dev/null +++ b/src/main/java/controllers/UserController.java @@ -0,0 +1,67 @@ +package controllers; + +import exception.ValidationException; +import model.User; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.web.bind.annotation.*; + +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@RestController +@RequestMapping("/users") +public class UserController { + private static final Logger log = LoggerFactory.getLogger(UserController.class); + + private final Map users = new HashMap<>(); + private int idCounter = 1; + + @GetMapping + public List findAll() { + return new ArrayList<>(users.values()); + } + + @PostMapping + public User create(@RequestBody User user) { + validate(user); + if (user.getName() == null || user.getName().isBlank()) { + user.setName(user.getLogin()); + } + user.setId(idCounter++); + users.put(user.getId(), user); + log.info("Создан пользователь: {}", user); + return user; + } + + @PutMapping + public User update(@RequestBody User user) { + validate(user); + if (!users.containsKey(user.getId())) { + log.warn("Попытка обновления несуществующего пользователя с id {}", user.getId()); + throw new ValidationException("Пользователь с таким id не найден"); + } + + if (user.getName() == null || user.getName().isBlank()) { + user.setName(user.getLogin()); + } + users.put(user.getId(), user); + log.info("Обновлен пользователь: {}", user); + return user; + } + + private void validate(User user) { + if (user.getEmail() == null || user.getEmail().isBlank() || !user.getEmail().contains("@")) { + throw new ValidationException("Электронная почта не может быть пустой и должна содержать символ @"); + } + if (user.getLogin() == null || user.getLogin().isBlank() || user.getLogin().contains(" ")) { + throw new ValidationException("Логин не может быть пустым и содержать пробелы"); + } + if (user.getBirthday() != null && user.getBirthday().isAfter(LocalDate.now())) { + throw new ValidationException("Дата рождения не может быть в будущем"); + } + } +} \ No newline at end of file diff --git a/src/main/java/exception/ValidationException.java b/src/main/java/exception/ValidationException.java new file mode 100644 index 0000000..06e07ae --- /dev/null +++ b/src/main/java/exception/ValidationException.java @@ -0,0 +1,7 @@ +package exception; + +public class ValidationException extends RuntimeException { + public ValidationException(String message) { + super(message); + } +} \ No newline at end of file diff --git a/src/main/java/model/Film.java b/src/main/java/model/Film.java new file mode 100644 index 0000000..d303502 --- /dev/null +++ b/src/main/java/model/Film.java @@ -0,0 +1,51 @@ +package model; + +import java.time.LocalDate; + +public class Film { + private int id; + private String name; + private String description; + private LocalDate releaseDate; + private int duration; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public LocalDate getReleaseDate() { + return releaseDate; + } + + public void setReleaseDate(LocalDate releaseDate) { + this.releaseDate = releaseDate; + } + + public int getDuration() { + return duration; + } + + public void setDuration(int duration) { + this.duration = duration; + } +} \ No newline at end of file diff --git a/src/main/java/model/User.java b/src/main/java/model/User.java new file mode 100644 index 0000000..ad301a6 --- /dev/null +++ b/src/main/java/model/User.java @@ -0,0 +1,51 @@ +package model; + +import java.time.LocalDate; + +public class User { + private int id; + private String email; + private String login; + private String name; + private LocalDate birthday; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getLogin() { + return login; + } + + public void setLogin(String login) { + this.login = login; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public LocalDate getBirthday() { + return birthday; + } + + public void setBirthday(LocalDate birthday) { + this.birthday = birthday; + } +} \ No newline at end of file diff --git a/src/manager/HistoryManager.java b/src/manager/HistoryManager.java deleted file mode 100644 index 6070997..0000000 --- a/src/manager/HistoryManager.java +++ /dev/null @@ -1,9 +0,0 @@ -package manager; - -import model.Task; -import java.util.List; - -public interface HistoryManager { - void add(Task task); - List getHistory(); -} \ No newline at end of file diff --git a/src/manager/InMemoryHistoryManager.java b/src/manager/InMemoryHistoryManager.java deleted file mode 100644 index aee6b0d..0000000 --- a/src/manager/InMemoryHistoryManager.java +++ /dev/null @@ -1,25 +0,0 @@ -package manager; - -import model.Task; -import java.util.ArrayList; -import java.util.List; - -public class InMemoryHistoryManager implements HistoryManager { - private static final int MAX_HISTORY_SIZE = 10; - private final List history = new ArrayList<>(); - - @Override - public void add(Task task) { - if (task == null) return; - - if (history.size() >= MAX_HISTORY_SIZE) { - history.removeFirst(); // Удаляем самый старый элемент - } - history.add(task); - } - - @Override - public List getHistory() { - return new ArrayList<>(history); - } -} \ No newline at end of file diff --git a/src/manager/InMemoryTaskManager.java b/src/manager/InMemoryTaskManager.java deleted file mode 100644 index 9b107ab..0000000 --- a/src/manager/InMemoryTaskManager.java +++ /dev/null @@ -1,213 +0,0 @@ -package manager; - -import model.Task; -import model.Epic; -import model.Subtask; -import model.Status; -import java.util.*; - -public class InMemoryTaskManager implements TaskManager { - private final Map tasks = new HashMap<>(); - private final Map epics = new HashMap<>(); - private final Map subtasks = new HashMap<>(); - private final HistoryManager historyManager; - private int nextId = 1; - - public InMemoryTaskManager() { - this.historyManager = Managers.getDefaultHistory(); - } - - private int generateId() { return nextId++; } - - // Модифицируем методы получения задач для добавления в историю - @Override - public Task getTaskById(int id) { - Task task = tasks.get(id); - if (task != null) { - historyManager.add(task); - } - return task; - } - - @Override - public Epic getEpicById(int id) { - Epic epic = epics.get(id); - if (epic != null) { - historyManager.add(epic); - } - return epic; - } - - @Override - public Subtask getSubtaskById(int id) { - Subtask subtask = subtasks.get(id); - if (subtask != null) { - historyManager.add(subtask); - } - return subtask; - } - - // Добавляем метод для получения истории - @Override - public List getHistory() { - return historyManager.getHistory(); - } - - // Остальные методы остаются без изменений... - @Override public List getAllTasks() { return new ArrayList<>(tasks.values()); } - - @Override - public void deleteAllTasks() { tasks.clear(); } - - @Override - public Task createTask(Task task) { - if (task == null) return null; - Task newTask = new Task(task.getName(), task.getDescription(), generateId(), task.getStatus()); - tasks.put(newTask.getId(), newTask); - return newTask; - } - - @Override - public void updateTask(Task task) { - if (task == null || !tasks.containsKey(task.getId())) return; - tasks.put(task.getId(), task); - } - - @Override - public void deleteTaskById(int id) { tasks.remove(id); } - - @Override - public List getAllEpics() { return new ArrayList<>(epics.values()); } - - @Override - public void deleteAllEpics() { - for (Epic epic : epics.values()) { - for (Integer subtaskId : epic.getSubtaskIds()) { - subtasks.remove(subtaskId); - } - } - epics.clear(); - } - - @Override - public Epic createEpic(Epic epic) { - if (epic == null) return null; - Epic newEpic = new Epic(epic.getName(), epic.getDescription()); - newEpic.setId(generateId()); - epics.put(newEpic.getId(), newEpic); - return newEpic; - } - - @Override - public void updateEpic(Epic epic) { - if (epic == null || !epics.containsKey(epic.getId())) return; - Epic existingEpic = epics.get(epic.getId()); - existingEpic.setName(epic.getName()); - existingEpic.setDescription(epic.getDescription()); - } - - @Override - public void deleteEpicById(int id) { - Epic epic = epics.get(id); - if (epic != null) { - for (Integer subtaskId : epic.getSubtaskIds()) { - subtasks.remove(subtaskId); - } - epics.remove(id); - } - } - - @Override - public List getAllSubtasks() { return new ArrayList<>(subtasks.values()); } - - @Override - public void deleteAllSubtasks() { - for (Epic epic : epics.values()) { - epic.clearSubtasks(); - updateEpicStatus(epic.getId()); - } - subtasks.clear(); - } - - @Override - public Subtask createSubtask(Subtask subtask) { - if (subtask == null || !epics.containsKey(subtask.getEpicId())) return null; - Subtask newSubtask = new Subtask(subtask.getName(), subtask.getDescription(), generateId(), subtask.getStatus(), subtask.getEpicId()); - subtasks.put(newSubtask.getId(), newSubtask); - Epic epic = epics.get(newSubtask.getEpicId()); - epic.addSubtaskId(newSubtask.getId()); - updateEpicStatus(epic.getId()); - return newSubtask; - } - - @Override - public void updateSubtask(Subtask subtask) { - if (subtask == null || !subtasks.containsKey(subtask.getId())) return; - Subtask existingSubtask = subtasks.get(subtask.getId()); - int oldEpicId = existingSubtask.getEpicId(); - int newEpicId = subtask.getEpicId(); - - if (oldEpicId != newEpicId) { - Epic oldEpic = epics.get(oldEpicId); - if (oldEpic != null) { - oldEpic.removeSubtaskId(subtask.getId()); - updateEpicStatus(oldEpicId); - } - Epic newEpic = epics.get(newEpicId); - if (newEpic != null) { - newEpic.addSubtaskId(subtask.getId()); - } - } - - subtasks.put(subtask.getId(), subtask); - updateEpicStatus(subtask.getEpicId()); - } - - @Override - public void deleteSubtaskById(int id) { - Subtask subtask = subtasks.get(id); - if (subtask != null) { - Epic epic = epics.get(subtask.getEpicId()); - if (epic != null) { - epic.removeSubtaskId(id); - updateEpicStatus(epic.getId()); - } - subtasks.remove(id); - } - } - - @Override - public List getSubtasksByEpicId(int epicId) { - List result = new ArrayList<>(); - Epic epic = epics.get(epicId); - if (epic != null) { - for (Integer subtaskId : epic.getSubtaskIds()) { - Subtask subtask = subtasks.get(subtaskId); - if (subtask != null) result.add(subtask); - } - } - return result; - } - - private void updateEpicStatus(int epicId) { - Epic epic = epics.get(epicId); - if (epic == null) return; - List subtaskIds = epic.getSubtaskIds(); - if (subtaskIds.isEmpty()) { - epic.updateStatus(Status.NEW); - return; - } - boolean allDone = true; - boolean allNew = true; - for (Integer subtaskId : subtaskIds) { - Subtask subtask = subtasks.get(subtaskId); - if (subtask == null) continue; - if (subtask.getStatus() != Status.DONE) allDone = false; - if (subtask.getStatus() != Status.NEW) allNew = false; - if (!allDone && !allNew) break; - } - if (allDone) epic.updateStatus(Status.DONE); - else if (allNew) epic.updateStatus(Status.NEW); - else epic.updateStatus(Status.IN_PROGRESS); - } -} \ No newline at end of file diff --git a/src/manager/Managers.java b/src/manager/Managers.java deleted file mode 100644 index 64dfb6f..0000000 --- a/src/manager/Managers.java +++ /dev/null @@ -1,12 +0,0 @@ -package manager; - -public class Managers { - - public static TaskManager getDefault() { - return new InMemoryTaskManager(); - } - - public static HistoryManager getDefaultHistory() { - return new InMemoryHistoryManager(); - } -} \ No newline at end of file diff --git a/src/manager/TaskManager.java b/src/manager/TaskManager.java deleted file mode 100644 index 09e55fa..0000000 --- a/src/manager/TaskManager.java +++ /dev/null @@ -1,34 +0,0 @@ -package manager; - -import model.Task; -import model.Epic; -import model.Subtask; -import java.util.List; - -public interface TaskManager { - List getAllTasks(); - void deleteAllTasks(); - Task getTaskById(int id); - Task createTask(Task task); - void updateTask(Task task); - void deleteTaskById(int id); - - List getAllEpics(); - void deleteAllEpics(); - Epic getEpicById(int id); - Epic createEpic(Epic epic); - void updateEpic(Epic epic); - void deleteEpicById(int id); - - List getAllSubtasks(); - void deleteAllSubtasks(); - Subtask getSubtaskById(int id); - Subtask createSubtask(Subtask subtask); - void updateSubtask(Subtask subtask); - void deleteSubtaskById(int id); - - List getSubtasksByEpicId(int epicId); - - // Новый метод для получения истории - List getHistory(); -} \ No newline at end of file diff --git a/src/model/Epic.java b/src/model/Epic.java deleted file mode 100644 index 6634160..0000000 --- a/src/model/Epic.java +++ /dev/null @@ -1,31 +0,0 @@ -package model; - -import java.util.ArrayList; -import java.util.List; - -public class Epic extends Task { - private List subtaskIds; - - public Epic(String name, String description) { - super(name, description, Status.NEW); - this.subtaskIds = new ArrayList<>(); - } - - public List getSubtaskIds() { return new ArrayList<>(subtaskIds); } - public void addSubtaskId(int subtaskId) { if (!subtaskIds.contains(subtaskId)) subtaskIds.add(subtaskId); } - public void removeSubtaskId(int subtaskId) { subtaskIds.remove(Integer.valueOf(subtaskId)); } - public void clearSubtasks() { subtaskIds.clear(); } - - @Override - public void setStatus(Status status) { - throw new UnsupportedOperationException("Статус эпика рассчитывается автоматически"); - } - - public void updateStatus(Status status) { this.status = status; } - - @Override - public String toString() { - return String.format("Epic{name='%s', description='%s', id=%d, status=%s, subtaskIds=%s}", - name, description, id, status, subtaskIds); - } -} \ No newline at end of file diff --git a/src/model/Status.java b/src/model/Status.java deleted file mode 100644 index cbae870..0000000 --- a/src/model/Status.java +++ /dev/null @@ -1,7 +0,0 @@ -package model; - -public enum Status { - NEW, - IN_PROGRESS, - DONE -} \ No newline at end of file diff --git a/src/model/Subtask.java b/src/model/Subtask.java deleted file mode 100644 index d1547d7..0000000 --- a/src/model/Subtask.java +++ /dev/null @@ -1,24 +0,0 @@ -package model; - -public class Subtask extends Task { - private int epicId; - - public Subtask(String name, String description, Status status, int epicId) { - super(name, description, status); - this.epicId = epicId; - } - - public Subtask(String name, String description, int id, Status status, int epicId) { - super(name, description, id, status); - this.epicId = epicId; - } - - public int getEpicId() { return epicId; } - public void setEpicId(int epicId) { this.epicId = epicId; } - - @Override - public String toString() { - return String.format("Subtask{name='%s', description='%s', id=%d, status=%s, epicId=%d}", - name, description, id, status, epicId); - } -} \ No newline at end of file diff --git a/src/model/Task.java b/src/model/Task.java deleted file mode 100644 index 1547b36..0000000 --- a/src/model/Task.java +++ /dev/null @@ -1,49 +0,0 @@ -package model; - -import java.util.Objects; - -public class Task { - protected String name; - protected String description; - protected int id; - protected Status status; - - public Task(String name, String description, Status status) { - this.name = name; - this.description = description; - this.status = status; - } - - public Task(String name, String description, int id, Status status) { - this.name = name; - this.description = description; - this.id = id; - this.status = status; - } - - public String getName() { return name; } - public void setName(String name) { this.name = name; } - public String getDescription() { return description; } - public void setDescription(String description) { this.description = description; } - public int getId() { return id; } - public void setId(int id) { this.id = id; } - public Status getStatus() { return status; } - public void setStatus(Status status) { this.status = status; } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - Task task = (Task) o; - return id == task.id; - } - - @Override - public int hashCode() { return Objects.hash(id); } - - @Override - public String toString() { - return String.format("Task{name='%s', description='%s', id=%d, status=%s}", - name, description, id, status); - } -} \ No newline at end of file diff --git a/src/test/FilmValidationTest.java b/src/test/FilmValidationTest.java new file mode 100644 index 0000000..b933a91 --- /dev/null +++ b/src/test/FilmValidationTest.java @@ -0,0 +1,93 @@ +import controllers.FilmController; +import exception.ValidationException; +import model.Film; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.time.LocalDate; + +import static org.junit.jupiter.api.Assertions.*; + +class FilmValidationTest { + + private FilmController controller; + + @BeforeEach + void setUp() { + controller = new FilmController(); + } + + @Test + void shouldCreateFilmWithStandardData() { + Film film = new Film(); + film.setName("Titanic"); + film.setDescription("Ship crash"); + film.setDuration(120); + film.setReleaseDate(LocalDate.of(1997, 12, 19)); + + Film createdFilm = controller.create(film); + + assertNotNull(createdFilm); + assertEquals(1, createdFilm.getId()); + } + + @Test + void shouldThrowExceptionWhenNameIsEmpty() { + Film film = new Film(); + film.setName(""); // Пустое имя + film.setDescription("Description"); + film.setDuration(100); + film.setReleaseDate(LocalDate.now()); + + ValidationException exception = assertThrows(ValidationException.class, () -> { + controller.create(film); + }); + assertEquals("Название фильма не может быть пустым", exception.getMessage()); + } + + @Test + void shouldThrowExceptionWhenDescriptionIsTooLong() { + Film film = new Film(); + film.setName("Name"); + // Создаем строку длиной 201 символ + String longDescription = "a".repeat(201); + film.setDescription(longDescription); + film.setDuration(100); + film.setReleaseDate(LocalDate.now()); + + ValidationException exception = assertThrows(ValidationException.class, () -> { + controller.create(film); + }); + assertEquals("Максимальная длина описания — 200 символов", exception.getMessage()); + } + + @Test + void shouldThrowExceptionWhenReleaseDateIsTooOld() { + Film film = new Film(); + film.setName("Name"); + film.setDescription("Description"); + film.setDuration(100); + // Дата раньше 28 декабря 1895 + film.setReleaseDate(LocalDate.of(1895, 12, 27)); + + ValidationException exception = assertThrows(ValidationException.class, () -> { + controller.create(film); + }); + assertEquals("Дата релиза — не раньше 28 декабря 1895 года", exception.getMessage()); + } + + @Test + void shouldThrowExceptionWhenDurationIsNegative() { + Film film = new Film(); + film.setName("Name"); + film.setDescription("Description"); + film.setDuration(-1); // Отрицательная длительность + film.setReleaseDate(LocalDate.now()); + + ValidationException exception = assertThrows(ValidationException.class, () -> { + controller.create(film); + }); + assertEquals("Продолжительность фильма должна быть положительной", exception.getMessage()); + } +} \ No newline at end of file diff --git a/src/test/UserValidationTest.java b/src/test/UserValidationTest.java new file mode 100644 index 0000000..bf13298 --- /dev/null +++ b/src/test/UserValidationTest.java @@ -0,0 +1,52 @@ +import controllers.UserController; +import exception.ValidationException; +import model.User; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.time.LocalDate; + +import static org.junit.jupiter.api.Assertions.*; + +class UserValidationTest { + + private UserController controller; + + @BeforeEach + void setUp() { + controller = new UserController(); + } + + @Test + void shouldSetLoginAsNameIfNameIsEmpty() { + User user = new User(); + user.setLogin("login"); + user.setEmail("email@test.com"); + user.setBirthday(LocalDate.of(2000, 1, 1)); + user.setName(""); // Пустое имя + + User createdUser = controller.create(user); + + assertEquals("login", createdUser.getName()); + } + + @Test + void shouldThrowExceptionForInvalidEmail() { + User user = new User(); + user.setLogin("login"); + user.setEmail("invalid-email"); // Нет @ + user.setBirthday(LocalDate.now()); + + assertThrows(ValidationException.class, () -> controller.create(user)); + } + + @Test + void shouldThrowExceptionForSpacesInLogin() { + User user = new User(); + user.setLogin("log in"); // Пробел + user.setEmail("email@test.com"); + user.setBirthday(LocalDate.now()); + + assertThrows(ValidationException.class, () -> controller.create(user)); + } +} \ No newline at end of file diff --git a/test/manager/HistoryDataPreservationTest.java b/test/manager/HistoryDataPreservationTest.java deleted file mode 100644 index b041735..0000000 --- a/test/manager/HistoryDataPreservationTest.java +++ /dev/null @@ -1,53 +0,0 @@ -package manager; - -import model.Task; -import model.Status; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.*; - -class HistoryDataPreservationTest { - private HistoryManager historyManager; - - @BeforeEach - void setUp() { - historyManager = new InMemoryHistoryManager(); - } - - @Test - void historyPreservesTaskData() { - // Создаем задачу - Task originalTask = new Task("Original", "Original Description", 1, Status.NEW); - - // Добавляем в историю - historyManager.add(originalTask); - - // Изменяем оригинальную задачу - originalTask.setName("Modified"); - originalTask.setDescription("Modified Description"); - originalTask.setStatus(Status.DONE); - - // Получаем задачу из истории - Task historicalTask = historyManager.getHistory().get(0); - - // Проверяем, что данные в истории сохранились оригинальными - assertEquals("Original", historicalTask.getName(), "История должна сохранить оригинальное имя"); - assertEquals("Original Description", historicalTask.getDescription(), - "История должна сохранить оригинальное описание"); - assertEquals(Status.NEW, historicalTask.getStatus(), "История должна сохранить оригинальный статус"); - assertEquals(1, historicalTask.getId(), "История должна сохранить оригинальный ID"); - } - - @Test - void historyContainsIndependentCopies() { - Task task = new Task("Test", "Description", 1, Status.NEW); - historyManager.add(task); - - // Изменяем оригинальную задачу - task.setName("Changed"); - - // Задача в истории не должна измениться - assertNotEquals(task.getName(), historyManager.getHistory().get(0).getName(), - "Задача в истории не должна зависеть от изменений оригинала"); - } -} \ No newline at end of file diff --git a/test/manager/ManagersTest.java b/test/manager/ManagersTest.java deleted file mode 100644 index c62d2c6..0000000 --- a/test/manager/ManagersTest.java +++ /dev/null @@ -1,31 +0,0 @@ -package manager; - -import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.*; - -class ManagersTest { - - @Test - void getDefaultReturnsInitializedTaskManager() { - TaskManager manager = Managers.getDefault(); - - assertNotNull(manager, "Менеджер не должен быть null"); - assertTrue(manager instanceof InMemoryTaskManager, "Должен возвращаться InMemoryTaskManager"); - - // Проверяем, что менеджер готов к работе - assertDoesNotThrow(() -> manager.getAllTasks()); - assertDoesNotThrow(() -> manager.getAllEpics()); - assertDoesNotThrow(() -> manager.getAllSubtasks()); - } - - @Test - void getDefaultHistoryReturnsInitializedHistoryManager() { - HistoryManager historyManager = Managers.getDefaultHistory(); - - assertNotNull(historyManager, "History manager не должен быть null"); - assertTrue(historyManager instanceof InMemoryHistoryManager, "Должен возвращаться InMemoryHistoryManager"); - - // Проверяем, что history manager готов к работе - assertDoesNotThrow(() -> historyManager.getHistory()); - } -} \ No newline at end of file diff --git a/test/manager/TaskInheritanceTest.java b/test/manager/TaskInheritanceTest.java deleted file mode 100644 index b723370..0000000 --- a/test/manager/TaskInheritanceTest.java +++ /dev/null @@ -1,37 +0,0 @@ -package manager; - -import model.Epic; -import model.Status; -import model.Subtask; -import model.Task; -import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.*; - -class TaskInheritanceTest { - - @Test - void taskAndSubtaskWithSameIdShouldNotBeEqual() { - Task task = new Task("Task", "Description", 1, Status.NEW); - Subtask subtask = new Subtask("Subtask", "Description", 1, Status.NEW, 2); - - assertNotEquals(task, subtask, "Task и Subtask с одинаковым ID не должны быть равны"); - } - - @Test - void subtasksWithSameIdShouldBeEqual() { - Subtask subtask1 = new Subtask("Subtask 1", "Description 1", 1, Status.NEW, 10); - Subtask subtask2 = new Subtask("Subtask 2", "Description 2", 1, Status.DONE, 20); - - assertEquals(subtask1, subtask2, "Subtask с одинаковым ID должны быть равны"); - } - - @Test - void epicsWithSameIdShouldBeEqual() { - Epic epic1 = new Epic("Epic 1", "Description 1"); - epic1.setId(1); - Epic epic2 = new Epic("Epic 2", "Description 2"); - epic2.setId(1); - - assertEquals(epic1, epic2, "Epic с одинаковым ID должны быть равны"); - } -} \ No newline at end of file diff --git a/test/manager/TaskManagerFunctionalityTest.java b/test/manager/TaskManagerFunctionalityTest.java deleted file mode 100644 index 36e024b..0000000 --- a/test/manager/TaskManagerFunctionalityTest.java +++ /dev/null @@ -1,41 +0,0 @@ -package manager; - -import model.Task; -import model.Epic; -import model.Subtask; -import model.Status; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.*; - -class TaskManagerFunctionalityTest { - private TaskManager taskManager; - - @BeforeEach - void setUp() { - taskManager = new InMemoryTaskManager(); - } - - @Test - void canAddAndFindAllTaskTypes() { - // Создаем задачи всех типов - Task task = taskManager.createTask(new Task("Task", "Description", Status.NEW)); - Epic epic = taskManager.createEpic(new Epic("Epic", "Description")); - Subtask subtask = taskManager.createSubtask(new Subtask("Subtask", "Description", Status.NEW, epic.getId())); - - // Проверяем, что все создались - assertNotNull(task, "Задача должна быть создана"); - assertNotNull(epic, "Epic должен быть создан"); - assertNotNull(subtask, "Subtask должен быть создан"); - - // Проверяем поиск по ID - assertNotNull(taskManager.getTaskById(task.getId()), "Должна найтись задача по ID"); - assertNotNull(taskManager.getEpicById(epic.getId()), "Должен найтись epic по ID"); - assertNotNull(taskManager.getSubtaskById(subtask.getId()), "Должен найтись subtask по ID"); - - // Проверяем получение всех задач - assertEquals(1, taskManager.getAllTasks().size(), "Должна быть 1 задача"); - assertEquals(1, taskManager.getAllEpics().size(), "Должен быть 1 epic"); - assertEquals(1, taskManager.getAllSubtasks().size(), "Должен быть 1 subtask"); - } -} \ No newline at end of file diff --git a/test/model/EpicIntegrationTest.java b/test/model/EpicIntegrationTest.java deleted file mode 100644 index 772bb13..0000000 --- a/test/model/EpicIntegrationTest.java +++ /dev/null @@ -1,28 +0,0 @@ -package model; - -import manager.Managers; -import manager.TaskManager; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.*; - -class EpicIntegrationTest { - private TaskManager taskManager; - - @BeforeEach - void setUp() { - taskManager = Managers.getDefault(); - } - - @Test - void epicCannotBeAddedAsItsOwnSubtask() { - Epic epic = taskManager.createEpic(new Epic("Test Epic", "Description")); - - // Пытаемся создать подзадачу с epicId равным ID самого эпика - Subtask invalidSubtask = new Subtask("Invalid", "Description", Status.NEW, epic.getId()); - - // Должен вернуть null, так как epic не может быть своим же эпиком - assertNull(taskManager.createSubtask(invalidSubtask), - "Epic не должен быть добавлен в качестве своей же подзадачи"); - } -} \ No newline at end of file diff --git a/test/model/SubtaskIntegrationTest.java b/test/model/SubtaskIntegrationTest.java deleted file mode 100644 index 084c298..0000000 --- a/test/model/SubtaskIntegrationTest.java +++ /dev/null @@ -1,30 +0,0 @@ -package model; - -import manager.Managers; -import manager.TaskManager; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.*; - -class SubtaskIntegrationTest { - private TaskManager taskManager; - - @BeforeEach - void setUp() { - taskManager = Managers.getDefault(); - } - - @Test - void subtaskCannotBeItsOwnEpic() { - Epic epic = taskManager.createEpic(new Epic("Test Epic", "Description")); - Subtask subtask = taskManager.createSubtask(new Subtask("Subtask", "Description", Status.NEW, epic.getId())); - - // Пытаемся изменить epicId подзадачи на её собственный ID - subtask.setEpicId(subtask.getId()); - taskManager.updateSubtask(subtask); - - // Epic ID не должен измениться на собственный ID подзадачи - assertNotEquals(subtask.getId(), subtask.getEpicId(), - "Subtask не должен быть своим же эпиком"); - } -} \ No newline at end of file diff --git a/test/model/TaskIdConflictTest.java b/test/model/TaskIdConflictTest.java deleted file mode 100644 index 222e673..0000000 --- a/test/model/TaskIdConflictTest.java +++ /dev/null @@ -1,42 +0,0 @@ -package model; - -import model.Task; -import model.Status; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.*; - -class TaskIdConflictTest { - private TaskManager taskManager; - - @BeforeEach - void setUp() { - taskManager = new InMemoryTaskManager(); - } - - @Test - void noConflictBetweenGeneratedAndManualIds() { - // Создаем задачу с автоматически сгенерированным ID - Task autoTask = taskManager.createTask(new Task("Auto", "Description", Status.NEW)); - - // Создаем задачу вручную с таким же ID - Task manualTask = new Task("Manual", "Description", autoTask.getId(), Status.NEW); - - // Пытаемся обновить задачу с существующим ID - taskManager.updateTask(manualTask); - - // Проверяем, что задача обновилась, а не создалась новая - assertEquals(1, taskManager.getAllTasks().size(), "Должна остаться одна задача"); - assertEquals("Manual", taskManager.getTaskById(autoTask.getId()).getName(), - "Задача должна быть обновлена, а не создана новая"); - } - - @Test - void tasksWithDifferentIdsCoexist() { - Task task1 = taskManager.createTask(new Task("Task 1", "Description", Status.NEW)); - Task task2 = taskManager.createTask(new Task("Task 2", "Description", Status.NEW)); - - assertNotEquals(task1.getId(), task2.getId(), "Задачи должны иметь разные ID"); - assertEquals(2, taskManager.getAllTasks().size(), "Обе задачи должны существовать"); - } -} \ No newline at end of file diff --git a/test/model/TaskImmutabilityTest.java b/test/model/TaskImmutabilityTest.java deleted file mode 100644 index ff8b490..0000000 --- a/test/model/TaskImmutabilityTest.java +++ /dev/null @@ -1,40 +0,0 @@ -package model; - -import model.Task; -import model.Status; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.*; - -class TaskImmutabilityTest { - private TaskManager taskManager; - - @BeforeEach - void setUp() { - taskManager = new InMemoryTaskManager(); - } - - @Test - void taskRemainsUnchangedWhenAddedToManager() { - // Создаем оригинальную задачу - Task originalTask = new Task("Original", "Original Description", Status.NEW); - - // Сохраняем оригинальные значения - String originalName = originalTask.getName(); - String originalDescription = originalTask.getDescription(); - Status originalStatus = originalTask.getStatus(); - - // Добавляем в менеджер - Task createdTask = taskManager.createTask(originalTask); - - // Проверяем, что оригинальная задача не изменилась - assertEquals(originalName, originalTask.getName(), "Оригинальное имя не должно измениться"); - assertEquals(originalDescription, originalTask.getDescription(), "Оригинальное описание не должно измениться"); - assertEquals(originalStatus, originalTask.getStatus(), "Оригинальный статус не должен измениться"); - - // Проверяем, что созданная задача имеет те же значения - assertEquals(originalName, createdTask.getName(), "Имя должно сохраниться"); - assertEquals(originalDescription, createdTask.getDescription(), "Описание должно сохраниться"); - assertEquals(originalStatus, createdTask.getStatus(), "Статус должен сохраниться"); - } -} \ No newline at end of file diff --git a/test/model/TaskTest.java b/test/model/TaskTest.java deleted file mode 100644 index 67329c9..0000000 --- a/test/model/TaskTest.java +++ /dev/null @@ -1,26 +0,0 @@ -package model; - -import model.Status; -import model.Task; -import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.*; - -class TaskTest { - - @Test - void tasksWithSameIdShouldBeEqual() { - Task task1 = new Task("Task 1", "Description 1", 1, Status.NEW); - Task task2 = new Task("Task 2", "Description 2", 1, Status.DONE); - - assertEquals(task1, task2, "Задачи с одинаковым ID должны быть равны"); - assertEquals(task1.hashCode(), task2.hashCode(), "HashCode должен совпадать для одинаковых ID"); - } - - @Test - void tasksWithDifferentIdShouldNotBeEqual() { - Task task1 = new Task("Task", "Description", 1, Status.NEW); - Task task2 = new Task("Task", "Description", 2, Status.NEW); - - assertNotEquals(task1, task2, "Задачи с разными ID не должны быть равны"); - } -} \ No newline at end of file