diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..7bc07ec --- /dev/null +++ b/.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/.idea/encodings.xml b/.idea/encodings.xml new file mode 100644 index 0000000..aa00ffa --- /dev/null +++ b/.idea/encodings.xml @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..f0f8287 --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,12 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..28faa95 --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/README.md b/README.md index 0d2067d..b432446 100644 --- a/README.md +++ b/README.md @@ -5,4 +5,8 @@ ### Apache httpd - [ ] Enable logging to APACHE_LOG_DIR (this folder is currently being created during build process, but not used by apache server) - [X] Redirecting from /index.html to / -- [ ] https \ No newline at end of file +- [ ] https support + +### Java FCGI +- [ ] User input validayion +- [ ] Add support of responces with information about errors diff --git a/docker-compose.yaml b/docker-compose.yaml index b5133c5..d3e538d 100644 --- a/docker-compose.yaml +++ b/docker-compose.yaml @@ -7,4 +7,20 @@ services: - APACHE_LOG_DIR="/var/log/httpd-server/" restart: on-failure ports: - - "8080:80" \ No newline at end of file + - "8080:80" + networks: + - internal_net + + java-fastcgi: + container_name: fastcgi-server + build: + context: ./server/ + restart: on-failure + depends_on: + - apache-httpd + networks: + - internal_net + +networks: + internal_net: + driver: bridge \ No newline at end of file diff --git a/httpd/conf/custom/apache-httpd-lab1.conf b/httpd/conf/custom/apache-httpd-lab1.conf index 7dc5172..4b9a4d7 100644 --- a/httpd/conf/custom/apache-httpd-lab1.conf +++ b/httpd/conf/custom/apache-httpd-lab1.conf @@ -12,6 +12,20 @@ AllowOverride AuthConfig FileInfo + # ========================== + # FastCGI server setup start + # ========================== + + ProxyPass /fcgi-bin/ fcgi://fastcgi-server:55555/ + ProxyPassReverse /fcgi-bin/ fcgi://fastcgi-server:55555/ + + + Require all granted + + + # ========================== + # FastCGI server setup end + # ========================== # ErrorLog /var/log/httpd-server/error.log # CustomLog /var/log/httpd-server/access.log combined diff --git a/httpd/conf/httpd.conf b/httpd/conf/httpd.conf index bb2a000..b0097be 100644 --- a/httpd/conf/httpd.conf +++ b/httpd/conf/httpd.conf @@ -139,11 +139,11 @@ LoadModule headers_module modules/mod_headers.so LoadModule setenvif_module modules/mod_setenvif.so LoadModule version_module modules/mod_version.so #LoadModule remoteip_module modules/mod_remoteip.so -#LoadModule proxy_module modules/mod_proxy.so +LoadModule proxy_module modules/mod_proxy.so #LoadModule proxy_connect_module modules/mod_proxy_connect.so #LoadModule proxy_ftp_module modules/mod_proxy_ftp.so #LoadModule proxy_http_module modules/mod_proxy_http.so -#LoadModule proxy_fcgi_module modules/mod_proxy_fcgi.so +LoadModule proxy_fcgi_module modules/mod_proxy_fcgi.so #LoadModule proxy_scgi_module modules/mod_proxy_scgi.so #LoadModule proxy_uwsgi_module modules/mod_proxy_uwsgi.so #LoadModule proxy_fdpass_module modules/mod_proxy_fdpass.so 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/Main.xml b/server/.idea/runConfigurations/Main.xml new file mode 100644 index 0000000..2e1a7a7 --- /dev/null +++ b/server/.idea/runConfigurations/Main.xml @@ -0,0 +1,17 @@ + + + + \ No newline at end of file diff --git a/server/.idea/runConfigurations/build_lab1.xml b/server/.idea/runConfigurations/build_lab1.xml new file mode 100644 index 0000000..590c3fc --- /dev/null +++ b/server/.idea/runConfigurations/build_lab1.xml @@ -0,0 +1,33 @@ + + + + + + + + \ No newline at end of file diff --git a/server/.idea/runConfigurations/install_lib.xml b/server/.idea/runConfigurations/install_lib.xml new file mode 100644 index 0000000..46b58cf --- /dev/null +++ b/server/.idea/runConfigurations/install_lib.xml @@ -0,0 +1,37 @@ + + + + + + + + \ No newline at end of file diff --git a/server/.idea/vcs.xml b/server/.idea/vcs.xml new file mode 100644 index 0000000..288b36b --- /dev/null +++ b/server/.idea/vcs.xml @@ -0,0 +1,7 @@ + + + + + + + \ 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..5d96a1a --- /dev/null +++ b/server/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,2 @@ +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/Dockerfile b/server/Dockerfile new file mode 100644 index 0000000..3cf7d07 --- /dev/null +++ b/server/Dockerfile @@ -0,0 +1,20 @@ +FROM openjdk:17-jdk-slim AS build + +# copy maven confis +COPY pom.xml mvnw ./ +COPY .mvn .mvn + +# copy fastcgi lib +COPY lib lib + +# mvnw (aka Apache Maven Wrapper) allows to acess maven simplier +RUN ./mvnw install:install-file -Dfile=./lib/fastcgi-lib.jar -DgroupId=com.fastcgi -DartifactId=fastcgi -Dversion=1.0 -Dpackaging=jar +RUN ./mvnw dependency:resolve + +COPY src src +RUN ./mvnw clean package + +FROM openjdk:17-jdk-slim +WORKDIR server +COPY --from=build target/*.jar server-1.0.jar +ENTRYPOINT ["java", "-DFCGI_PORT=55555", "-jar", "server-1.0.jar"] \ No newline at end of file diff --git a/server/dependency-reduced-pom.xml b/server/dependency-reduced-pom.xml new file mode 100644 index 0000000..9443a5f --- /dev/null +++ b/server/dependency-reduced-pom.xml @@ -0,0 +1,43 @@ + + + 4.0.0 + org.web1 + server + 1.0 + + + + maven-jar-plugin + 3.4.2 + + + + org.web1.Main + + + true + + + + + + maven-shade-plugin + 3.6.0 + + + shade-my-jar + package + + shade + + + + + + + + 17 + 17 + UTF-8 + + diff --git a/server/lib/fastcgi-lib.jar b/server/lib/fastcgi-lib.jar new file mode 100644 index 0000000..1f35370 Binary files /dev/null and b/server/lib/fastcgi-lib.jar differ diff --git a/server/mvnw b/server/mvnw new file mode 100755 index 0000000..e9cf8d3 --- /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.3 +# +# 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/pom.xml b/server/pom.xml new file mode 100644 index 0000000..1962106 --- /dev/null +++ b/server/pom.xml @@ -0,0 +1,61 @@ + + + 4.0.0 + + org.web1 + server + 1.0 + + + 17 + 17 + UTF-8 + + + + + com.fastcgi + fastcgi + 1.0 + + + + + + + + org.apache.maven.plugins + maven-jar-plugin + 3.4.2 + + + + org.web1.Main + + + true + + + + + + + + org.apache.maven.plugins + maven-shade-plugin + 3.6.0 + + + shade-my-jar + package + + shade + + + + + + + \ No newline at end of file diff --git a/server/src/main/java/org/web1/Main.java b/server/src/main/java/org/web1/Main.java new file mode 100644 index 0000000..d5488be --- /dev/null +++ b/server/src/main/java/org/web1/Main.java @@ -0,0 +1,35 @@ +package org.web1; + +import com.fastcgi.*; +import java.util.HashMap; +import java.util.function.Function; + +import org.web1.checkers.Checker; +import org.web1.checkers.CheckerFunction; +import org.web1.utils.JsonBuilder; +import org.web1.utils.QueryStringToHashmap; +import org.web1.utils.ResponseController; + +public class Main { + private static final Function> parseQuery = new QueryStringToHashmap(); + private static final CheckerFunction checker = new Checker(); + + public static void main(String[] args) { + FCGIInterface fastCGI = new FCGIInterface(); + + while (fastCGI.FCGIaccept() >= 0) { + HashMap queryParams = parseQuery.apply( + FCGIInterface.request.params.getProperty("QUERY_STRING") + ); + boolean checkResult = checker.test(queryParams); + + String result = ResponseController.create( + new JsonBuilder() + .add("result", checkResult) + .add("elapsedTime", 100) + ); + + System.out.println(result); + } + } +} \ No newline at end of file diff --git a/server/src/main/java/org/web1/checkers/Checker.java b/server/src/main/java/org/web1/checkers/Checker.java new file mode 100644 index 0000000..6885c88 --- /dev/null +++ b/server/src/main/java/org/web1/checkers/Checker.java @@ -0,0 +1,36 @@ +package org.web1.checkers; +import org.web1.checkers.utils.GraphQuarters; +import org.web1.checkers.utils.GraphUtils; + +import java.util.HashMap; + +public class Checker implements CheckerFunction{ + public boolean test(HashMap data) { + int x = Integer.parseInt(data.get("x")); + float y = Float.parseFloat(data.get("y")); + float r = Float.parseFloat(data.get("r")); + + final GraphQuarters quarter = GraphUtils.getQuarter(x, y); + + if (quarter == GraphQuarters.FIRST_QUADRANT) return firstQuarterTester(x, y, r); + else if (quarter == GraphQuarters.SECOND_QUADRANT) return secondQuarterTester(x, y, r); + else if (quarter == GraphQuarters.THIRD_QUADRANT) return thirdQuarterTester(x, y, r); + return forthQuarterTester(x, y, r); + } + + private boolean firstQuarterTester(int x, float y, float r) { + return x <= r/2 && y <= r; + } + + private boolean secondQuarterTester(int x, float y, float r) { + return y <= (r/2 + 0.5f*x); + } + + private boolean thirdQuarterTester(int x, float y, float r) { + return false; + } + + private boolean forthQuarterTester(int x, float y, float r) { + return Math.sqrt(x*x + y*y) <= r/2; + } +} \ No newline at end of file diff --git a/server/src/main/java/org/web1/checkers/CheckerFunction.java b/server/src/main/java/org/web1/checkers/CheckerFunction.java new file mode 100644 index 0000000..38f03ec --- /dev/null +++ b/server/src/main/java/org/web1/checkers/CheckerFunction.java @@ -0,0 +1,8 @@ +package org.web1.checkers; + +import java.util.HashMap; + +@FunctionalInterface +public interface CheckerFunction { + boolean test(HashMap data); +} diff --git a/server/src/main/java/org/web1/checkers/utils/GraphQuarters.java b/server/src/main/java/org/web1/checkers/utils/GraphQuarters.java new file mode 100644 index 0000000..b522194 --- /dev/null +++ b/server/src/main/java/org/web1/checkers/utils/GraphQuarters.java @@ -0,0 +1,8 @@ +package org.web1.checkers.utils; + +public enum GraphQuarters { + FIRST_QUADRANT, + SECOND_QUADRANT, + THIRD_QUADRANT, + FORTH_QUADRANT, FOURTH_QUADRANT +} diff --git a/server/src/main/java/org/web1/checkers/utils/GraphUtils.java b/server/src/main/java/org/web1/checkers/utils/GraphUtils.java new file mode 100644 index 0000000..21af497 --- /dev/null +++ b/server/src/main/java/org/web1/checkers/utils/GraphUtils.java @@ -0,0 +1,13 @@ +package org.web1.checkers.utils; + +public class GraphUtils { + public static GraphQuarters getQuarter(int x, float y) { + boolean isXGraterOrEqualsZero = x >= 0; + boolean isYGraterOrEqualsZero = y >= 0; + + if (isXGraterOrEqualsZero && isYGraterOrEqualsZero) return GraphQuarters.FIRST_QUADRANT; + else if (!isXGraterOrEqualsZero && !isYGraterOrEqualsZero) return GraphQuarters.THIRD_QUADRANT; + else if (!isXGraterOrEqualsZero && isYGraterOrEqualsZero) return GraphQuarters.SECOND_QUADRANT; // читабельность важнее + return GraphQuarters.FOURTH_QUADRANT; + } +} diff --git a/server/src/main/java/org/web1/utils/JsonBuilder.java b/server/src/main/java/org/web1/utils/JsonBuilder.java new file mode 100644 index 0000000..44c805f --- /dev/null +++ b/server/src/main/java/org/web1/utils/JsonBuilder.java @@ -0,0 +1,21 @@ +package org.web1.utils; + +import java.util.HashMap; + +public class JsonBuilder { + private final HashMap data = new HashMap<>(); + + public JsonBuilder add(String key, T value) { + this.data.put(key, value.toString()); + return this; + } + + public String build() { + StringBuilder jsonString = new StringBuilder("{\n"); + + for (String key : data.keySet()) + jsonString.append(String.format("\t%s: %s,\n", key, data.get(key))); + + return jsonString + "}"; + } +} diff --git a/server/src/main/java/org/web1/utils/QueryStringToHashmap.java b/server/src/main/java/org/web1/utils/QueryStringToHashmap.java new file mode 100644 index 0000000..da22d77 --- /dev/null +++ b/server/src/main/java/org/web1/utils/QueryStringToHashmap.java @@ -0,0 +1,23 @@ +package org.web1.utils; + +import java.util.HashMap; +import java.util.function.Function; + +public class QueryStringToHashmap implements Function> { + public HashMap apply(String jsonStr) { + HashMap params = new HashMap<>(); + + String[] pairs = jsonStr.split("&"); // get key+value pairs string + + for (String pair : pairs) { + + String[] keyValue = pair.split("="); // get key+value pairs arrays. first elem - key, second - value + + if (keyValue.length > 1) params.put(keyValue[0], keyValue[1]); + else params.put(keyValue[0], ""); + } + + return params; + } + +} diff --git a/server/src/main/java/org/web1/utils/ResponseController.java b/server/src/main/java/org/web1/utils/ResponseController.java new file mode 100644 index 0000000..00f314c --- /dev/null +++ b/server/src/main/java/org/web1/utils/ResponseController.java @@ -0,0 +1,16 @@ +package org.web1.utils; + +public class ResponseController { + private static final String BASE_RESPONSE = """ + Access-Control-Allow-Origin: * + Connection: keep-alive + Content-Type: application/json + Content-Length: %d + \s + %s + \s"""; + public static String create(JsonBuilder jsonBuilder) { + String response = jsonBuilder.build(); + return String.format(BASE_RESPONSE, response.length(), response); + } +}