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/.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 e5782a6..49d52a4 100644 --- a/README.md +++ b/README.md @@ -1 +1,12 @@ -# WebProgramming lab work №1 \ No newline at end of file +# WebProgramming lab work №1 + +## TODOs + +### 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 support + +### Java FCGI +- [ ] User input validation +- [ ] Add support of responces with information about errors diff --git a/docker-compose.yaml b/docker-compose.yaml new file mode 100644 index 0000000..d3e538d --- /dev/null +++ b/docker-compose.yaml @@ -0,0 +1,26 @@ +services: + apache-httpd: + container_name: httpd-server + build: + context: ./httpd/ + args: + - APACHE_LOG_DIR="/var/log/httpd-server/" + restart: on-failure + ports: + - "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/Dockerfile b/httpd/Dockerfile new file mode 100644 index 0000000..555b51c --- /dev/null +++ b/httpd/Dockerfile @@ -0,0 +1,19 @@ +FROM httpd:2.4-alpine + +# create staticfiles directory +RUN mkdir -p /var/www/localhost/htdocs +COPY ./static/ /var/www/localhost/htdocs/static/ + +# add custom apache configs +RUN mkdir -p /etc/apache2/conf-custom +COPY ./conf/custom/ /etc/apache2/conf-custom/ + +# create logs directory (temporary disabled) +ARG APACHE_LOG_DIR +RUN mkdir -p ${APACHE_LOG_DIR} +RUN chown www-data:www-data ${APACHE_LOG_DIR} + +# setup main apache configuration +COPY ./conf/httpd.conf /usr/local/apache2/conf/httpd.conf + +EXPOSE 80 \ No newline at end of file diff --git a/httpd/conf/custom/apache-httpd-lab1.conf b/httpd/conf/custom/apache-httpd-lab1.conf new file mode 100644 index 0000000..4b9a4d7 --- /dev/null +++ b/httpd/conf/custom/apache-httpd-lab1.conf @@ -0,0 +1,32 @@ + + ServerAdmin reshes@rambler.ru + DocumentRoot /var/www/localhost/htdocs/static/ + + + # do NOT generate index.html if it doesn't present + Options -Indexes + + # Allows usage of some instructions in .htaccess + # AuthConfig - allows set custom Require + # FileInfo - allows set custom Redirect and RewriteRule + 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 + \ No newline at end of file diff --git a/httpd/conf/httpd.conf b/httpd/conf/httpd.conf new file mode 100644 index 0000000..b0097be --- /dev/null +++ b/httpd/conf/httpd.conf @@ -0,0 +1,552 @@ +# +# This is the main Apache HTTP server configuration file. It contains the +# configuration directives that give the server its instructions. +# See for detailed information. +# In particular, see +# +# for a discussion of each configuration directive. +# +# Do NOT simply read the instructions in here without understanding +# what they do. They're here only as hints or reminders. If you are unsure +# consult the online docs. You have been warned. +# +# Configuration and logfile names: If the filenames you specify for many +# of the server's control files begin with "/" (or "drive:/" for Win32), the +# server will use that explicit path. If the filenames do *not* begin +# with "/", the value of ServerRoot is prepended -- so "logs/access_log" +# with ServerRoot set to "/usr/local/apache2" will be interpreted by the +# server as "/usr/local/apache2/logs/access_log", whereas "/logs/access_log" +# will be interpreted as '/logs/access_log'. + +# +# ServerRoot: The top of the directory tree under which the server's +# configuration, error, and log files are kept. +# +# Do not add a slash at the end of the directory path. If you point +# ServerRoot at a non-local disk, be sure to specify a local disk on the +# Mutex directive, if file-based mutexes are used. If you wish to share the +# same ServerRoot for multiple httpd daemons, you will need to change at +# least PidFile. +# +ServerRoot "/usr/local/apache2" + +# +# Mutex: Allows you to set the mutex mechanism and mutex file directory +# for individual mutexes, or change the global defaults +# +# Uncomment and change the directory if mutexes are file-based and the default +# mutex file directory is not on a local disk or is not appropriate for some +# other reason. +# +# Mutex default:logs + +# +# Listen: Allows you to bind Apache to specific IP addresses and/or +# ports, instead of the default. See also the +# directive. +# +# Change this to Listen on specific IP addresses as shown below to +# prevent Apache from glomming onto all bound IP addresses. +# +#Listen 12.34.56.78:80 +Listen 80 + +# +# Dynamic Shared Object (DSO) Support +# +# To be able to use the functionality of a module which was built as a DSO you +# have to place corresponding `LoadModule' lines at this location so the +# directives contained in it are actually available _before_ they are used. +# Statically compiled modules (those listed by `httpd -l') do not need +# to be loaded here. +# +# Example: +# LoadModule foo_module modules/mod_foo.so +# +LoadModule mpm_event_module modules/mod_mpm_event.so +#LoadModule mpm_prefork_module modules/mod_mpm_prefork.so +#LoadModule mpm_worker_module modules/mod_mpm_worker.so +LoadModule authn_file_module modules/mod_authn_file.so +#LoadModule authn_dbm_module modules/mod_authn_dbm.so +#LoadModule authn_anon_module modules/mod_authn_anon.so +#LoadModule authn_dbd_module modules/mod_authn_dbd.so +#LoadModule authn_socache_module modules/mod_authn_socache.so +LoadModule authn_core_module modules/mod_authn_core.so +LoadModule authz_host_module modules/mod_authz_host.so +LoadModule authz_groupfile_module modules/mod_authz_groupfile.so +LoadModule authz_user_module modules/mod_authz_user.so +#LoadModule authz_dbm_module modules/mod_authz_dbm.so +#LoadModule authz_owner_module modules/mod_authz_owner.so +#LoadModule authz_dbd_module modules/mod_authz_dbd.so +LoadModule authz_core_module modules/mod_authz_core.so +#LoadModule authnz_ldap_module modules/mod_authnz_ldap.so +#LoadModule authnz_fcgi_module modules/mod_authnz_fcgi.so +LoadModule access_compat_module modules/mod_access_compat.so +LoadModule auth_basic_module modules/mod_auth_basic.so +#LoadModule auth_form_module modules/mod_auth_form.so +#LoadModule auth_digest_module modules/mod_auth_digest.so +#LoadModule allowmethods_module modules/mod_allowmethods.so +#LoadModule isapi_module modules/mod_isapi.so +#LoadModule file_cache_module modules/mod_file_cache.so +#LoadModule cache_module modules/mod_cache.so +#LoadModule cache_disk_module modules/mod_cache_disk.so +#LoadModule cache_socache_module modules/mod_cache_socache.so +#LoadModule socache_shmcb_module modules/mod_socache_shmcb.so +#LoadModule socache_dbm_module modules/mod_socache_dbm.so +#LoadModule socache_memcache_module modules/mod_socache_memcache.so +#LoadModule socache_redis_module modules/mod_socache_redis.so +#LoadModule watchdog_module modules/mod_watchdog.so +#LoadModule macro_module modules/mod_macro.so +#LoadModule dbd_module modules/mod_dbd.so +#LoadModule bucketeer_module modules/mod_bucketeer.so +#LoadModule dumpio_module modules/mod_dumpio.so +#LoadModule echo_module modules/mod_echo.so +#LoadModule example_hooks_module modules/mod_example_hooks.so +#LoadModule case_filter_module modules/mod_case_filter.so +#LoadModule case_filter_in_module modules/mod_case_filter_in.so +#LoadModule example_ipc_module modules/mod_example_ipc.so +#LoadModule buffer_module modules/mod_buffer.so +#LoadModule data_module modules/mod_data.so +#LoadModule ratelimit_module modules/mod_ratelimit.so +LoadModule reqtimeout_module modules/mod_reqtimeout.so +#LoadModule ext_filter_module modules/mod_ext_filter.so +#LoadModule request_module modules/mod_request.so +#LoadModule include_module modules/mod_include.so +LoadModule filter_module modules/mod_filter.so +#LoadModule reflector_module modules/mod_reflector.so +#LoadModule substitute_module modules/mod_substitute.so +#LoadModule sed_module modules/mod_sed.so +#LoadModule charset_lite_module modules/mod_charset_lite.so +#LoadModule deflate_module modules/mod_deflate.so +#LoadModule xml2enc_module modules/mod_xml2enc.so +#LoadModule proxy_html_module modules/mod_proxy_html.so +#LoadModule brotli_module modules/mod_brotli.so +LoadModule mime_module modules/mod_mime.so +#LoadModule ldap_module modules/mod_ldap.so +LoadModule log_config_module modules/mod_log_config.so +#LoadModule log_debug_module modules/mod_log_debug.so +#LoadModule log_forensic_module modules/mod_log_forensic.so +#LoadModule logio_module modules/mod_logio.so +#LoadModule lua_module modules/mod_lua.so +LoadModule env_module modules/mod_env.so +#LoadModule mime_magic_module modules/mod_mime_magic.so +#LoadModule cern_meta_module modules/mod_cern_meta.so +#LoadModule expires_module modules/mod_expires.so +LoadModule headers_module modules/mod_headers.so +#LoadModule ident_module modules/mod_ident.so +#LoadModule usertrack_module modules/mod_usertrack.so +#LoadModule unique_id_module modules/mod_unique_id.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_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_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 +#LoadModule proxy_wstunnel_module modules/mod_proxy_wstunnel.so +#LoadModule proxy_ajp_module modules/mod_proxy_ajp.so +#LoadModule proxy_balancer_module modules/mod_proxy_balancer.so +#LoadModule proxy_express_module modules/mod_proxy_express.so +#LoadModule proxy_hcheck_module modules/mod_proxy_hcheck.so +#LoadModule session_module modules/mod_session.so +#LoadModule session_cookie_module modules/mod_session_cookie.so +#LoadModule session_crypto_module modules/mod_session_crypto.so +#LoadModule session_dbd_module modules/mod_session_dbd.so +#LoadModule slotmem_shm_module modules/mod_slotmem_shm.so +#LoadModule slotmem_plain_module modules/mod_slotmem_plain.so +#LoadModule ssl_module modules/mod_ssl.so +#LoadModule optional_hook_export_module modules/mod_optional_hook_export.so +#LoadModule optional_hook_import_module modules/mod_optional_hook_import.so +#LoadModule optional_fn_import_module modules/mod_optional_fn_import.so +#LoadModule optional_fn_export_module modules/mod_optional_fn_export.so +#LoadModule dialup_module modules/mod_dialup.so +#LoadModule http2_module modules/mod_http2.so +#LoadModule proxy_http2_module modules/mod_proxy_http2.so +#LoadModule md_module modules/mod_md.so +#LoadModule lbmethod_byrequests_module modules/mod_lbmethod_byrequests.so +#LoadModule lbmethod_bytraffic_module modules/mod_lbmethod_bytraffic.so +#LoadModule lbmethod_bybusyness_module modules/mod_lbmethod_bybusyness.so +#LoadModule lbmethod_heartbeat_module modules/mod_lbmethod_heartbeat.so +LoadModule unixd_module modules/mod_unixd.so +#LoadModule heartbeat_module modules/mod_heartbeat.so +#LoadModule heartmonitor_module modules/mod_heartmonitor.so +#LoadModule dav_module modules/mod_dav.so +LoadModule status_module modules/mod_status.so +LoadModule autoindex_module modules/mod_autoindex.so +#LoadModule asis_module modules/mod_asis.so +#LoadModule info_module modules/mod_info.so +#LoadModule suexec_module modules/mod_suexec.so + + #LoadModule cgid_module modules/mod_cgid.so + + + #LoadModule cgi_module modules/mod_cgi.so + +#LoadModule dav_fs_module modules/mod_dav_fs.so +#LoadModule dav_lock_module modules/mod_dav_lock.so +#LoadModule vhost_alias_module modules/mod_vhost_alias.so +#LoadModule negotiation_module modules/mod_negotiation.so +LoadModule dir_module modules/mod_dir.so +#LoadModule imagemap_module modules/mod_imagemap.so +#LoadModule actions_module modules/mod_actions.so +#LoadModule speling_module modules/mod_speling.so +#LoadModule userdir_module modules/mod_userdir.so +LoadModule alias_module modules/mod_alias.so +LoadModule rewrite_module modules/mod_rewrite.so + + +# +# If you wish httpd to run as a different user or group, you must run +# httpd as root initially and it will switch. +# +# User/Group: The name (or #number) of the user/group to run httpd as. +# It is usually good practice to create a dedicated user and group for +# running httpd, as with most system services. +# +User www-data +Group www-data + + + +# 'Main' server configuration +# +# The directives in this section set up the values used by the 'main' +# server, which responds to any requests that aren't handled by a +# definition. These values also provide defaults for +# any containers you may define later in the file. +# +# All of these directives may appear inside containers, +# in which case these default settings will be overridden for the +# virtual host being defined. +# + +# +# ServerAdmin: Your address, where problems with the server should be +# e-mailed. This address appears on some server-generated pages, such +# as error documents. e.g. admin@your-domain.com +# +ServerAdmin you@example.com + +# +# ServerName gives the name and port that the server uses to identify itself. +# This can often be determined automatically, but we recommend you specify +# it explicitly to prevent problems during startup. +# +# If your host doesn't have a registered DNS name, enter its IP address here. +# +#ServerName www.example.com:80 + +# +# Deny access to the entirety of your server's filesystem. You must +# explicitly permit access to web content directories in other +# blocks below. +# + + AllowOverride none + Require all denied + + +# +# Note that from this point forward you must specifically allow +# particular features to be enabled - so if something's not working as +# you might expect, make sure that you have specifically enabled it +# below. +# + +# +# DocumentRoot: The directory out of which you will serve your +# documents. By default, all requests are taken from this directory, but +# symbolic links and aliases may be used to point to other locations. +# +DocumentRoot "/usr/local/apache2/htdocs" + + # + # Possible values for the Options directive are "None", "All", + # or any combination of: + # Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews + # + # Note that "MultiViews" must be named *explicitly* --- "Options All" + # doesn't give it to you. + # + # The Options directive is both complicated and important. Please see + # http://httpd.apache.org/docs/2.4/mod/core.html#options + # for more information. + # + Options Indexes FollowSymLinks + + # + # AllowOverride controls what directives may be placed in .htaccess files. + # It can be "All", "None", or any combination of the keywords: + # AllowOverride FileInfo AuthConfig Limit + # + AllowOverride None + + # + # Controls who can get stuff from this server. + # + Require all granted + + +# +# DirectoryIndex: sets the file that Apache will serve if a directory +# is requested. +# + + DirectoryIndex index.html + + +# +# The following lines prevent .htaccess and .htpasswd files from being +# viewed by Web clients. +# + + Require all denied + + +# +# ErrorLog: The location of the error log file. +# If you do not specify an ErrorLog directive within a +# container, error messages relating to that virtual host will be +# logged here. If you *do* define an error logfile for a +# container, that host's errors will be logged there and not here. +# +ErrorLog /proc/self/fd/2 + +# +# LogLevel: Control the number of messages logged to the error_log. +# Possible values include: debug, info, notice, warn, error, crit, +# alert, emerg. +# +LogLevel warn + + + # + # The following directives define some format nicknames for use with + # a CustomLog directive (see below). + # + LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined + LogFormat "%h %l %u %t \"%r\" %>s %b" common + + + # You need to enable mod_logio.c to use %I and %O + LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio + + + # + # The location and format of the access logfile (Common Logfile Format). + # If you do not define any access logfiles within a + # container, they will be logged here. Contrariwise, if you *do* + # define per- access logfiles, transactions will be + # logged therein and *not* in this file. + # + CustomLog /proc/self/fd/1 common + + # + # If you prefer a logfile with access, agent, and referer information + # (Combined Logfile Format) you can use the following directive. + # + #CustomLog "logs/access_log" combined + + + + # + # Redirect: Allows you to tell clients about documents that used to + # exist in your server's namespace, but do not anymore. The client + # will make a new request for the document at its new location. + # Example: + # Redirect permanent /foo http://www.example.com/bar + + # + # Alias: Maps web paths into filesystem paths and is used to + # access content that does not live under the DocumentRoot. + # Example: + # Alias /webpath /full/filesystem/path + # + # If you include a trailing / on /webpath then the server will + # require it to be present in the URL. You will also likely + # need to provide a section to allow access to + # the filesystem path. + + # + # ScriptAlias: This controls which directories contain server scripts. + # ScriptAliases are essentially the same as Aliases, except that + # documents in the target directory are treated as applications and + # run by the server when requested rather than as documents sent to the + # client. The same rules about trailing "/" apply to ScriptAlias + # directives as to Alias. + # + ScriptAlias /cgi-bin/ "/usr/local/apache2/cgi-bin/" + + + + + # + # ScriptSock: On threaded servers, designate the path to the UNIX + # socket used to communicate with the CGI daemon of mod_cgid. + # + #Scriptsock cgisock + + +# +# "/usr/local/apache2/cgi-bin" should be changed to whatever your ScriptAliased +# CGI directory exists, if you have that configured. +# + + AllowOverride None + Options None + Require all granted + + + + # + # Avoid passing HTTP_PROXY environment to CGI's on this or any proxied + # backend servers which have lingering "httpoxy" defects. + # 'Proxy' request header is undefined by the IETF, not listed by IANA + # + RequestHeader unset Proxy early + + + + # + # TypesConfig points to the file containing the list of mappings from + # filename extension to MIME-type. + # + TypesConfig conf/mime.types + + # + # AddType allows you to add to or override the MIME configuration + # file specified in TypesConfig for specific file types. + # + #AddType application/x-gzip .tgz + # + # AddEncoding allows you to have certain browsers uncompress + # information on the fly. Note: Not all browsers support this. + # + #AddEncoding x-compress .Z + #AddEncoding x-gzip .gz .tgz + # + # If the AddEncoding directives above are commented-out, then you + # probably should define those extensions to indicate media types: + # + AddType application/x-compress .Z + AddType application/x-gzip .gz .tgz + + # + # AddHandler allows you to map certain file extensions to "handlers": + # actions unrelated to filetype. These can be either built into the server + # or added with the Action directive (see below) + # + # To use CGI scripts outside of ScriptAliased directories: + # (You will also need to add "ExecCGI" to the "Options" directive.) + # + #AddHandler cgi-script .cgi + + # For type maps (negotiated resources): + #AddHandler type-map var + + # + # Filters allow you to process content before it is sent to the client. + # + # To parse .shtml files for server-side includes (SSI): + # (You will also need to add "Includes" to the "Options" directive.) + # + #AddType text/html .shtml + #AddOutputFilter INCLUDES .shtml + + +# +# The mod_mime_magic module allows the server to use various hints from the +# contents of the file itself to determine its type. The MIMEMagicFile +# directive tells the module where the hint definitions are located. +# +#MIMEMagicFile conf/magic + +# +# Customizable error responses come in three flavors: +# 1) plain text 2) local redirects 3) external redirects +# +# Some examples: +#ErrorDocument 500 "The server made a boo boo." +#ErrorDocument 404 /missing.html +#ErrorDocument 404 "/cgi-bin/missing_handler.pl" +#ErrorDocument 402 http://www.example.com/subscription_info.html +# + +# +# MaxRanges: Maximum number of Ranges in a request before +# returning the entire resource, or one of the special +# values 'default', 'none' or 'unlimited'. +# Default setting is to accept 200 Ranges. +#MaxRanges unlimited + +# +# EnableMMAP and EnableSendfile: On systems that support it, +# memory-mapping or the sendfile syscall may be used to deliver +# files. This usually improves server performance, but must +# be turned off when serving from networked-mounted +# filesystems or if support for these functions is otherwise +# broken on your system. +# Defaults: EnableMMAP On, EnableSendfile Off +# +#EnableMMAP off +#EnableSendfile on + +# Supplemental configuration +# +# The configuration files in the conf/extra/ directory can be +# included to add extra features or to modify the default configuration of +# the server, or you may simply copy their contents here and change as +# necessary. + +# Server-pool management (MPM specific) +#Include conf/extra/httpd-mpm.conf + +# Multi-language error messages +#Include conf/extra/httpd-multilang-errordoc.conf + +# Fancy directory listings +#Include conf/extra/httpd-autoindex.conf + +# Language settings +#Include conf/extra/httpd-languages.conf + +# User home directories +#Include conf/extra/httpd-userdir.conf + +# Real-time info on requests and configuration +#Include conf/extra/httpd-info.conf + +# Virtual hosts +#Include conf/extra/httpd-vhosts.conf + +# Local access to the Apache HTTP Server Manual +#Include conf/extra/httpd-manual.conf + +# Distributed authoring and versioning (WebDAV) +#Include conf/extra/httpd-dav.conf + +# Various default settings +#Include conf/extra/httpd-default.conf + +# Configure mod_proxy_html to understand HTML4/XHTML1 + +Include conf/extra/proxy-html.conf + + +# Secure (SSL/TLS) connections +#Include conf/extra/httpd-ssl.conf +# +# Note: The following must must be present to support +# starting without SSL on platforms with no /dev/random equivalent +# but a statically compiled-in mod_ssl. +# + +SSLRandomSeed startup builtin +SSLRandomSeed connect builtin + + +Include /etc/apache2/conf-custom/apache-httpd-lab1.conf \ No newline at end of file diff --git a/httpd/static/.htaccess b/httpd/static/.htaccess new file mode 100644 index 0000000..ec27b8f --- /dev/null +++ b/httpd/static/.htaccess @@ -0,0 +1,6 @@ +Require all granted + +# Редирект /index.html на / +# Redirect 301 /index.html / +RewriteEngine On +RewriteRule ^index\.html$ / [R=301,L] \ No newline at end of file diff --git a/httpd/static/index.html b/httpd/static/index.html new file mode 100644 index 0000000..330cf34 --- /dev/null +++ b/httpd/static/index.html @@ -0,0 +1,765 @@ + + + + + + Web lab1 + + + + +
+ +
+

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

+

Группа: P3108

+

Вариант: 467233

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

Выберите X:

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

Выберете R:

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

Выберете Y:

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

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

+
+ + + + + + + + + + + + + + +
Дата и времяЗатраченное времяXYRРезультат
+
+ История пуста. Заполните форму, чтобы добавить данные. +
+
+ +
+ +
+
+
+ + + + \ No newline at end of file diff --git a/httpd/static/js/ajax.js b/httpd/static/js/ajax.js new file mode 100644 index 0000000..9975aa8 --- /dev/null +++ b/httpd/static/js/ajax.js @@ -0,0 +1,22 @@ +const sendAJAXGETRequest = (url, data, callback) => { + // encode url + const query = []; + for (const key in data) { + query.push(String(key) + '=' + String(data[key])); + } + + // creating AJAX req object + const xhr = new XMLHttpRequest(); + // enable CORS support + xhr.withCredentials = true; + + xhr.open("GET", url+(query.length ? '?' + query.join('&') : '')); + + xhr.onreadystatechange = () => { + if (xhr.readyState == 4) { // status of finished request + callback(xhr.responseText) + } + }; + + xhr.send(data) +}; \ 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/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..a5181cc --- /dev/null +++ b/server/src/main/java/org/web1/Main.java @@ -0,0 +1,39 @@ +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; +import org.web1.utils.Timer; + +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(); + Timer timer = new Timer(); + + while (fastCGI.FCGIaccept() >= 0) { + timer.start(); + + 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("elapsedTimeNs", timer.stop()) + ); + + 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..9e7c49c --- /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, + 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..c87b3a2 --- /dev/null +++ b/server/src/main/java/org/web1/utils/JsonBuilder.java @@ -0,0 +1,23 @@ +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() { + if (data.isEmpty()) return "{}"; + + StringBuilder jsonString = new StringBuilder("{\n"); + + for (String key : data.keySet()) + jsonString.append(String.format("\t\"%s\": %s,\n", key, data.get(key))); + + return jsonString.substring(0, jsonString.length() - 2) + "\n}"; + } +} 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..8032608 --- /dev/null +++ b/server/src/main/java/org/web1/utils/ResponseController.java @@ -0,0 +1,15 @@ +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"""; + public static String create(JsonBuilder jsonBuilder) { + String response = jsonBuilder.build(); + return String.format(BASE_RESPONSE, response.length(), response); + } +} diff --git a/server/src/main/java/org/web1/utils/Timer.java b/server/src/main/java/org/web1/utils/Timer.java new file mode 100644 index 0000000..48adcff --- /dev/null +++ b/server/src/main/java/org/web1/utils/Timer.java @@ -0,0 +1,11 @@ +package org.web1.utils; + +public class Timer { + long startTime; + public void start() { + this.startTime = System.nanoTime(); + } + public long stop() { + return System.nanoTime() - this.startTime; + } +}