diff --git a/.github/workflows/linter.yaml b/.github/workflows/linter.yaml new file mode 100644 index 0000000..1bed085 --- /dev/null +++ b/.github/workflows/linter.yaml @@ -0,0 +1,24 @@ +name: CI + +on: + push: + branches: [ "dev", "main" ] + pull_request: + branches: [ "dev", "main" ] + + # Allows you to run this workflow manually from the Actions tab + workflow_dispatch: + +jobs: + build: + runs-on: ubuntu-latest + + steps: + # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it + - uses: actions/checkout@v4 + + # Super-linter is a ready-to-run collection of linters and code analyzers, to help validate your source code + - name: Super-Linter + uses: super-linter/super-linter@v7.1.0 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..5ff6309 --- /dev/null +++ b/.gitignore @@ -0,0 +1,38 @@ +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### IntelliJ IDEA ### +.idea/modules.xml +.idea/jarRepositories.xml +.idea/compiler.xml +.idea/libraries/ +*.iws +*.iml +*.ipr + +### Eclipse ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ + +### Mac OS ### +.DS_Store \ No newline at end of file diff --git a/docker-compose.yaml b/docker-compose.yaml new file mode 100644 index 0000000..b587a9f --- /dev/null +++ b/docker-compose.yaml @@ -0,0 +1,9 @@ +services: + server: + container_name: server + build: + context: ./server/ + dockerfile: ./docker/jsp-Dockerfile + restart: on-failure + ports: + - "80:8080" \ No newline at end of file diff --git a/server/.gitignore b/server/.gitignore new file mode 100644 index 0000000..5ff6309 --- /dev/null +++ b/server/.gitignore @@ -0,0 +1,38 @@ +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### IntelliJ IDEA ### +.idea/modules.xml +.idea/jarRepositories.xml +.idea/compiler.xml +.idea/libraries/ +*.iws +*.iml +*.ipr + +### Eclipse ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ + +### Mac OS ### +.DS_Store \ No newline at end of file diff --git a/server/.idea/.gitignore b/server/.idea/.gitignore new file mode 100644 index 0000000..7bc07ec --- /dev/null +++ b/server/.idea/.gitignore @@ -0,0 +1,10 @@ +# Default ignored files +/shelf/ +/workspace.xml +# Editor-based HTTP Client requests +/httpRequests/ +# Environment-dependent path to Maven home directory +/mavenHomeManager.xml +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml diff --git a/server/.idea/encodings.xml b/server/.idea/encodings.xml new file mode 100644 index 0000000..aa00ffa --- /dev/null +++ b/server/.idea/encodings.xml @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/server/.idea/misc.xml b/server/.idea/misc.xml new file mode 100644 index 0000000..82dbec8 --- /dev/null +++ b/server/.idea/misc.xml @@ -0,0 +1,14 @@ + + + + + + + + + + \ No newline at end of file diff --git a/server/.idea/runConfigurations/build_lab2.xml b/server/.idea/runConfigurations/build_lab2.xml new file mode 100644 index 0000000..23fde66 --- /dev/null +++ b/server/.idea/runConfigurations/build_lab2.xml @@ -0,0 +1,33 @@ + + + + + + + + \ No newline at end of file diff --git a/server/.idea/vcs.xml b/server/.idea/vcs.xml new file mode 100644 index 0000000..6c0b863 --- /dev/null +++ b/server/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/server/.idea/webContexts.xml b/server/.idea/webContexts.xml new file mode 100644 index 0000000..f4124c7 --- /dev/null +++ b/server/.idea/webContexts.xml @@ -0,0 +1,10 @@ + + + + + + \ No newline at end of file diff --git a/server/.mvn/wrapper/maven-wrapper.properties b/server/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..ffcab66 --- /dev/null +++ b/server/.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.9/apache-maven-3.9.9-bin.zip diff --git a/server/docker/jsp-Dockerfile b/server/docker/jsp-Dockerfile new file mode 100644 index 0000000..fdea693 --- /dev/null +++ b/server/docker/jsp-Dockerfile @@ -0,0 +1,13 @@ +FROM eclipse-temurin:17-jdk-alpine AS build + +# copy maven configs +COPY pom.xml mvnw ./ +COPY .mvn .mvn + +# copy source code +COPY src src +RUN ./mvnw clean package + +FROM quay.io/wildfly/wildfly:latest-jdk17 +WORKDIR server +COPY --from=build ./target/server-1.0.war /opt/jboss/wildfly/standalone/deployments/ROOT.war \ No newline at end of file diff --git a/server/mvnw b/server/mvnw new file mode 100755 index 0000000..bd8896b --- /dev/null +++ b/server/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/server/mvnw.cmd b/server/mvnw.cmd new file mode 100644 index 0000000..5761d94 --- /dev/null +++ b/server/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/server/pom.xml b/server/pom.xml new file mode 100644 index 0000000..ba86f35 --- /dev/null +++ b/server/pom.xml @@ -0,0 +1,45 @@ + + + 4.0.0 + + org.web2 + server + 1.0 + war + + + 17 + 17 + UTF-8 + + + + + + jakarta.servlet + jakarta.servlet-api + 6.1.0 + provided + + + + + org.projectlombok + lombok + 1.18.42 + + + + + + + + org.apache.maven.plugins + maven-war-plugin + 3.4.0 + + + + \ No newline at end of file diff --git a/server/src/main/java/org/validator/ValidatedRecordFactory.java b/server/src/main/java/org/validator/ValidatedRecordFactory.java new file mode 100644 index 0000000..3d3d75e --- /dev/null +++ b/server/src/main/java/org/validator/ValidatedRecordFactory.java @@ -0,0 +1,22 @@ +package org.validator; + +import org.validator.validation.ValidationController; + +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; + +public class ValidatedRecordFactory { + @SuppressWarnings("unchecked") + public static T create(Class recordClass, Object... args) { + try { + Constructor constructor = (Constructor) recordClass.getDeclaredConstructors()[0]; + T record = constructor.newInstance(args); + + ValidationController.validateObject(record); + + return record; + } catch (InvocationTargetException | InstantiationException | IllegalAccessException e) { + throw new RuntimeException("Record can't be created", e); + } + } +} \ No newline at end of file diff --git a/server/src/main/java/org/validator/annotations/NotNull.java b/server/src/main/java/org/validator/annotations/NotNull.java new file mode 100644 index 0000000..731af81 --- /dev/null +++ b/server/src/main/java/org/validator/annotations/NotNull.java @@ -0,0 +1,12 @@ +package org.validator.annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.FIELD, ElementType.RECORD_COMPONENT, ElementType.ANNOTATION_TYPE}) +public @interface NotNull { + String errorMsg() default "Field required"; +} diff --git a/server/src/main/java/org/validator/annotations/Number.java b/server/src/main/java/org/validator/annotations/Number.java new file mode 100644 index 0000000..e92023f --- /dev/null +++ b/server/src/main/java/org/validator/annotations/Number.java @@ -0,0 +1,19 @@ +package org.validator.annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE}) +@NotNull(errorMsg = "Number field is required") +@Size(min = 1, errorMsg = "Number must not be empty") +@Pattern(pattern = "^-?\\d+(\\.\\d+)?$", errorMsg = "Must be a valid number") +public @interface Number { + String rangeErrorMsg() default "Number must be between %s and %s"; + String stepErrorMsg() default "Number distance from minimum must be divisible by %s"; + double min() default Integer.MIN_VALUE; + double max() default Integer.MAX_VALUE; + double step() default 0; +} diff --git a/server/src/main/java/org/validator/annotations/Pattern.java b/server/src/main/java/org/validator/annotations/Pattern.java new file mode 100644 index 0000000..ca18e9c --- /dev/null +++ b/server/src/main/java/org/validator/annotations/Pattern.java @@ -0,0 +1,14 @@ +package org.validator.annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.FIELD, ElementType.RECORD_COMPONENT, ElementType.ANNOTATION_TYPE}) +@NotNull +public @interface Pattern { + String errorMsg() default "Pattern mismatch"; + String pattern(); +} diff --git a/server/src/main/java/org/validator/annotations/Size.java b/server/src/main/java/org/validator/annotations/Size.java new file mode 100644 index 0000000..e923d5b --- /dev/null +++ b/server/src/main/java/org/validator/annotations/Size.java @@ -0,0 +1,15 @@ +package org.validator.annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.FIELD, ElementType.RECORD_COMPONENT, ElementType.ANNOTATION_TYPE}) +@NotNull +public @interface Size { + String errorMsg() default "String size must be between %d and %d"; + int min() default 0; + long max() default Integer.MAX_VALUE; +} diff --git a/server/src/main/java/org/validator/validation/ValidationController.java b/server/src/main/java/org/validator/validation/ValidationController.java new file mode 100644 index 0000000..ab89146 --- /dev/null +++ b/server/src/main/java/org/validator/validation/ValidationController.java @@ -0,0 +1,56 @@ +package org.validator.validation; + +import org.validator.annotations.NotNull; +import org.validator.annotations.Number; +import org.validator.annotations.Pattern; +import org.validator.annotations.Size; +import org.validator.validation.validators.*; + +import java.lang.annotation.Annotation; +import java.lang.reflect.Field; +import java.util.HashMap; + +public class ValidationController { + + private static final HashMap, Validator> validatorCache = new HashMap<>(); + + static { + validatorCache.put(NotNull.class, new NotNullValidator()); + validatorCache.put(Size.class, new SizeValidator()); + validatorCache.put(Pattern.class, new PatternValidator()); + validatorCache.put(Number.class, new NumberValidator()); + } + + public static void validateObject(T object) { + for (Field field : object.getClass().getDeclaredFields()) { + try { + field.setAccessible(true); + + Object value = field.get(object); + validateField(value, field.getAnnotations()); + } catch (IllegalAccessException e) { + throw new RuntimeException("Failed to validate field: " + field.getName(), e); + } + } + } + + private static void validateField(Object value, T[] annotations) { + for (Annotation annotation : annotations) { + validateAnnotation(annotation, value); + } + } + + @SuppressWarnings("unchecked") + private static void validateAnnotation(Annotation annotation, Object value) { + Class annotationType = annotation.annotationType(); + + Validator validator = (Validator) validatorCache.get(annotationType); + if (validator == null) return; + + for (Annotation metaAnnotation : annotationType.getAnnotations()) validateAnnotation(metaAnnotation, value); + + validator.validate(annotation, value); + } +} + + diff --git a/server/src/main/java/org/validator/validation/exceptions/ValidationException.java b/server/src/main/java/org/validator/validation/exceptions/ValidationException.java new file mode 100644 index 0000000..d889557 --- /dev/null +++ b/server/src/main/java/org/validator/validation/exceptions/ValidationException.java @@ -0,0 +1,7 @@ +package org.validator.validation.exceptions; + +public class ValidationException extends RuntimeException { + public ValidationException(String message) { + super(message); + } +} diff --git a/server/src/main/java/org/validator/validation/validators/NotNullValidator.java b/server/src/main/java/org/validator/validation/validators/NotNullValidator.java new file mode 100644 index 0000000..37381fc --- /dev/null +++ b/server/src/main/java/org/validator/validation/validators/NotNullValidator.java @@ -0,0 +1,13 @@ +package org.validator.validation.validators; + +import org.validator.annotations.NotNull; +import org.validator.validation.exceptions.ValidationException; + +public class NotNullValidator implements Validator { + @Override + public void validate(NotNull annotation, Object value) { + if (value == null) { + throw new ValidationException(annotation.errorMsg()); + } + } +} \ No newline at end of file diff --git a/server/src/main/java/org/validator/validation/validators/NumberValidator.java b/server/src/main/java/org/validator/validation/validators/NumberValidator.java new file mode 100644 index 0000000..4f12131 --- /dev/null +++ b/server/src/main/java/org/validator/validation/validators/NumberValidator.java @@ -0,0 +1,23 @@ +package org.validator.validation.validators; + +import org.validator.annotations.Number; +import org.validator.validation.exceptions.ValidationException; + +public class NumberValidator implements Validator { + @Override + public void validate(Number annotation, Object value) { + if (value instanceof String str) { + double num = Double.parseDouble(str); + if (num < annotation.min() || num > annotation.max()) { + throw new ValidationException( + String.format(annotation.rangeErrorMsg(), annotation.min(), annotation.max()) + ); + } + if (annotation.step() != 0 && (num-annotation.min())%annotation.step() != 0) { + throw new ValidationException( + String.format(annotation.stepErrorMsg(), annotation.step()) + ); + } + } + } +} \ No newline at end of file diff --git a/server/src/main/java/org/validator/validation/validators/PatternValidator.java b/server/src/main/java/org/validator/validation/validators/PatternValidator.java new file mode 100644 index 0000000..450bcf6 --- /dev/null +++ b/server/src/main/java/org/validator/validation/validators/PatternValidator.java @@ -0,0 +1,15 @@ +package org.validator.validation.validators; + +import org.validator.annotations.Pattern; +import org.validator.validation.exceptions.ValidationException; + +public class PatternValidator implements Validator { + @Override + public void validate(Pattern annotation, Object value) { + if (value instanceof String str) { + if (!str.matches(annotation.pattern())) { + throw new ValidationException(annotation.errorMsg()); + } + } + } +} \ No newline at end of file diff --git a/server/src/main/java/org/validator/validation/validators/SizeValidator.java b/server/src/main/java/org/validator/validation/validators/SizeValidator.java new file mode 100644 index 0000000..9e96199 --- /dev/null +++ b/server/src/main/java/org/validator/validation/validators/SizeValidator.java @@ -0,0 +1,21 @@ +package org.validator.validation.validators; + +import org.validator.annotations.Size; +import org.validator.validation.exceptions.ValidationException; + +public class SizeValidator implements Validator { + @Override + public void validate(Size annotation, Object value) { + if (value instanceof String str) { + if (str.length() < annotation.min() || str.length() > annotation.max()) { + throw new ValidationException( + String.format( + annotation.errorMsg(), + annotation.min(), + annotation.max() + ) + ); + } + } + } +} \ No newline at end of file diff --git a/server/src/main/java/org/validator/validation/validators/Validator.java b/server/src/main/java/org/validator/validation/validators/Validator.java new file mode 100644 index 0000000..990eb59 --- /dev/null +++ b/server/src/main/java/org/validator/validation/validators/Validator.java @@ -0,0 +1,7 @@ +package org.validator.validation.validators; +import java.lang.annotation.Annotation; + +@FunctionalInterface +public interface Validator { + void validate(A annotation, Object value); +} \ No newline at end of file diff --git a/server/src/main/java/org/web2/controllers/ControllerServlet.java b/server/src/main/java/org/web2/controllers/ControllerServlet.java new file mode 100644 index 0000000..9d58b24 --- /dev/null +++ b/server/src/main/java/org/web2/controllers/ControllerServlet.java @@ -0,0 +1,35 @@ +package org.web2.controllers; + +import jakarta.servlet.*; +import jakarta.servlet.http.*; +import jakarta.servlet.annotation.*; +import org.web2.controllers.services.utils.logging.SimpleLogger; + +import java.io.IOException; +import java.util.logging.Logger; + +@WebServlet("/lab") +public class ControllerServlet extends HttpServlet { + private final Logger logger = SimpleLogger.create(); + + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + String x = req.getParameter("X"); + String y = req.getParameter("Y"); + String r = req.getParameter("R"); + + logger.info(String.format("Received params (x:%s y:%s r:%s)", x, y, r)); + + if (x != null && y != null && r != null) { + logger.info("Redirecting to check"); + + RequestDispatcher dispatcher = req.getRequestDispatcher("/check"); + dispatcher.forward(req, resp); + } else { + logger.info("Redirecting to root"); + + RequestDispatcher dispatcher = req.getRequestDispatcher("index.jsp"); + dispatcher.forward(req, resp); + } + } +} diff --git a/server/src/main/java/org/web2/controllers/services/AreaCheckServlet.java b/server/src/main/java/org/web2/controllers/services/AreaCheckServlet.java new file mode 100644 index 0000000..ca4f7d3 --- /dev/null +++ b/server/src/main/java/org/web2/controllers/services/AreaCheckServlet.java @@ -0,0 +1,68 @@ +package org.web2.controllers.services; + + +import jakarta.servlet.*; +import jakarta.servlet.http.*; +import jakarta.servlet.annotation.*; + +import org.validator.ValidatedRecordFactory; +import org.validator.validation.exceptions.ValidationException; +import org.web2.controllers.services.DTOs.AreaCheckRequestDTO; +import org.web2.controllers.services.checkers.Checker; +import org.web2.controllers.services.utils.time.Stopwatch; +import org.web2.model.ResultBean; + +import java.io.IOException; +import java.util.Date; +import java.util.ArrayList; + +@WebServlet("/check") +public class AreaCheckServlet extends HttpServlet { + private final Stopwatch timer = new Stopwatch(); + private final Checker checker = new Checker(); + + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + final Stopwatch elapsedTimeTimer = timer.start(); + + try { + AreaCheckRequestDTO requestData = ValidatedRecordFactory.create( + AreaCheckRequestDTO.class, + req.getParameter("X"), + req.getParameter("Y"), + req.getParameter("R") + ); + + boolean hit = checker.test( + Float.parseFloat(requestData.X()), + Float.parseFloat(requestData.Y()), + Integer.parseInt(requestData.R()) + ); + + final ResultBean newResult = new ResultBean( + Float.parseFloat(requestData.X()), + Float.parseFloat(requestData.Y()), + Integer.parseInt(requestData.R()), + hit, + new Date(), + elapsedTimeTimer.stop() + ); + + HttpSession session = req.getSession(); + @SuppressWarnings("unchecked") + ArrayList results = (ArrayList) session.getAttribute("results"); + if (results == null) { + results = new ArrayList<>(); + } + + results.add(newResult); + session.setAttribute("results", results); + session.setAttribute("lastResult", newResult); + + RequestDispatcher dispatcher = req.getRequestDispatcher("result.jsp"); + dispatcher.forward(req, resp); + } catch (ValidationException e) { + resp.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage()); + } + } +} diff --git a/server/src/main/java/org/web2/controllers/services/DTOs/AreaCheckRequestDTO.java b/server/src/main/java/org/web2/controllers/services/DTOs/AreaCheckRequestDTO.java new file mode 100644 index 0000000..6e63fd9 --- /dev/null +++ b/server/src/main/java/org/web2/controllers/services/DTOs/AreaCheckRequestDTO.java @@ -0,0 +1,10 @@ +package org.web2.controllers.services.DTOs; + +import org.validator.annotations.Number; + +public record AreaCheckRequestDTO ( + @Number(min = -5, max = 3) String X, + @Number(min = -2, max = 2, step = 0.5) String Y, + @Number(min = 1, max = 5, step = 1) String R +) {} + diff --git a/server/src/main/java/org/web2/controllers/services/checkers/Checker.java b/server/src/main/java/org/web2/controllers/services/checkers/Checker.java new file mode 100644 index 0000000..6a56146 --- /dev/null +++ b/server/src/main/java/org/web2/controllers/services/checkers/Checker.java @@ -0,0 +1,31 @@ +package org.web2.controllers.services.checkers; + +import org.web2.controllers.services.checkers.utils.PlotQuarters; +import org.web2.controllers.services.checkers.utils.PlotUtils; + +public class Checker implements CheckerFunction{ + public boolean test(final float x, final float y, final int r) { + final PlotQuarters quarter = PlotUtils.getQuarter(x, y); + + if (quarter == PlotQuarters.FIRST_QUADRANT) return firstQuarterTester(x, y, r); + else if (quarter == PlotQuarters.SECOND_QUADRANT) return secondQuarterTester(x, y, r); + else if (quarter == PlotQuarters.THIRD_QUADRANT) return thirdQuarterTester(x, y, r); + return forthQuarterTester(x, y, r); + } + + private boolean firstQuarterTester(final float x, final float y, final float r) { + return y <= (r - x); + } + + private boolean secondQuarterTester(final float x, final float y, final float r) { + return Math.sqrt(x * x + y * y) <= r / 2; + } + + private boolean thirdQuarterTester(final float x, final float y,final float r) { + return false; + } + + private boolean forthQuarterTester(final float x, final float y, final float r) { + return x >= -r / 2 && y <= r; + } +} \ No newline at end of file diff --git a/server/src/main/java/org/web2/controllers/services/checkers/CheckerFunction.java b/server/src/main/java/org/web2/controllers/services/checkers/CheckerFunction.java new file mode 100644 index 0000000..cbacda7 --- /dev/null +++ b/server/src/main/java/org/web2/controllers/services/checkers/CheckerFunction.java @@ -0,0 +1,6 @@ +package org.web2.controllers.services.checkers; + +@FunctionalInterface +public interface CheckerFunction { + boolean test(float x, float y, int r); +} diff --git a/server/src/main/java/org/web2/controllers/services/checkers/utils/PlotQuarters.java b/server/src/main/java/org/web2/controllers/services/checkers/utils/PlotQuarters.java new file mode 100644 index 0000000..14f6dc1 --- /dev/null +++ b/server/src/main/java/org/web2/controllers/services/checkers/utils/PlotQuarters.java @@ -0,0 +1,8 @@ +package org.web2.controllers.services.checkers.utils; + +public enum PlotQuarters { + FIRST_QUADRANT, + SECOND_QUADRANT, + THIRD_QUADRANT, + FOURTH_QUADRANT +} diff --git a/server/src/main/java/org/web2/controllers/services/checkers/utils/PlotUtils.java b/server/src/main/java/org/web2/controllers/services/checkers/utils/PlotUtils.java new file mode 100644 index 0000000..6d8fb2d --- /dev/null +++ b/server/src/main/java/org/web2/controllers/services/checkers/utils/PlotUtils.java @@ -0,0 +1,13 @@ +package org.web2.controllers.services.checkers.utils; + +public class PlotUtils { + public static PlotQuarters getQuarter(final float x, final float y) { + boolean isXGraterOrEqualsZero = x >= 0; + boolean isYGraterOrEqualsZero = y >= 0; + + if (isXGraterOrEqualsZero && isYGraterOrEqualsZero) return PlotQuarters.FIRST_QUADRANT; + else if (isXGraterOrEqualsZero && !isYGraterOrEqualsZero) return PlotQuarters.SECOND_QUADRANT; // читабельность важнее + else if (!isXGraterOrEqualsZero && !isYGraterOrEqualsZero) return PlotQuarters.THIRD_QUADRANT; // читабельность важнее + return PlotQuarters.FOURTH_QUADRANT; + } +} diff --git a/server/src/main/java/org/web2/controllers/services/utils/logging/SimpleLogger.java b/server/src/main/java/org/web2/controllers/services/utils/logging/SimpleLogger.java new file mode 100644 index 0000000..dd50178 --- /dev/null +++ b/server/src/main/java/org/web2/controllers/services/utils/logging/SimpleLogger.java @@ -0,0 +1,23 @@ +package org.web2.controllers.services.utils.logging; + +import java.io.IOException; +import java.util.logging.*; + +public class SimpleLogger { + private static final Logger logger = Logger.getLogger(SimpleLogger.class.getName()); + private static final Formatter SimpleLoggerFormatter = new SimpleLoggerFormatter(); + + public static Logger create(){ + try { + Handler fileHandler = new FileHandler("/tmp/server.log"); + + fileHandler.setFormatter(SimpleLoggerFormatter); + logger.addHandler(fileHandler); + logger.setLevel(Level.INFO); + + return logger; + } catch (SecurityException | IOException e) { + throw new RuntimeException("Can't init logger"); + } + } +} \ No newline at end of file diff --git a/server/src/main/java/org/web2/controllers/services/utils/logging/SimpleLoggerFormatter.java b/server/src/main/java/org/web2/controllers/services/utils/logging/SimpleLoggerFormatter.java new file mode 100644 index 0000000..c0630fb --- /dev/null +++ b/server/src/main/java/org/web2/controllers/services/utils/logging/SimpleLoggerFormatter.java @@ -0,0 +1,22 @@ +package org.web2.controllers.services.utils.logging; + +import java.util.Date; +import java.util.logging.Formatter; +import java.util.logging.LogRecord; + +public class SimpleLoggerFormatter extends Formatter { + private final String logstringFormat = "%s - %s %s \t %s \n"; + + @Override + public String format(LogRecord record) { + return String.format( + logstringFormat, + + new Date(record.getMillis()), + record.getSourceClassName(), + record.getSourceMethodName(), + record.getMessage() + ); + } + +} \ No newline at end of file diff --git a/server/src/main/java/org/web2/controllers/services/utils/time/Stopwatch.java b/server/src/main/java/org/web2/controllers/services/utils/time/Stopwatch.java new file mode 100644 index 0000000..dc3fa15 --- /dev/null +++ b/server/src/main/java/org/web2/controllers/services/utils/time/Stopwatch.java @@ -0,0 +1,13 @@ +package org.web2.controllers.services.utils.time; + +public class Stopwatch { + private long startTime; + + public Stopwatch start() { + this.startTime = System.nanoTime(); + return this; + } + public long stop() { + return System.nanoTime() - this.startTime; + } +} diff --git a/server/src/main/java/org/web2/jstlUtils/JstlFunctions.java b/server/src/main/java/org/web2/jstlUtils/JstlFunctions.java new file mode 100644 index 0000000..3b81070 --- /dev/null +++ b/server/src/main/java/org/web2/jstlUtils/JstlFunctions.java @@ -0,0 +1,16 @@ +package org.web2.jstlUtils; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class JstlFunctions { + public static List reverse(List list) { + if (list == null) { + return null; + } + List reversed = new ArrayList<>(list); + Collections.reverse(reversed); + return reversed; + } +} \ No newline at end of file diff --git a/server/src/main/java/org/web2/model/ResultBean.java b/server/src/main/java/org/web2/model/ResultBean.java new file mode 100644 index 0000000..ca2e209 --- /dev/null +++ b/server/src/main/java/org/web2/model/ResultBean.java @@ -0,0 +1,20 @@ +package org.web2.model; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; + +import java.util.Date; + +@Getter +@NoArgsConstructor +@AllArgsConstructor +public class ResultBean { + private double x; + private double y; + private double r; + + private boolean hit; + private Date time; + private long elapsedTimeNs; +} diff --git a/server/src/main/webapp/WEB-INF/tld/utils.tld b/server/src/main/webapp/WEB-INF/tld/utils.tld new file mode 100644 index 0000000..7b83590 --- /dev/null +++ b/server/src/main/webapp/WEB-INF/tld/utils.tld @@ -0,0 +1,17 @@ + + + + 1.0 + utils + utils + + + reverse + org.web2.jstlUtils.JstlFunctions + + java.util.List reverse(java.util.List) + + + \ No newline at end of file diff --git a/server/src/main/webapp/WEB-INF/web.xml b/server/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000..404d76a --- /dev/null +++ b/server/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,29 @@ + + + + + ControllerServlet + org.web2.controllers.ControllerServlet + + + ControllerServlet + /lab + + + + AreaCheckServlet + org.web2.controllers.services.AreaCheckServlet + + + AreaCheckServlet + /check + + + + index.jsp + + \ No newline at end of file diff --git a/server/src/main/webapp/assets/css/error.css b/server/src/main/webapp/assets/css/error.css new file mode 100644 index 0000000..d0c668f --- /dev/null +++ b/server/src/main/webapp/assets/css/error.css @@ -0,0 +1,41 @@ +.error-message { + position: fixed; + bottom: 20px; + right: 20px; + + background-color: var(--error-bg); + color: var(--text-primary); + + padding: 15px 20px; + + border-radius: 8px; + box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3); + + z-index: 1000; + + max-width: 350px; + + animation: errorSlideIn 0.3s ease-out, errorFadeOut 0.5s ease-in 4.5s forwards; +} + +/* Анимации */ +@keyframes errorSlideIn { + from { + transform: translateX(100%); + opacity: 0; + } + to { + transform: translateX(0); + opacity: 1; + } +} + +@keyframes errorFadeOut { + from { + opacity: 1; + } + to { + opacity: 0; + display: none; + } +} \ No newline at end of file diff --git a/server/src/main/webapp/assets/css/history.css b/server/src/main/webapp/assets/css/history.css new file mode 100644 index 0000000..2e75782 --- /dev/null +++ b/server/src/main/webapp/assets/css/history.css @@ -0,0 +1,93 @@ +.history-section { + margin-top: 30px; +} + + .history-title { + text-align: center; + + color: var(--text-primary); + font-size: 1.4rem; + + margin-bottom: 15px; + } + + .history-table { + width: 100%; + + display: block; + + background: var(--bg-tertiary); + + border-collapse: collapse; + border-radius: 8px; + overflow: hidden; + + overflow-x: auto; + + box-shadow: var(--shadow); + } + + .history-table th, .history-table td { + width: 100%; + padding: 15px; + text-align: left; + border-bottom: 1px solid var(--border-color); + } + + .history-table th { + background: oklch(30% 0.06 260); + + color: var(--text-secondary); + + font-weight: 600; + position: sticky; + top: 0; + } + + .history-table tr:last-child td { + border-bottom: none; + } + + .history-table tr:hover { + background: oklch(40% 0.06 260); + } + + .history-table td { + color: var(--text-secondary); + } + + .empty-history { + text-align: center; + color: var(--text-secondary); + font-style: italic; + + padding: 20px 10px 5px 10px; + } + +.action-buttons { + display: grid; + justify-content: center; + + margin-top: 20px; +} + + .clear-btn { + padding: 12px 24px; + + background: var(--btn-primary); + + color: var(--text-primary); + + border: none; + border-radius: 6px; + + cursor: pointer; + + transition: all 0.3s ease; + } + + .clear-btn:hover { + background: var(--btn-secondary); + + transform: translateY(var(--btn-active-translateY)); + } \ No newline at end of file diff --git a/server/src/main/webapp/assets/css/main.css b/server/src/main/webapp/assets/css/main.css new file mode 100644 index 0000000..ef874d0 --- /dev/null +++ b/server/src/main/webapp/assets/css/main.css @@ -0,0 +1,284 @@ +* { + margin: 0; + padding: 0; + box-sizing: border-box; +} + +body { + /* Дефолтные настройки стиля текста */ + font-family: 'fantasy;', sans-serif; + color: var(--text-secondary); + line-height: 1.6; + + background: var(--bg-primary); + + min-height: 100vh; + padding: 20px; + + /* Расположение элементов */ + display: grid; + justify-items: center; + + user-select: none; +} + + .container { + max-width: 800px; + width: 100%; + padding: 30px; + + background: var(--bg-secondary); + + border-radius: 12px; + + box-shadow: var(--shadow); + } + + .header { + text-align: center; + + padding-bottom: 10px; + margin-bottom: 10px; + + border-bottom: 2px solid var(--border-color); + } + + .header h1 { + color: var(--text-primary); + font-size: 2.2rem; + font-weight: 300; + } + + .header h2 { + color: var(--text-secondary); + font-size: 1.2rem; + font-weight: 500; + } + + .graph-container { + display: grid; + justify-items: center; + } + + .form-container { + padding: 10px; + } + + #form-svg-placeholder { + color: var(--accent-primary); + font-size: 1.4rem; + text-align: center; + margin-bottom: 10px; + } + + .form-grid { + display: grid; + grid-template-columns: 1fr 3fr; + + background: var(--bg-tertiary); + + border-radius: 8px; + overflow: hidden; + } + + .form-row { + display: contents; + } + + .row-label { + padding: 20px; + background: oklch(30% 0.06 260); + + display: flex; + align-items: center; + + font-weight: 600; + color: var(--accent-primary); + border-bottom: 1px solid var(--border-color); + } + .row-label p { + color: var(--text-secondary); + } + + .row-input { + padding: 20px; + background: var(--bg-tertiary); + + display: inline-flex; + gap: 3%; + + border-bottom: 1px solid var(--border-color); + } + .input-group { + display: flex; + flex-direction: column; + + align-items: center; + + gap: 2px; + } + + input, label { + cursor: pointer; + } + input[type="radio"] { + width: 18px; + height: 18px; + + accent-color: var(--accent-primary); + } + + input[type="number"] { + width: 100%; + max-width: 200px; + padding: 12px; + + border: 2px solid var(--border-color); + border-radius: 6px; + + background: var(--bg-secondary); + + color: var(--text-primary); + font-size: 16px; + + transition: border-color 0.3s ease; + } + + input[type="number"]:focus { + outline: none; + border-color: var(--accent-primary); + } + + label { + color: var(--text-secondary); + transition: color 0.3s ease; + } + + label:hover { + color: var(--text-primary); + } + + input:checked ~ label { + color: var(--text-primary); + } + input:hover ~ label { + color: var(--text-primary); + } + + .submit-container { + display: grid; + grid-template-columns: 1fr; + + margin-top: 10px; + } + + .submit-btn { + padding: 16px; + + background: var(--accent-primary); + + font-size: 1rem; + font-weight: 600; + color: var(--text-primary); + + border: none; + border-radius: 8px; + + cursor: pointer; + + transition: all 0.3s ease; + } + + .submit-btn:hover { + background: var(--accent-secondary); + transform: translateY(var(--btn-active-translateY)); + box-shadow: var(--shadow); + } + + .container { + animation: containerFadeIn 0.6s ease-out; + } + + /* Адаптивность */ + @media (max-width: 768px) { + .form-grid { + grid-template-columns: 1fr; + } + + .form-label { + padding: 15px; + border-bottom: none; + background: oklch(25% 0.06 260); + } + + .form-input { + padding: 15px 15px 20px 15px; + border-bottom: 1px solid var(--border-color); + } + + .form-row:last-child .form-input { + border-bottom: none; + } + + input[type="number"] { + max-width: 100%; + } + } + + @media (max-width: 480px) { + .container { + padding: 20px; + } + + .header h1 { + font-size: 1.8rem; + } + + .input-group { + flex-direction: column; + align-items: flex-start; + gap: 8px; + } + } + + +/* Адаптивность */ +@media (max-width: 968px) { + .container { + min-width: 95%; + } + + .history-table { + font-size: 14px; + } + + .history-table th, + .history-table td { + padding: 10px; + } +} + +@media (max-width: 768px) { + .form-grid { + grid-template-columns: 1fr; + } +} + +@media (max-width: 550px) { + .header h1 { + font-size: 1.8rem; + } +} + +/* Анимации */ +@keyframes containerFadeIn { + from { + opacity: 0; + transform: translateY(20px); + } + to { + opacity: 1; + transform: translateY(0); + } +} + diff --git a/server/src/main/webapp/assets/css/plot.css b/server/src/main/webapp/assets/css/plot.css new file mode 100644 index 0000000..9ab92a0 --- /dev/null +++ b/server/src/main/webapp/assets/css/plot.css @@ -0,0 +1,17 @@ +.svg-cord-line { + stroke: var(--svg-axis-primary); +} +.svg-cord-arrow { + fill: var(--svg-axis-primary); +} +.svg-caption { + fill: var(--text-secondary); + font-size: 12px; +} +.svg-fill-area { + fill: var(--svg-fill-area); + fill-opacity: 0.7; +} +.point-on-plot { + fill: var(--accent-primary); +} \ No newline at end of file diff --git a/server/src/main/webapp/assets/css/themes/default.css b/server/src/main/webapp/assets/css/themes/default.css new file mode 100644 index 0000000..329a993 --- /dev/null +++ b/server/src/main/webapp/assets/css/themes/default.css @@ -0,0 +1,28 @@ +:root { + /* Цветовая палитра в OKLCH */ + --bg-primary: oklch(15% 0.06 260); + --bg-secondary: oklch(25% 0.06 260); + --bg-tertiary: oklch(35% 0.06 260); + + --text-primary: oklch(95% 0.02 260); + --text-secondary: oklch(75% 0.02 260); + + --accent-primary: oklch(65% 0.22 260); + --accent-secondary: oklch(55% 0.18 260); + + --border-color: oklch(30% 0.05 260); + --shadow: 0 4px 12px oklch(0% 0 0 / 0.3); + + --btn-primary: oklch(55% 0.18 50); + --btn-secondary: oklch(50% 0.18 50); + + --svg-axis-primary: oklch(75% 0.04 260); + --svg-fill-area: oklch(52% 0.07 200); + + --error-bg: oklch(55% 0.15 19); + + /* Всякое разное */ + --btn-active-translateY: -2px; + + font-size: 16px; +} \ No newline at end of file diff --git a/server/src/main/webapp/assets/img/logo.ico b/server/src/main/webapp/assets/img/logo.ico new file mode 100644 index 0000000..acc119e Binary files /dev/null and b/server/src/main/webapp/assets/img/logo.ico differ diff --git a/server/src/main/webapp/index.jsp b/server/src/main/webapp/index.jsp new file mode 100644 index 0000000..08cb4ea --- /dev/null +++ b/server/src/main/webapp/index.jsp @@ -0,0 +1,273 @@ +<%@ page contentType="text/html;charset=UTF-8" %> + +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> +<%@ taglib prefix="u" uri="utils" %> +<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> + + + + + + + + Web lab2 + + + + + + + + + + + + +
+ + + + +
+

Решетников Сергей Евгеньевич

+

Группа: P3208

+

Вариант: 583167

+
+ +
+ + + + + + + + + + + + + + + + + + + + + + R + R/2 + -R/2 + -R + + X + + + R + R/2 + -R/2 + -R + + Y + + + + + + + + + + + + + + + + + + + + + + + +
+ + +
+
+
+ +
+
+

Выберите X:

+
+
+ +
+
+ + +
+
+

Выберете Y:

+
+
+ + +
+ + +
+
+
+
+ + +
+
+

Выберете R:

+
+
+ +
+ + +
+
+
+
+
+
+ +
+
+
+ + +
+

История введенных данных

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Дата и времяЗатраченное времяXYRРезультат
${ res.elapsedTimeNs } ns${ res.isHit() ? "Hit" : "Miss" }
+ История пуста. Заполните форму, чтобы добавить данные. +
+
+ +
+ +
+
+
+ + + + \ No newline at end of file diff --git a/server/src/main/webapp/js/error.js b/server/src/main/webapp/js/error.js new file mode 100644 index 0000000..d7384b2 --- /dev/null +++ b/server/src/main/webapp/js/error.js @@ -0,0 +1,31 @@ +class ErrorFactory { + #errorBlockClassName + + constructor(errorBlockClassName){ + this.#errorBlockClassName = errorBlockClassName; + } + + #clearErrors(){ + let existingErrors = document.querySelectorAll(this.#errorBlockClassName); + existingErrors.forEach(error => error.remove()); + } + + showError(message, showTimeMs = 5000){ + this.#clearErrors(); + + // Слздаём элемент + const errorDiv = document.createElement('div'); + errorDiv.className = this.#errorBlockClassName; + errorDiv.textContent = message; + + // Вставка + document.body.appendChild(errorDiv); + + // Убираем по прошествии времени + setTimeout(() => { + if (errorDiv.parentNode) { + errorDiv.parentNode.removeChild(errorDiv); + } + }, showTimeMs); + } +} \ No newline at end of file diff --git a/server/src/main/webapp/js/form.js b/server/src/main/webapp/js/form.js new file mode 100644 index 0000000..c4bb19e --- /dev/null +++ b/server/src/main/webapp/js/form.js @@ -0,0 +1,19 @@ +class Form { + #formId + + constructor(formId){ + this.#formId = formId; + } + + send(X,Y,R){ + const form = document.getElementById(this.#formId); + + // X + form["X"].value = X.toFixed(2); + + // Y + document.querySelectorAll(`input[name="Y"][value="${Y}"]`)[0].checked = true; + + form.submit(); + } +} \ No newline at end of file diff --git a/server/src/main/webapp/js/plot.js b/server/src/main/webapp/js/plot.js new file mode 100644 index 0000000..ec37a2a --- /dev/null +++ b/server/src/main/webapp/js/plot.js @@ -0,0 +1,70 @@ +const convertCheckerCordsToSvgCords = ( + X, Y, R, + paddingX = 20, + paddingY = 20, + XAxisSize = 160, + YAxisSize = 160 +) => { + return [paddingX + (1 + X/R)*XAxisSize/2, paddingY + (1 - Y/R)*YAxisSize/2]; +} + +const convertSvgCordsToCheckerCords = ( + absX, absY, + centerX, centerY, + paddingX, paddingY, + scale, + R +) => { + return [ + (((absX - paddingX) - centerX) / scale)*R, + ((centerY - (absY - paddingY)) / scale)*R, + R + ]; +}; + +const findNearest = (target, elemsArray) => { + let closest = null; + let minDiff = Infinity; + + elemsArray.forEach(elem => { + const value = parseFloat(elem.value); + const diff = Math.abs(target - value); + if (diff < minDiff) { + minDiff = diff; + closest = elem; + } + }); + + return closest; +} + +// Кликоуловтель 2.1 +const handlePlotClick = (event) => { + return new Promise((resolve, reject) => { + const R = document.getElementById("graph-test-form")["R"].value; + + if (!R) reject("Сначала выберите радиус R"); + + const plot = document.getElementById("graph-svg"); + const rect = plot.getBoundingClientRect(); + + const [X,Y,] = convertSvgCordsToCheckerCords( + event.clientX, event.clientY, + rect.width/2, rect.height/2, + rect.left, rect.top, + 80, + R + ) + + resolve( + [ + X, + findNearest( + Y, + document.querySelectorAll('input[name="Y"]') + ).value, + R + ] + ) + }) +}; \ No newline at end of file diff --git a/server/src/main/webapp/result.jsp b/server/src/main/webapp/result.jsp new file mode 100644 index 0000000..ece89e5 --- /dev/null +++ b/server/src/main/webapp/result.jsp @@ -0,0 +1,71 @@ +<%@ page import="org.web2.model.ResultBean" %> +<%@ page contentType="text/html;charset=UTF-8" %> + +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> +<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> + + + + + + + + Web lab2 + + + + + + + + + + + + + +
+ +