commit 965fac1acb821d9038d229181f06a1568ff706cb Author: erius Date: Sat Feb 18 14:46:12 2023 +0300 first commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b63da45 --- /dev/null +++ b/.gitignore @@ -0,0 +1,42 @@ +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ + +### IntelliJ IDEA ### +.idea/modules.xml +.idea/jarRepositories.xml +.idea/compiler.xml +.idea/libraries/ +*.iws +*.iml +*.ipr +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +### Eclipse ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ + +### Mac OS ### +.DS_Store \ No newline at end of file diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..13566b8 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,8 @@ +# Default ignored files +/shelf/ +/workspace.xml +# Editor-based HTTP Client requests +/httpRequests/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml diff --git a/.idea/gradle.xml b/.idea/gradle.xml new file mode 100644 index 0000000..611e7c8 --- /dev/null +++ b/.idea/gradle.xml @@ -0,0 +1,17 @@ + + + + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..3baff1b --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/.idea/uiDesigner.xml b/.idea/uiDesigner.xml new file mode 100644 index 0000000..2b63946 --- /dev/null +++ b/.idea/uiDesigner.xml @@ -0,0 +1,124 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/webContexts.xml b/.idea/webContexts.xml new file mode 100644 index 0000000..f4124c7 --- /dev/null +++ b/.idea/webContexts.xml @@ -0,0 +1,10 @@ + + + + + + \ No newline at end of file diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..dddf514 --- /dev/null +++ b/build.gradle @@ -0,0 +1,36 @@ +plugins { + id 'java' + id 'war' +} + +group 'ru.erius' +version '1.0' + +repositories { + mavenCentral() +} + +ext { + junitVersion = '5.8.2' +} + +sourceCompatibility = '1.8' +targetCompatibility = '1.8' + +tasks.withType(JavaCompile) { + options.encoding = 'UTF-8' +} + +dependencies { + compileOnly('javax.mvc:javax.mvc-api:1.0.0') + compileOnly('javax.servlet:javax.servlet-api:4.0.1') + compileOnly('javax.servlet.jsp:jsp-api:2.0') + compileOnly('javax.servlet:jstl:1.2') + + testImplementation("org.junit.jupiter:junit-jupiter-api:${junitVersion}") + testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:${junitVersion}") +} + +test { + useJUnitPlatform() +} \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..7454180 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..aa991fc --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-7.4.2-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..1b6c787 --- /dev/null +++ b/gradlew @@ -0,0 +1,234 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${0##*/} + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..107acd3 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,89 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..f07f569 --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = "web-lab2" \ No newline at end of file diff --git a/src/main/java/ru/erius/weblab2/controller/AreaCheckServlet.java b/src/main/java/ru/erius/weblab2/controller/AreaCheckServlet.java new file mode 100644 index 0000000..e0eb219 --- /dev/null +++ b/src/main/java/ru/erius/weblab2/controller/AreaCheckServlet.java @@ -0,0 +1,79 @@ +package ru.erius.weblab2.controller; + +import ru.erius.weblab2.model.HitInfo; +import ru.erius.weblab2.model.HitInfoTable; + +import javax.servlet.RequestDispatcher; +import javax.servlet.ServletException; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.time.Clock; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.Date; +import java.util.Arrays; +import java.util.Optional; + +@WebServlet(name = "AreaCheckerServlet", value = "/check") +public class AreaCheckServlet extends HttpServlet { + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + long executionTime = System.nanoTime(); + int timezoneOffset; + try { + Optional timezoneOffsetCookie = readCookie(req, "timezoneOffset"); + timezoneOffset = timezoneOffsetCookie.map(Integer::parseInt).orElse(0); + } catch (NumberFormatException e) { + timezoneOffset = 0; + } + + float x, y, r; + try { + x = Float.parseFloat(req.getParameter("xValue")); + y = Float.parseFloat(req.getParameter("yValue")); + r = Float.parseFloat(req.getParameter("rValue")); + } catch (NumberFormatException e) { + resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "X, Y and R must be numeric"); + RequestDispatcher rootDispatcher = req.getRequestDispatcher("/"); + rootDispatcher.forward(req, resp); + return; + } + + boolean hit = checkHit(x, y, r); + Date hitTime = Date.from(Instant.now().minus(timezoneOffset, ChronoUnit.MINUTES)); + + HitInfo hitInfo = new HitInfo(); + hitInfo.setX(x); hitInfo.setY(y); hitInfo.setR(r); + hitInfo.setHit(hit); + hitInfo.setHitDateTime(hitTime); + + if (req.getSession().getAttribute("hitInfosTable") == null) + req.getSession().setAttribute("hitInfosTable", new HitInfoTable()); + HitInfoTable hitInfosTable = (HitInfoTable) req.getSession().getAttribute("hitInfosTable"); + + executionTime = System.nanoTime() - executionTime; + hitInfo.setExecutionTime(executionTime); + hitInfosTable.getHitInfos().add(hitInfo); + + resp.setStatus(HttpServletResponse.SC_OK); + RequestDispatcher rootDispatcher = req.getRequestDispatcher("/"); + rootDispatcher.forward(req, resp); + } + + private boolean checkHit(float x, float y, float r) { + return x <= 0 && y <= 0 && y >= -x - r / 2 || + x <= 0 && y >= 0 && x >= -r / 2 && y <= r || + x >= 0 && y >= 0 && x * x + y * y <= r * r / 4; + } + + private Optional readCookie(HttpServletRequest req, String key) { + return Arrays.stream(req.getCookies()) + .filter(c -> key.equals(c.getName())) + .map(Cookie::getValue) + .findAny(); + } +} diff --git a/src/main/java/ru/erius/weblab2/controller/ControllerServlet.java b/src/main/java/ru/erius/weblab2/controller/ControllerServlet.java new file mode 100644 index 0000000..11f6346 --- /dev/null +++ b/src/main/java/ru/erius/weblab2/controller/ControllerServlet.java @@ -0,0 +1,35 @@ +package ru.erius.weblab2.controller; + +import ru.erius.weblab2.model.HitInfoTable; + +import javax.servlet.RequestDispatcher; +import javax.servlet.ServletException; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +@WebServlet(name = "ControllerServlet", value = "/control") +public class ControllerServlet extends HttpServlet { + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + if (req.getParameter("xValue") != null && req.getParameter("yValue") != null && req.getParameter("rValue") != null) { + RequestDispatcher checkDispatcher = req.getRequestDispatcher("/check"); + checkDispatcher.forward(req, resp); + return; + } + RequestDispatcher rootDispatcher = req.getRequestDispatcher("/"); + rootDispatcher.forward(req, resp); + } + + @Override + protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + if (req.getParameter("clear") != null) { + HitInfoTable hitInfosTable = (HitInfoTable) req.getSession().getAttribute("hitInfosTable"); + hitInfosTable.getHitInfos().clear(); + } + RequestDispatcher rootDispatcher = req.getRequestDispatcher("/"); + rootDispatcher.forward(req, resp); + } +} diff --git a/src/main/java/ru/erius/weblab2/model/HitInfo.java b/src/main/java/ru/erius/weblab2/model/HitInfo.java new file mode 100644 index 0000000..10c683d --- /dev/null +++ b/src/main/java/ru/erius/weblab2/model/HitInfo.java @@ -0,0 +1,65 @@ +package ru.erius.weblab2.model; + +import java.io.Serializable; +import java.util.Date; + +public class HitInfo implements Serializable { + private float x, y, r, executionTime; + private boolean hit; + private Date hitDateTime; + + public HitInfo() { + x = 0; y = 0; r = 0; + executionTime = 0; + hit = false; + hitDateTime = new Date(); + } + + public float getX() { + return x; + } + + public void setX(float x) { + this.x = x; + } + + public float getY() { + return y; + } + + public void setY(float y) { + this.y = y; + } + + public float getR() { + return r; + } + + public void setR(float r) { + this.r = r; + } + + public float getExecutionTime() { + return executionTime; + } + + public void setExecutionTime(float executionTime) { + this.executionTime = executionTime; + } + + public boolean isHit() { + return hit; + } + + public void setHit(boolean hit) { + this.hit = hit; + } + + public Date getHitDateTime() { + return hitDateTime; + } + + public void setHitDateTime(Date hitDateTime) { + this.hitDateTime = hitDateTime; + } +} diff --git a/src/main/java/ru/erius/weblab2/model/HitInfoTable.java b/src/main/java/ru/erius/weblab2/model/HitInfoTable.java new file mode 100644 index 0000000..7de9519 --- /dev/null +++ b/src/main/java/ru/erius/weblab2/model/HitInfoTable.java @@ -0,0 +1,21 @@ +package ru.erius.weblab2.model; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +public class HitInfoTable implements Serializable { + private List hitInfos; + + public HitInfoTable() { + hitInfos = new ArrayList<>(); + } + + public List getHitInfos() { + return hitInfos; + } + + public void setHitInfos(List hitInfos) { + this.hitInfos = hitInfos; + } +} diff --git a/src/main/java/ru/erius/weblab2/util/ControlsGenerator.java b/src/main/java/ru/erius/weblab2/util/ControlsGenerator.java new file mode 100644 index 0000000..313abfd --- /dev/null +++ b/src/main/java/ru/erius/weblab2/util/ControlsGenerator.java @@ -0,0 +1,48 @@ +package ru.erius.weblab2.util; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.jsp.JspWriter; +import java.io.IOException; + +public final class ControlsGenerator { + public static void generateRadio(HttpServletRequest request, JspWriter out) throws IOException { + String radioHtml = "\n" + + ""; + float checkedRadioValue; + try { + String prevXValue = request.getParameter("xValue"); + checkedRadioValue = prevXValue == null ? 0 : Float.parseFloat(prevXValue); + checkedRadioValue = Math.round(checkedRadioValue * 2) / 2f; + checkedRadioValue = checkedRadioValue > 2 ? 2 : checkedRadioValue < -2 ? -2 : checkedRadioValue; + } catch (NumberFormatException e) { + checkedRadioValue = 0; + } + for (int i = 0; i < 9; i++) { + float radioValue = i / 2f - 2; + String checked = radioValue == checkedRadioValue ? "checked" : ""; + String ithRadioHtml = String.format(radioHtml, i, radioValue, checked); + out.print(ithRadioHtml.replace(',', '.')); + } + } + + public static void generateOptions(HttpServletRequest request, JspWriter out) throws IOException { + String optionHtml = ""; + int selectedOptionId; + try { + String prevRValue = request.getParameter("rValue"); + selectedOptionId = prevRValue == null ? 0 : Integer.parseInt(prevRValue); + } catch (NumberFormatException e) { + selectedOptionId = 3; + } + for (int i = 1; i < 6; i++) { + String selected = i == selectedOptionId ? "selected" : ""; + String ithOptionHtml = String.format(optionHtml, i, selected); + out.print(ithOptionHtml); + } + } + + public static String parameterOrEmpty(HttpServletRequest request, String name) { + String parameter = request.getParameter(name); + return parameter == null ? "" : parameter; + } +} diff --git a/src/main/webapp/WEB-INF/web.xml b/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000..d80081d --- /dev/null +++ b/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,6 @@ + + + \ No newline at end of file diff --git a/src/main/webapp/css/style.css b/src/main/webapp/css/style.css new file mode 100644 index 0000000..c7293c3 --- /dev/null +++ b/src/main/webapp/css/style.css @@ -0,0 +1,83 @@ +html, body { + height: 100%; + width: 100%; + left: 0; + right: 0; + margin: 0; +} + +div { + border: 1px solid black; + border-right: none; + border-left: none; + font-size: 20px; +} + +canvas { + border: 1px solid black; + margin-top: 50%; +} + +.inputForm { + margin-top: 35%; +} + +.inputForm label { + margin-right: 5px; +} + +.header { + background-color: #ccc; + font-size: 32px; + font-family: cursive; + text-align: center; + width: 100%; +} + +.container { + display: flex; + width: 100%; + height: 75%; +} + +.container div { + float: left; + padding: 10px; +} + +.left { + background-color: #ddd; + text-align: center; + font-weight: bold; + font-size: 32px; + width: 20%; +} + +.main { + background-color: #eee; + overflow-y: scroll; + width: 50%; + border-left: 1px solid black; + border-right: 1px solid black; +} + +.right { + background-color: #bbb; + width: 30%; +} + +.main table { + width: 100%; +} + +.main table, th, td { + border: 1px solid black; + border-collapse: collapse; + padding: 5px; + text-align: center; +} + +.footer { + background-color: #ccc; + width: 100%; +} diff --git a/src/main/webapp/hits.jsp b/src/main/webapp/hits.jsp new file mode 100644 index 0000000..23a3baf --- /dev/null +++ b/src/main/webapp/hits.jsp @@ -0,0 +1,37 @@ +<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %> +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> +<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> + + + + + + Hits + + + + + + + + + + + + + + + + + + + + + + + + + +
XYRПопаданиеВремя вызоваВремя выполнения
${hitInfo.hit ? "Да" : "Нет"}
+ + diff --git a/src/main/webapp/img/graph.png b/src/main/webapp/img/graph.png new file mode 100644 index 0000000..c3afc7c Binary files /dev/null and b/src/main/webapp/img/graph.png differ diff --git a/src/main/webapp/index.jsp b/src/main/webapp/index.jsp new file mode 100644 index 0000000..a27b9d6 --- /dev/null +++ b/src/main/webapp/index.jsp @@ -0,0 +1,54 @@ +<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %> +<%@ page import="ru.erius.weblab2.util.ControlsGenerator" %> + + + + + + лаба 2 + + +
+ Капралов Егор Михайлович
+ P32101
+ Вариант - 1211 +
+
+
+ +
+ +
+
+ +
+
+
+ Выберите X:
+ <% ControlsGenerator.generateRadio(request, out); %> +

+ Введите Y:
+ "/> +

+ Выберите R:
+ +

+ +

+
+ + +
+
+
+ + + + + diff --git a/src/main/webapp/js/client.js b/src/main/webapp/js/client.js new file mode 100644 index 0000000..f7cd3bc --- /dev/null +++ b/src/main/webapp/js/client.js @@ -0,0 +1,60 @@ +const yInput = document.getElementById('yInput'); +const yLabel = document.getElementById('yLabel'); +const rInput = document.getElementById('rInput'); +const inputForm = document.getElementById('inputData'); +const yMin = -5, yMax = 5; + +if (yInput.value != null) validateNumberField(yInput, yLabel, yMin, yMax) +addValidationEventListeners(yInput, yLabel, yMin, yMax); +setTimezone(); +scrollToBottom() + +function addValidationEventListeners(input, label, minValue, maxValue) { + const events = ['change', 'paste', 'input']; + // check input values on specified events + events.forEach(event => { + input.addEventListener(event, _ => validateNumberField(input, label, minValue, maxValue)); + }); + // dont send form if data isnt valid + inputForm.addEventListener('submit', e => { + if (!validateNumberField(input, label, minValue, maxValue)) { + e.preventDefault(); + } + }); + input.placeholder = `От ${minValue} до ${maxValue}`; +} + +function scrollToBottom() { + const results = document.getElementById('main') + results.scrollTop = results.scrollHeight +} + +function validateNumberField(input, label, minValue, maxValue) { + // check if input is numeric and is in range [minValue, maxValue] + const inputValue = input.value.replace(',', '.'); + const number = parseFloat(inputValue); + const isNumeric = !isNaN(number); + if (isNumeric) input.value = limitDecimalPlaces(inputValue, 3); + const isValid = isNumeric && minValue <= number && number <= maxValue; + if (isValid) { + // green checkmark + label.innerHTML = '\u2714'; + label.style.color = 'green'; + } + else { + // red warning + label.innerHTML = `Введите число от ${minValue} до ${maxValue}`; + label.style.color = 'red' + } + return isValid; +} + +function limitDecimalPlaces(str, decimalPlaces) { + const pointIndex = str.indexOf('.'); + return str.substring(0, pointIndex + decimalPlaces + 1); +} + +function setTimezone() { + const time = new Date(); + document.cookie = `timezoneOffset=${time.getTimezoneOffset()}`; +} diff --git a/src/main/webapp/js/plot.js b/src/main/webapp/js/plot.js new file mode 100644 index 0000000..9a9cf88 --- /dev/null +++ b/src/main/webapp/js/plot.js @@ -0,0 +1,105 @@ +const plot = document.getElementById('plot') +const plotCtx = plot.getContext('2d') + +drawPlot() + +plot.addEventListener('mousedown', e => { + const r = rInput.value + if (r === undefined) return + const [xPlot, yPlot] = getMousePlotCoords(plot, e) + const [x, y] = convertToServerCoordinates(xPlot, yPlot, r) + window.location.replace(`./control?xValue=${x}&yValue=${y}&rValue=${r}&xPlot=${xPlot}&yPlot=${yPlot}`) +}) + +function getMousePlotCoords(plot, event) { + const rect = plot.getBoundingClientRect() + const x = event.clientX - rect.left + const y = event.clientY - rect.top + return [x, y] +} + +function convertToServerCoordinates(xPlot, yPlot, r) { + const widthRatio = 2 * r / plot.width, heightRatio = 2 * r / plot.height + const x = xPlot * widthRatio - r, y = -(yPlot * heightRatio - r) + return [x, y] +} + +function drawLastHit() { + const params = new URLSearchParams(window.location.search) + const xPlotParam = params.get("xPlot"), yPlotParam = params.get("yPlot") + if (!xPlotParam || !yPlotParam) return + const xPlot = parseFloat(xPlotParam), yPlot = parseFloat(yPlotParam) + plotCtx.strokeStyle = 'red' + plotCtx.fillStyle = 'red' + plotCtx.beginPath() + plotCtx.arc(xPlot, yPlot, 5, 0, 2 * Math.PI) + plotCtx.fill() + plotCtx.closePath() +} + +function drawPlot() { + const halfWidth = plot.width / 2, halfHeight = plot.height / 2 + const quarterWidth = halfWidth / 2, quarterHeight = halfHeight / 2 + plotCtx.clearRect(0, 0, plot.width, plot.height) + + plotCtx.strokeStyle = 'pink' + plotCtx.fillStyle = 'pink' + plotCtx.lineWidth = 1 + // 2nd quadrant - rectangle + plotCtx.fillRect(quarterWidth, 0, quarterWidth, halfHeight) + + // 3rd quadrant - right triangle + plotCtx.beginPath() + plotCtx.moveTo(quarterWidth, halfHeight) + plotCtx.lineTo(halfWidth, halfHeight) + plotCtx.lineTo(halfWidth, 3 * quarterHeight) + plotCtx.fill() + plotCtx.closePath() + + // 4th quadrant - circle quarter + plotCtx.beginPath() + plotCtx.arc(halfWidth, halfHeight, quarterWidth, -Math.PI / 2, 0) + plotCtx.moveTo(halfWidth, quarterHeight) + plotCtx.lineTo(halfWidth, halfHeight) + plotCtx.lineTo(3 * quarterWidth, halfHeight) + plotCtx.fill() + plotCtx.closePath() + + plotCtx.strokeStyle = 'gray' + plotCtx.beginPath() + for (let i = 0; i < 16; i++) { + const lineX = plot.width * i / 16, lineY = plot.height * i / 16 + plotCtx.moveTo(lineX, 0) + plotCtx.lineTo(lineX, plot.height) + plotCtx.moveTo(0, lineY) + plotCtx.lineTo(plot.width, lineY) + } + plotCtx.stroke() + plotCtx.closePath() + + plotCtx.strokeStyle = 'black' + plotCtx.fillStyle = 'black' + plotCtx.lineWidth = 3 + // x and y axis + plotCtx.beginPath() + plotCtx.moveTo(halfWidth, 0) + plotCtx.lineTo(halfWidth, plot.height) + plotCtx.moveTo(0, halfHeight) + plotCtx.lineTo(plot.width, halfHeight) + + // markings and labels + const labels = ['-R', '-R/2', '0', 'R/2', 'R'] + for (let i = 0; i <= 4; i++) { + if (i === 2) continue + const markingX = plot.width * i / 4, markingY = plot.height * (4 - i) / 4 + plotCtx.moveTo(markingX, halfHeight - 5) + plotCtx.lineTo(markingX, halfHeight + 5) + plotCtx.fillText(labels[i], markingX - 8 * (i - 2), halfHeight - 10, 20) + plotCtx.moveTo(halfWidth - 5, markingY) + plotCtx.lineTo(halfWidth + 5, markingY) + plotCtx.fillText(labels[i], halfWidth + 10, markingY + 8 * (i - 2), 20) + } + plotCtx.stroke() + plotCtx.closePath() + drawLastHit() +}