diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000..5000259 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,20 @@ +--- +name: Bug report +about: Create a report to help us improve +title: "[BUG]" +labels: '' +assignees: '' + +--- + +**Describe the bug** +A clear and concise description of what the bug is. + +**To Reproduce** +Code sample to reproduce the behavior + +**Expected behavior** +A clear and concise description of what you expected to happen. + +**Additional context** +Add any other context about the problem here. diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 0000000..a5b62af --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,20 @@ +--- +name: Feature request +about: Suggest an idea for this project +title: "[FEAT]" +labels: '' +assignees: '' + +--- + +**Is your feature request related to a problem? Please describe.** +A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] + +**Describe the solution you'd like** +A clear and concise description of what you want to happen. + +**Describe alternatives you've considered** +A clear and concise description of any alternative solutions or features you've considered. + +**Additional context** +Add any other context or screenshots about the feature request here. diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000..6ad0d8e --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,7 @@ + All Submissions: + +* [ ] Have you checked to ensure there aren't other open [Pull Requests](../../../pulls) for the same update/change? + +### Changes to Core Features: + +* [ ] Have you added an explanation of what your changes do and why you'd like us to include them? diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..519d912 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,10 @@ +version: 2 +updates: + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "weekly" + - package-ecosystem: "gradle" + directory: "/" + schedule: + interval: "weekly" diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 0000000..33eca80 --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,49 @@ +# This workflow will build a Java project with Gradle +# For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-gradle + +name: Java CI with Gradle for general purposes + +on: + workflow_dispatch: {} + push: + branches: + - '**' + paths-ignore: + - '**.yml' + - '**.md' + - '**/gradle-wrapper.jar' + - '**/gradle-wrapper.properties' + - '**/gradlew' + - '**/gradlew.bat' + +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Setup Java + uses: actions/setup-java@v4 + with: + distribution: 'temurin' + java-version: 17 + + - name: Validate Gradle wrapper + uses: gradle/actions/wrapper-validation@v4 + + - name: Cache SonarCloud packages + uses: actions/cache@v4 + with: + path: ~/.sonar/cache + key: ${{ runner.os }}-sonar + restore-keys: ${{ runner.os }}-sonar + + - name: Cache Gradle packages + uses: actions/cache@v4 + with: + path: ~/.gradle/caches + key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle') }} + restore-keys: ${{ runner.os }}-gradle + + - name: Build with Gradle + run: ./gradlew build \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c5ebdcd --- /dev/null +++ b/.gitignore @@ -0,0 +1,33 @@ +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr +out/ + +### Eclipse ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +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/README.md b/README.md new file mode 100644 index 0000000..05c6d29 --- /dev/null +++ b/README.md @@ -0,0 +1,11 @@ +# JIQS + +Includes +- Javalin +- jOOQ +- Flyway +- Gestalt +- Inject +- Spotless + +Add Swagger (use interface to separate annotations from the actual controller) \ No newline at end of file diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..1f258ad --- /dev/null +++ b/build.gradle @@ -0,0 +1,198 @@ +import java.nio.charset.StandardCharsets + +plugins { + // https://docs.gradle.org/current/userguide/idea_plugin.html + id 'idea' + + // https://docs.gradle.org/current/userguide/java_plugin.html + id 'java' + + // https://plugins.gradle.org/plugin/io.github.suppierk.jooq-java-class-generator + id 'io.github.suppierk.jooq-java-class-generator' version "$jooqJavaClassGeneratorVersion" + + // https://plugins.gradle.org/plugin/com.diffplug.spotless + id 'com.diffplug.spotless' version "$spotlessVersion" + + // https://docs.gradle.org/current/userguide/jacoco_plugin.html + id 'jacoco' + + // https://plugins.gradle.org/plugin/com.google.cloud.tools.jib + id 'com.google.cloud.tools.jib' version "$jibVersion" +} + +repositories { + mavenCentral() +} + +dependencies { + // =============================== + // ===== COMMON DEPENDENCIES ===== + // =============================== + + // https://mvnrepository.com/artifact/io.javalin/javalin-bundle + implementation group: 'io.javalin', name: 'javalin-bundle', version: javalinVersion + + // https://mvnrepository.com/artifact/io.javalin.community.openapi/javalin-openapi-plugin + implementation group: 'io.javalin.community.openapi', name: 'javalin-openapi-plugin', version: javalinVersion + + // https://mvnrepository.com/artifact/io.javalin.community.openapi/openapi-annotation-processor + annotationProcessor group: 'io.javalin.community.openapi', name: 'openapi-annotation-processor', version: javalinVersion + + // https://mvnrepository.com/artifact/io.javalin.community.openapi/javalin-swagger-plugin + implementation group: 'io.javalin.community.openapi', name: 'javalin-swagger-plugin', version: javalinVersion + + // https://mvnrepository.com/artifact/io.github.suppierk/inject + implementation group: 'io.github.suppierk', name: 'inject', version: injectVersion + + // https://mvnrepository.com/artifact/com.github.gestalt-config/gestalt-core + implementation group: 'com.github.gestalt-config', name: 'gestalt-core', version: gestaltVersion + + // https://mvnrepository.com/artifact/com.zaxxer/HikariCP + implementation group: 'com.zaxxer', name: 'HikariCP', version: hikariVersion + + // https://mvnrepository.com/artifact/org.jooq/jooq + implementation group: 'org.jooq', name: 'jooq', version: jooqVersion + + // https://mvnrepository.com/artifact/org.flywaydb/flyway-core + implementation group: 'org.flywaydb', name: 'flyway-core', version: flywayVersion + + // ===================================== + // ===== PREFERENTIAL DEPENDENCIES ===== + // ===================================== + + // https://mvnrepository.com/artifact/com.github.gestalt-config/gestalt-yaml + implementation group: 'com.github.gestalt-config', name: 'gestalt-yaml', version: gestaltVersion + + // https://mvnrepository.com/artifact/org.flywaydb/flyway-database-postgresql + implementation group: 'org.flywaydb', name: 'flyway-database-postgresql', version: flywayVersion + + // https://mvnrepository.com/artifact/org.postgresql/postgresql + implementation group: 'org.postgresql', name: 'postgresql', version: postgresVersion + + // https://mvnrepository.com/artifact/org.postgresql/postgresql + jooqGenerator group: 'org.postgresql', name: 'postgresql', version: postgresVersion + + // https://mvnrepository.com/artifact/com.github.f4b6a3/uuid-creator + implementation group: 'com.github.f4b6a3', name: 'uuid-creator', version: uuidCreatorVersion + + // ============================= + // ===== TEST DEPENDENCIES ===== + // ============================= + + // https://mvnrepository.com/artifact/org.junit/junit-bom + testImplementation platform(group: 'org.junit', name: 'junit-bom', version: junitVersion) + + // https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter + testImplementation group: 'org.junit.jupiter', name: 'junit-jupiter' + + // ========================================== + // ===== PREFERENTIAL TEST DEPENDENCIES ===== + // ========================================== + + // https://mvnrepository.com/artifact/org.testcontainers/postgresql + testImplementation group: 'org.testcontainers', name: 'postgresql', version: testcontainersVersion + + // https://mvnrepository.com/artifact/nl.jqno.equalsverifier/equalsverifier-nodep + testImplementation group: 'nl.jqno.equalsverifier', name: 'equalsverifier-nodep', version: equalsVerifierVersion +} + +// Setup Flyway database migration +// https://documentation.red-gate.com/fd/gradle-task-184127407.html +flyway { + driver = databaseDriverClassName +} + +// Setup jOOQ code generation +// https://github.com/etiennestuder/gradle-jooq-plugin?tab=readme-ov-file#configuring-the-jooq-generation-tool +jooq { + version = jooqVersion + + configurations { + main { + generationTool { + logging = org.jooq.meta.jaxb.Logging.WARN + + generator { + database { + name = databaseJooqGeneratorClassName + } + + generate { + fluentSetters = true + } + + target { + packageName = databaseJooqGeneratedClassesPackageName + } + } + } + } + } +} + +java { + sourceCompatibility = javaVersion + targetCompatibility = javaVersion + + toolchain { + languageVersion = JavaLanguageVersion.of(javaVersion) + } +} + +// Enable Spotless code formatting rules +// https://github.com/diffplug/spotless/tree/main/plugin-gradle +spotless { + java { + target '**/*.java' + + // Aligns with Intellij IDEA default settings + toggleOffOn('@formatter:off', '@formatter:on') + + googleJavaFormat() + } + + groovyGradle { + target '**/*.gradle' + + greclipse() + } +} + +test { + dependsOn spotlessCheck + finalizedBy jacocoTestReport + + useJUnitPlatform() +} + +jacocoTestReport { + // Tests are required to run before generating the report + dependsOn test + + reports { + html.required = true + xml.required = true + csv.required = false + } + + afterEvaluate { + classDirectories.setFrom(files(classDirectories.files.collect { + fileTree(dir: it, exclude: "${databaseJooqGeneratedClassesPackageName.replace('.', '/')}/**") + })) + } +} + +jib { + from { + image = "eclipse-temurin:$javaVersion-alpine" + } +} + +// Configure several tasks additionally for Gradle +tasks.withType(Copy).configureEach { + duplicatesStrategy = DuplicatesStrategy.INCLUDE +} + +tasks.withType(JavaCompile).configureEach { + options.encoding = StandardCharsets.UTF_8.name() +} \ No newline at end of file diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..2371cdf --- /dev/null +++ b/gradle.properties @@ -0,0 +1,33 @@ +# Project properties +group=io.github.suppierk +version=1.0-SNAPSHOT +javaVersion=17 + +# Database properties +databaseDriverClassName=org.postgresql.Driver +databaseJooqGeneratorClassName=org.jooq.meta.postgres.PostgresDatabase +databaseJooqGeneratedClassesPackageName=io.github.suppierk.jiqs.db + +# Plugin dependency properties +jooqJavaClassGeneratorVersion=1.0.1 +spotlessVersion=6.25.0 +jibVersion=3.3.2 + +# Common dependency properties +javalinVersion=6.4.0 +injectVersion=1.1.0 +gestaltVersion=0.35.1 +hikariVersion=6.2.1 +jooqVersion=3.19.16 +flywayVersion=11.1.0 + +# Preferential dependency properties +postgresVersion=42.7.4 +uuidCreatorVersion=6.0.0 + +# Test dependencies properties +junitVersion=5.11.4 + +# Preferential test dependencies properties +testcontainersVersion=1.20.4 +equalsVerifierVersion=3.17.5 \ 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..a4b76b9 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..e0fd020 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.12-all.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..f5feea6 --- /dev/null +++ b/gradlew @@ -0,0 +1,252 @@ +#!/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. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# 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/HEAD/platforms/jvm/plugins-application/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 + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s +' "$PWD" ) || exit + +# 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 + if ! command -v java >/dev/null 2>&1 + then + 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 +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + 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 + + +# 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"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# 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..9d21a21 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,94 @@ +@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 +@rem SPDX-License-Identifier: Apache-2.0 +@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=. +@rem This is normally unused +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% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +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% equ 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! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..c0e3baf --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'jiqs' \ No newline at end of file diff --git a/src/main/java/io/github/suppierk/jiqs/Application.java b/src/main/java/io/github/suppierk/jiqs/Application.java new file mode 100644 index 0000000..0f3f77e --- /dev/null +++ b/src/main/java/io/github/suppierk/jiqs/Application.java @@ -0,0 +1,38 @@ +package io.github.suppierk.jiqs; + +import io.github.suppierk.inject.Injector; +import io.github.suppierk.jiqs.configuration.ConfigurationProvider; +import io.github.suppierk.jiqs.configuration.GestaltProvider; +import io.github.suppierk.jiqs.configuration.JavalinProvider; +import io.github.suppierk.jiqs.configuration.JooqProvider; +import io.github.suppierk.jiqs.configuration.values.ServerPort; +import io.github.suppierk.jiqs.endpoints.HealthcheckEndpointGroup; +import io.github.suppierk.jiqs.endpoints.UsersEndpointGroup; +import io.github.suppierk.jiqs.services.UsersService; +import io.javalin.Javalin; + +public final class Application { + final Injector injector; + + public Application() { + this.injector = + Injector.injector() + .add(GestaltProvider.class, ConfigurationProvider.class) + .add(JooqProvider.class) + .add(JavalinProvider.class) + .add(HealthcheckEndpointGroup.class) + .add(UsersEndpointGroup.class, UsersService.class) + .build(); + } + + public static void main(String[] args) { + final var app = new Application(); + final var javalin = app.injector.get(Javalin.class); + + // Add shutdown hook for graceful shutdown + Runtime.getRuntime().addShutdownHook(new Thread(app.injector::close)); + + // Start the web server + javalin.start(app.injector.get(ServerPort.class).get()); + } +} diff --git a/src/main/java/io/github/suppierk/jiqs/configuration/ConfigurationProvider.java b/src/main/java/io/github/suppierk/jiqs/configuration/ConfigurationProvider.java new file mode 100644 index 0000000..52d1e8c --- /dev/null +++ b/src/main/java/io/github/suppierk/jiqs/configuration/ConfigurationProvider.java @@ -0,0 +1,43 @@ +package io.github.suppierk.jiqs.configuration; + +import com.zaxxer.hikari.HikariConfig; +import com.zaxxer.hikari.HikariDataSource; +import io.github.suppierk.inject.Provides; +import io.github.suppierk.jiqs.configuration.values.ServerPort; +import jakarta.inject.Inject; +import jakarta.inject.Singleton; +import org.flywaydb.core.Flyway; +import org.github.gestalt.config.Gestalt; +import org.github.gestalt.config.exceptions.GestaltException; + +@Singleton +public class ConfigurationProvider { + private final Gestalt gestalt; + + @Inject + public ConfigurationProvider(Gestalt gestalt) { + this.gestalt = gestalt; + } + + @Provides + @Singleton + public ServerPort serverPort() throws GestaltException { + return new ServerPort(gestalt.getConfig("server.port", Integer.class)); + } + + @Provides + @Singleton + public HikariDataSource dataSource() throws GestaltException { + final var config = new HikariConfig(); + config.setDriverClassName(org.postgresql.Driver.class.getName()); + config.setJdbcUrl(gestalt.getConfig("database.url", String.class)); + config.setUsername(gestalt.getConfig("database.username", String.class)); + config.setPassword(gestalt.getConfig("database.password", String.class)); + final var dataSource = new HikariDataSource(config); + + // Apply database migration + Flyway.configure().dataSource(dataSource).load().migrate(); + + return dataSource; + } +} diff --git a/src/main/java/io/github/suppierk/jiqs/configuration/GestaltProvider.java b/src/main/java/io/github/suppierk/jiqs/configuration/GestaltProvider.java new file mode 100644 index 0000000..29691a9 --- /dev/null +++ b/src/main/java/io/github/suppierk/jiqs/configuration/GestaltProvider.java @@ -0,0 +1,25 @@ +package io.github.suppierk.jiqs.configuration; + +import io.github.suppierk.inject.Provides; +import jakarta.inject.Singleton; +import org.github.gestalt.config.Gestalt; +import org.github.gestalt.config.builder.GestaltBuilder; +import org.github.gestalt.config.exceptions.GestaltException; +import org.github.gestalt.config.source.ClassPathConfigSourceBuilder; + +@Singleton +public class GestaltProvider { + @Provides + @Singleton + public Gestalt gestalt() throws GestaltException { + final var config = + new GestaltBuilder() + .addSource( + ClassPathConfigSourceBuilder.builder().setResource("application.yml").build()) + .build(); + + config.loadConfigs(); + + return config; + } +} diff --git a/src/main/java/io/github/suppierk/jiqs/configuration/JavalinProvider.java b/src/main/java/io/github/suppierk/jiqs/configuration/JavalinProvider.java new file mode 100644 index 0000000..67198b0 --- /dev/null +++ b/src/main/java/io/github/suppierk/jiqs/configuration/JavalinProvider.java @@ -0,0 +1,61 @@ +package io.github.suppierk.jiqs.configuration; + +import io.github.suppierk.inject.Provides; +import io.github.suppierk.jiqs.endpoints.HealthcheckEndpointGroup; +import io.github.suppierk.jiqs.endpoints.UsersEndpointGroup; +import io.javalin.Javalin; +import io.javalin.openapi.plugin.OpenApiPlugin; +import io.javalin.openapi.plugin.swagger.SwaggerPlugin; +import jakarta.inject.Inject; +import jakarta.inject.Singleton; + +@Singleton +public class JavalinProvider implements AutoCloseable { + private final HealthcheckEndpointGroup healthcheckEndpointGroup; + private final UsersEndpointGroup usersEndpointGroup; + + private final Javalin javalin; + + @Inject + public JavalinProvider( + HealthcheckEndpointGroup healthcheckEndpointGroup, UsersEndpointGroup usersEndpointGroup) { + this.healthcheckEndpointGroup = healthcheckEndpointGroup; + this.usersEndpointGroup = usersEndpointGroup; + + this.javalin = initializeJavalin(); + } + + @Provides + @Singleton + public Javalin javalin() { + return javalin; + } + + @Override + public void close() { + javalin.stop(); + } + + private Javalin initializeJavalin() { + return Javalin.create( + config -> { + // Disable banner in logs + config.showJavalinBanner = false; + + // Registering OpenAPI + config.registerPlugin(new SwaggerPlugin()); + config.registerPlugin( + new OpenApiPlugin( + pluginConfig -> + pluginConfig.withDefinitionConfiguration( + (version, definition) -> + definition.withInfo(info -> info.setTitle("JIQS stack example"))))); + + // Registering common endpoints + config.router.apiBuilder(healthcheckEndpointGroup); + + // Registering business endpoints + config.router.apiBuilder(usersEndpointGroup); + }); + } +} diff --git a/src/main/java/io/github/suppierk/jiqs/configuration/JooqProvider.java b/src/main/java/io/github/suppierk/jiqs/configuration/JooqProvider.java new file mode 100644 index 0000000..38ea174 --- /dev/null +++ b/src/main/java/io/github/suppierk/jiqs/configuration/JooqProvider.java @@ -0,0 +1,25 @@ +package io.github.suppierk.jiqs.configuration; + +import com.zaxxer.hikari.HikariDataSource; +import io.github.suppierk.inject.Provides; +import jakarta.inject.Inject; +import jakarta.inject.Singleton; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; + +@Singleton +public class JooqProvider { + private final HikariDataSource dataSource; + + @Inject + public JooqProvider(HikariDataSource dataSource) { + this.dataSource = dataSource; + } + + @Provides + @Singleton + public DSLContext dsl() { + return DSL.using(dataSource, SQLDialect.POSTGRES); + } +} diff --git a/src/main/java/io/github/suppierk/jiqs/configuration/values/ServerPort.java b/src/main/java/io/github/suppierk/jiqs/configuration/values/ServerPort.java new file mode 100644 index 0000000..8f9f601 --- /dev/null +++ b/src/main/java/io/github/suppierk/jiqs/configuration/values/ServerPort.java @@ -0,0 +1,38 @@ +package io.github.suppierk.jiqs.configuration.values; + +import java.util.Objects; +import java.util.StringJoiner; + +public final class ServerPort { + private final int port; + + public ServerPort(Integer port) { + if (port == null) { + throw new IllegalStateException("Server port must not be null"); + } + + this.port = port; + } + + public int get() { + return port; + } + + @Override + public boolean equals(Object o) { + if (!(o instanceof ServerPort that)) return false; + return port == that.port; + } + + @Override + public int hashCode() { + return Objects.hashCode(port); + } + + @Override + public String toString() { + return new StringJoiner(", ", ServerPort.class.getSimpleName() + "[", "]") + .add(Integer.toString(port)) + .toString(); + } +} diff --git a/src/main/java/io/github/suppierk/jiqs/endpoints/HealthcheckEndpointGroup.java b/src/main/java/io/github/suppierk/jiqs/endpoints/HealthcheckEndpointGroup.java new file mode 100644 index 0000000..cda9307 --- /dev/null +++ b/src/main/java/io/github/suppierk/jiqs/endpoints/HealthcheckEndpointGroup.java @@ -0,0 +1,14 @@ +package io.github.suppierk.jiqs.endpoints; + +import static io.javalin.apibuilder.ApiBuilder.get; + +import io.javalin.apibuilder.EndpointGroup; +import jakarta.inject.Singleton; + +@Singleton +public class HealthcheckEndpointGroup implements EndpointGroup { + @Override + public void addEndpoints() { + get("/api/health", ctx -> ctx.result("OK")); + } +} diff --git a/src/main/java/io/github/suppierk/jiqs/endpoints/UsersEndpointGroup.java b/src/main/java/io/github/suppierk/jiqs/endpoints/UsersEndpointGroup.java new file mode 100644 index 0000000..f8208e5 --- /dev/null +++ b/src/main/java/io/github/suppierk/jiqs/endpoints/UsersEndpointGroup.java @@ -0,0 +1,178 @@ +package io.github.suppierk.jiqs.endpoints; + +import static io.javalin.apibuilder.ApiBuilder.crud; + +import com.github.f4b6a3.uuid.UuidCreator; +import com.github.f4b6a3.uuid.util.UuidValidator; +import io.github.suppierk.jiqs.models.requests.UserRequest; +import io.github.suppierk.jiqs.models.responses.UserResponse; +import io.github.suppierk.jiqs.services.UsersService; +import io.javalin.apibuilder.CrudHandler; +import io.javalin.apibuilder.EndpointGroup; +import io.javalin.http.BadRequestResponse; +import io.javalin.http.Context; +import io.javalin.http.HttpStatus; +import io.javalin.http.NotFoundResponse; +import io.javalin.openapi.HttpMethod; +import io.javalin.openapi.OpenApi; +import io.javalin.openapi.OpenApiContent; +import io.javalin.openapi.OpenApiParam; +import io.javalin.openapi.OpenApiRequestBody; +import io.javalin.openapi.OpenApiResponse; +import jakarta.inject.Inject; +import jakarta.inject.Singleton; +import java.util.Map; +import java.util.UUID; + +@Singleton +public class UsersEndpointGroup implements EndpointGroup, CrudHandler { + private static final String USER_ID = "userId"; + private static final String PLURAL_USERS_ENDPOINT = "/api/users"; + private static final String SINGULAR_USER_ENDPOINT = "/api/users/{userId}"; + + private final UsersService service; + + @Inject + public UsersEndpointGroup(UsersService service) { + this.service = service; + } + + @Override + public void addEndpoints() { + crud(SINGULAR_USER_ENDPOINT, this); + } + + @Override + @OpenApi( + summary = "Create new user", + operationId = "createUser", + path = PLURAL_USERS_ENDPOINT, + methods = HttpMethod.POST, + tags = {"User"}, + requestBody = @OpenApiRequestBody(content = {@OpenApiContent(from = UserRequest.class)}), + responses = { + @OpenApiResponse(status = "200", content = @OpenApiContent(from = UserResponse.class)) + }) + public void create(Context context) { + final var request = context.bodyValidator(UserRequest.class).get(); + final var response = service.create(request); + context.json(response); + } + + @Override + @OpenApi( + summary = "Get all users", + operationId = "getUsers", + path = PLURAL_USERS_ENDPOINT, + methods = HttpMethod.GET, + tags = {"User"}, + responses = { + @OpenApiResponse(status = "200", content = @OpenApiContent(from = UserResponse[].class)) + }) + public void getAll(Context context) { + context.json(service.getAll()); + } + + @Override + @OpenApi( + summary = "Get user by ID", + operationId = "getUserById", + path = SINGULAR_USER_ENDPOINT, + methods = HttpMethod.PATCH, + pathParams = { + @OpenApiParam( + name = USER_ID, + type = UUID.class, + description = "The user ID", + required = true) + }, + tags = {"User"}, + responses = { + @OpenApiResponse(status = "200", content = @OpenApiContent(from = UserResponse.class)), + @OpenApiResponse(status = "400"), + @OpenApiResponse(status = "404") + }) + public void getOne(Context context, String resourceId) { + if (!UuidValidator.isValid(resourceId)) { + throw new BadRequestResponse( + HttpStatus.BAD_REQUEST.getMessage(), Map.of(USER_ID, resourceId)); + } + + final var userId = UuidCreator.fromString(resourceId); + final var response = + service + .getOne(userId) + .orElseThrow( + () -> + new NotFoundResponse( + HttpStatus.NOT_FOUND.getMessage(), Map.of(USER_ID, userId.toString()))); + context.json(response); + } + + @Override + @OpenApi( + summary = "Update user by ID", + operationId = "updateUserById", + path = SINGULAR_USER_ENDPOINT, + methods = HttpMethod.PATCH, + pathParams = { + @OpenApiParam( + name = USER_ID, + type = UUID.class, + description = "The user ID", + required = true) + }, + tags = {"User"}, + requestBody = @OpenApiRequestBody(content = {@OpenApiContent(from = UserRequest.class)}), + responses = { + @OpenApiResponse(status = "204", content = @OpenApiContent(from = UserResponse.class)), + @OpenApiResponse(status = "400"), + @OpenApiResponse(status = "404") + }) + public void update(Context context, String resourceId) { + if (!UuidValidator.isValid(resourceId)) { + throw new BadRequestResponse( + HttpStatus.BAD_REQUEST.getMessage(), Map.of(USER_ID, resourceId)); + } + + final var userId = UuidCreator.fromString(resourceId); + final var request = context.bodyValidator(UserRequest.class).get(); + final var response = + service + .update(userId, request) + .orElseThrow( + () -> + new NotFoundResponse( + HttpStatus.NOT_FOUND.getMessage(), Map.of(USER_ID, userId.toString()))); + context.json(response); + } + + @Override + @OpenApi( + summary = "Delete user by ID", + operationId = "deleteUserById", + path = SINGULAR_USER_ENDPOINT, + methods = HttpMethod.DELETE, + pathParams = { + @OpenApiParam( + name = USER_ID, + type = UUID.class, + description = "The user ID", + required = true) + }, + tags = {"User"}, + responses = { + @OpenApiResponse(status = "204"), + @OpenApiResponse(status = "400"), + }) + public void delete(Context context, String resourceId) { + if (!UuidValidator.isValid(resourceId)) { + throw new BadRequestResponse( + HttpStatus.BAD_REQUEST.getMessage(), Map.of(USER_ID, resourceId)); + } + + final var userId = UuidCreator.fromString(resourceId); + service.delete(userId); + context.status(HttpStatus.NO_CONTENT); + } +} diff --git a/src/main/java/io/github/suppierk/jiqs/models/requests/UserRequest.java b/src/main/java/io/github/suppierk/jiqs/models/requests/UserRequest.java new file mode 100644 index 0000000..d72ccf3 --- /dev/null +++ b/src/main/java/io/github/suppierk/jiqs/models/requests/UserRequest.java @@ -0,0 +1,25 @@ +package io.github.suppierk.jiqs.models.requests; + +import java.util.Arrays; +import java.util.Objects; +import java.util.StringJoiner; + +public record UserRequest(String username, char[] password) { + @Override + public boolean equals(Object o) { + if (!(o instanceof UserRequest that)) return false; + return Objects.equals(username, that.username) && Objects.deepEquals(password, that.password); + } + + @Override + public int hashCode() { + return Objects.hash(username, Arrays.hashCode(password)); + } + + @Override + public String toString() { + return new StringJoiner(", ", UserRequest.class.getSimpleName() + "[", "]") + .add("username='" + username + "'") + .toString(); + } +} diff --git a/src/main/java/io/github/suppierk/jiqs/models/responses/UserResponse.java b/src/main/java/io/github/suppierk/jiqs/models/responses/UserResponse.java new file mode 100644 index 0000000..fbf7d96 --- /dev/null +++ b/src/main/java/io/github/suppierk/jiqs/models/responses/UserResponse.java @@ -0,0 +1,10 @@ +package io.github.suppierk.jiqs.models.responses; + +import io.github.suppierk.jiqs.db.tables.records.UsersRecord; +import java.util.UUID; + +public record UserResponse(UUID id, String username) { + public UserResponse(UsersRecord databaseRecord) { + this(databaseRecord.getId(), databaseRecord.getName()); + } +} diff --git a/src/main/java/io/github/suppierk/jiqs/services/UsersService.java b/src/main/java/io/github/suppierk/jiqs/services/UsersService.java new file mode 100644 index 0000000..519d2a2 --- /dev/null +++ b/src/main/java/io/github/suppierk/jiqs/services/UsersService.java @@ -0,0 +1,68 @@ +package io.github.suppierk.jiqs.services; + +import static io.github.suppierk.jiqs.db.Tables.USERS; + +import com.github.f4b6a3.uuid.UuidCreator; +import io.github.suppierk.jiqs.models.requests.UserRequest; +import io.github.suppierk.jiqs.models.responses.UserResponse; +import jakarta.inject.Inject; +import jakarta.inject.Singleton; +import java.time.OffsetDateTime; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import org.jooq.DSLContext; + +@Singleton +public class UsersService { + private final DSLContext dsl; + + @Inject + public UsersService(DSLContext dsl) { + this.dsl = dsl; + } + + @SuppressWarnings("squid:S2129") + public UserResponse create(UserRequest userRequest) { + final var newRecord = dsl.newRecord(USERS); + newRecord.setId(UuidCreator.getTimeOrderedEpoch()); + newRecord.setCreatedAt(OffsetDateTime.now()); + newRecord.setName(userRequest.username()); + newRecord.setPassword(new String(userRequest.password())); + newRecord.insert(); + + return new UserResponse(newRecord); + } + + public List getAll() { + return dsl.selectFrom(USERS).fetchStream().map(UserResponse::new).toList(); + } + + public Optional getOne(UUID userId) { + return dsl.selectFrom(USERS).where(USERS.ID.eq(userId)).fetchOptional().map(UserResponse::new); + } + + @SuppressWarnings("squid:S2129") + public Optional update(UUID userId, UserRequest userRequest) { + return dsl.selectFrom(USERS) + .where(USERS.ID.eq(userId)) + .fetchOptional() + .map( + databaseRecord -> { + if (userRequest.username() != null) { + databaseRecord.setName(userRequest.username()); + } + + if (userRequest.password() != null) { + databaseRecord.setPassword(new String(userRequest.password())); + } + + databaseRecord.update(); + return new UserResponse(databaseRecord); + }); + } + + public void delete(UUID userId) { + dsl.deleteFrom(USERS).where(USERS.ID.eq(userId)).execute(); + } +} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml new file mode 100644 index 0000000..87d9d56 --- /dev/null +++ b/src/main/resources/application.yml @@ -0,0 +1,7 @@ +server: + port: ${PORT:=8080} + +database: + url: jdbc:postgresql://${DB_HOST}:${DB_PORT:=5432}/${DB_DATABASE}?loggerLevel=OFF + username: ${DB_USERNAME} + password: ${DB_PASSWORD} \ No newline at end of file diff --git a/src/main/resources/db/migration/V001__users_table.sql b/src/main/resources/db/migration/V001__users_table.sql new file mode 100644 index 0000000..0acf232 --- /dev/null +++ b/src/main/resources/db/migration/V001__users_table.sql @@ -0,0 +1,8 @@ +CREATE TABLE users +( + -- Tip: check out https://uuid7.com + id UUID PRIMARY KEY, + created_at TIMESTAMP WITH TIME ZONE NOT NULL, + name VARCHAR(128) NOT NULL, + password VARCHAR(128) NOT NULL +); \ No newline at end of file diff --git a/src/main/resources/logback.xml b/src/main/resources/logback.xml new file mode 100644 index 0000000..5eb2972 --- /dev/null +++ b/src/main/resources/logback.xml @@ -0,0 +1,28 @@ + + + + + %d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/test/java/io/github/suppierk/jiqs/ApplicationTest.java b/src/test/java/io/github/suppierk/jiqs/ApplicationTest.java new file mode 100644 index 0000000..b779e32 --- /dev/null +++ b/src/test/java/io/github/suppierk/jiqs/ApplicationTest.java @@ -0,0 +1,514 @@ +package io.github.suppierk.jiqs; + +import static io.github.suppierk.jiqs.db.Tables.USERS; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.fasterxml.jackson.databind.ObjectMapper; +import io.github.suppierk.inject.Injector; +import io.github.suppierk.jiqs.configuration.GestaltProvider; +import io.github.suppierk.jiqs.models.requests.UserRequest; +import io.github.suppierk.jiqs.models.responses.UserResponse; +import io.github.suppierk.test.AbstractDatabaseTest; +import io.javalin.Javalin; +import io.javalin.http.HttpStatus; +import io.javalin.testtools.JavalinTest; +import jakarta.inject.Singleton; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; +import org.github.gestalt.config.Gestalt; +import org.github.gestalt.config.builder.GestaltBuilder; +import org.github.gestalt.config.exceptions.GestaltException; +import org.github.gestalt.config.source.ConfigSourcePackage; +import org.github.gestalt.config.source.MapConfigSourceBuilder; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; +import org.testcontainers.shaded.org.apache.commons.lang3.RandomStringUtils; + +class ApplicationTest extends AbstractDatabaseTest { + @Singleton + static class TestGestaltProvider extends GestaltProvider { + @Override + public Gestalt gestalt() throws GestaltException { + final ConfigSourcePackage configSourcePackage = + MapConfigSourceBuilder.builder() + .addCustomConfig("database.url", getJdbcUrl()) + .addCustomConfig("database.username", getUsername()) + .addCustomConfig("database.password", getPassword()) + .build(); + + final Gestalt gestalt = new GestaltBuilder().addSource(configSourcePackage).build(); + gestalt.loadConfigs(); + return gestalt; + } + } + + static final ObjectMapper MAPPER = new ObjectMapper(); + + Injector injector; + Javalin javalin; + + @BeforeEach + void setUp() { + injector = + new Application() + .injector + .copy() + .replace(GestaltProvider.class, TestGestaltProvider.class) + .build(); + + javalin = injector.get(Javalin.class); + } + + @AfterEach + void tearDown() { + testDsl().truncate(USERS).execute(); + + injector.close(); + + assertTrue(javalin.jettyServer().server().isStopped()); + } + + @Nested + class CommonEndpoints { + @Test + void must_have_healthcheck_endpoint() { + JavalinTest.test( + javalin, + (server, client) -> { + try (final var healthcheckResponse = client.get("/api/health")) { + assertEquals( + HttpStatus.OK.getCode(), healthcheckResponse.code(), "Response code is not OK"); + assertEquals( + "OK", + healthcheckResponse.body().string(), + "Response body is not text saying 'OK'"); + } + }); + } + + @Test + void must_have_openapi_endpoint() { + JavalinTest.test( + javalin, + (server, client) -> { + try (final var metricsResponse = client.get("/openapi?v=default")) { + assertEquals( + HttpStatus.OK.getCode(), metricsResponse.code(), "Response code is not OK"); + + final var responseBody = metricsResponse.body().string(); + + assertNotNull(responseBody, "Response body is null"); + assertFalse(responseBody.isBlank(), "Response body is blank"); + } + + try (final var metricsResponse = client.get("/swagger")) { + assertEquals( + HttpStatus.OK.getCode(), metricsResponse.code(), "Response code is not OK"); + + final var responseBody = metricsResponse.body().string(); + + assertNotNull(responseBody, "Response body is null"); + assertFalse(responseBody.isBlank(), "Response body is blank"); + } + }); + } + } + + @Nested + class UsersEndpoints { + @Test + void when_create_user_request_is_not_correct_then_400_is_returned() { + JavalinTest.test( + javalin, + (server, client) -> { + try (final var invalidJsonResponse = client.post("/api/users", "bad request")) { + assertEquals( + HttpStatus.BAD_REQUEST.getCode(), + invalidJsonResponse.code(), + "Response code is not Bad Request"); + } + }); + } + + @Test + void when_create_user_request_is_correct_then_new_entity_is_created() { + JavalinTest.test( + javalin, + (server, client) -> { + final var request = + new UserRequest( + RandomStringUtils.randomAlphanumeric(16), + RandomStringUtils.randomAlphanumeric(16).toCharArray()); + + try (final var response = client.post("/api/users", request)) { + assertEquals(HttpStatus.OK.getCode(), response.code(), "Response code is not OK"); + + final var responseBody = response.body(); + assertNotNull(responseBody, "Response body is null"); + + // Check the response + final var parsedResponse = + assertDoesNotThrow( + () -> MAPPER.readValue(responseBody.bytes(), UserResponse.class)); + assertEquals( + request.username(), + parsedResponse.username(), + "Response username is not correct"); + + // Check the database + final var optionalRecord = + testDsl() + .selectFrom(USERS) + .where(USERS.ID.eq(parsedResponse.id())) + .fetchOptional(); + assertTrue(optionalRecord.isPresent(), "New database record must be created"); + + final var databaseRecord = optionalRecord.get(); + assertEquals( + request.username(), databaseRecord.getName(), "Database username is not correct"); + assertArrayEquals( + request.password(), + databaseRecord.getPassword().toCharArray(), + "Database password is not correct"); + } + }); + } + + @Test + void when_all_users_requested_then_result_is_returned() { + JavalinTest.test( + javalin, + (server, client) -> { + try (final var response = client.get("/api/users")) { + assertEquals(HttpStatus.OK.getCode(), response.code(), "Response code is not OK"); + + final var responseBody = response.body(); + assertNotNull(responseBody, "Response body is null"); + + final var parsedResponse = + assertDoesNotThrow( + () -> MAPPER.readValue(responseBody.bytes(), UserResponse[].class)); + assertEquals(0, parsedResponse.length, "Response body should be empty"); + } + }); + } + + @Test + void when_user_requested_with_incorrect_id_then_400_is_returned() { + JavalinTest.test( + javalin, + (server, client) -> { + try (final var response = client.get("/api/users/invalidUuid")) { + assertEquals( + HttpStatus.BAD_REQUEST.getCode(), + response.code(), + "Response code is not Bad Request"); + } + }); + } + + @Test + void when_missing_user_requested_then_404_is_returned() { + JavalinTest.test( + javalin, + (server, client) -> { + try (final var response = client.get("/api/users/" + UUID.randomUUID())) { + assertEquals( + HttpStatus.NOT_FOUND.getCode(), + response.code(), + "Response code is not Not Found"); + } + }); + } + + @Test + void when_existing_user_requested_then_it_is_returned() { + JavalinTest.test( + javalin, + (server, client) -> { + final var request = + new UserRequest( + RandomStringUtils.randomAlphanumeric(16), + RandomStringUtils.randomAlphanumeric(16).toCharArray()); + + final var userId = new AtomicReference(null); + + try (final var response = client.post("/api/users", request)) { + assertEquals(HttpStatus.OK.getCode(), response.code(), "Response code is not OK"); + + final var responseBody = response.body(); + assertNotNull(responseBody, "Response body is null"); + + // Check the response + final var parsedResponse = + assertDoesNotThrow( + () -> MAPPER.readValue(responseBody.bytes(), UserResponse.class)); + userId.set(parsedResponse.id()); + } + + try (final var response = client.get("/api/users/" + userId.get())) { + assertEquals(HttpStatus.OK.getCode(), response.code(), "Response code is not OK"); + + final var responseBody = response.body(); + assertNotNull(responseBody, "Response body is null"); + + // Check the response + final var parsedResponse = + assertDoesNotThrow( + () -> MAPPER.readValue(responseBody.bytes(), UserResponse.class)); + assertEquals(userId.get(), parsedResponse.id(), "IDs do not match"); + assertEquals( + request.username(), parsedResponse.username(), "Username is not correct"); + } + }); + } + + @Test + void when_user_update_requested_with_incorrect_id_then_400_is_returned() { + JavalinTest.test( + javalin, + (server, client) -> { + try (final var response = client.patch("/api/users/invalidUuid")) { + assertEquals( + HttpStatus.BAD_REQUEST.getCode(), + response.code(), + "Response code is not Bad Request"); + } + }); + } + + @Test + void when_missing_user_update_requested_then_400_is_returned() { + JavalinTest.test( + javalin, + (server, client) -> { + final var request = + new UserRequest( + RandomStringUtils.randomAlphanumeric(16), + RandomStringUtils.randomAlphanumeric(16).toCharArray()); + + try (final var response = client.patch("/api/users/" + UUID.randomUUID(), request)) { + assertEquals( + HttpStatus.NOT_FOUND.getCode(), + response.code(), + "Response code is not Not Found"); + } + }); + } + + @Test + void when_existing_user_update_requested_with_invalid_body_then_it_is_returned() { + JavalinTest.test( + javalin, + (server, client) -> { + final var request = + new UserRequest( + RandomStringUtils.randomAlphanumeric(16), + RandomStringUtils.randomAlphanumeric(16).toCharArray()); + + final var userId = new AtomicReference(null); + + try (final var response = client.post("/api/users", request)) { + assertEquals(HttpStatus.OK.getCode(), response.code(), "Response code is not OK"); + + final var responseBody = response.body(); + assertNotNull(responseBody, "Response body is null"); + + // Check the response + final var parsedResponse = + assertDoesNotThrow( + () -> MAPPER.readValue(responseBody.bytes(), UserResponse.class)); + userId.set(parsedResponse.id()); + } + + try (final var response = client.patch("/api/users/" + userId.get(), "bad request")) { + assertEquals( + HttpStatus.BAD_REQUEST.getCode(), + response.code(), + "Response code is not Bad Request"); + } + }); + } + + @Test + void when_existing_user_update_requested_with_empty_body_then_nothing_changes() { + JavalinTest.test( + javalin, + (server, client) -> { + final var request = + new UserRequest( + RandomStringUtils.randomAlphanumeric(16), + RandomStringUtils.randomAlphanumeric(16).toCharArray()); + + final var userId = new AtomicReference(null); + + try (final var response = client.post("/api/users", request)) { + assertEquals(HttpStatus.OK.getCode(), response.code(), "Response code is not OK"); + + final var responseBody = response.body(); + assertNotNull(responseBody, "Response body is null"); + + // Check the response + final var parsedResponse = + assertDoesNotThrow( + () -> MAPPER.readValue(responseBody.bytes(), UserResponse.class)); + userId.set(parsedResponse.id()); + } + + try (final var response = client.patch("/api/users/" + userId.get(), "{}")) { + assertEquals(HttpStatus.OK.getCode(), response.code(), "Response code is not OK"); + + final var responseBody = response.body(); + assertNotNull(responseBody, "Response body is null"); + + // Check the response + final var parsedResponse = + assertDoesNotThrow( + () -> MAPPER.readValue(responseBody.bytes(), UserResponse.class)); + assertEquals(userId.get(), parsedResponse.id(), "IDs do not match"); + assertEquals( + request.username(), parsedResponse.username(), "Username is not correct"); + + // Check the database + final var optionalRecord = + testDsl() + .selectFrom(USERS) + .where(USERS.ID.eq(parsedResponse.id())) + .fetchOptional(); + assertTrue(optionalRecord.isPresent(), "New database record must be created"); + + final var databaseRecord = optionalRecord.get(); + assertEquals( + request.username(), databaseRecord.getName(), "Database username is not correct"); + assertArrayEquals( + request.password(), + databaseRecord.getPassword().toCharArray(), + "Database password is not correct"); + } + }); + } + + @Test + void when_existing_user_update_requested_then_it_is_returned() { + JavalinTest.test( + javalin, + (server, client) -> { + final var request = + new UserRequest( + RandomStringUtils.randomAlphanumeric(16), + RandomStringUtils.randomAlphanumeric(16).toCharArray()); + + final var userId = new AtomicReference(null); + + try (final var response = client.post("/api/users", request)) { + assertEquals(HttpStatus.OK.getCode(), response.code(), "Response code is not OK"); + + final var responseBody = response.body(); + assertNotNull(responseBody, "Response body is null"); + + // Check the response + final var parsedResponse = + assertDoesNotThrow( + () -> MAPPER.readValue(responseBody.bytes(), UserResponse.class)); + userId.set(parsedResponse.id()); + } + + final var patchRequest = + new UserRequest( + RandomStringUtils.randomAlphanumeric(16), + RandomStringUtils.randomAlphanumeric(16).toCharArray()); + + try (final var response = client.patch("/api/users/" + userId.get(), patchRequest)) { + assertEquals(HttpStatus.OK.getCode(), response.code(), "Response code is not OK"); + + final var responseBody = response.body(); + assertNotNull(responseBody, "Response body is null"); + + // Check the response + final var parsedResponse = + assertDoesNotThrow( + () -> MAPPER.readValue(responseBody.bytes(), UserResponse.class)); + assertEquals(userId.get(), parsedResponse.id(), "IDs do not match"); + assertEquals( + patchRequest.username(), parsedResponse.username(), "Username is not correct"); + + // Check the database + final var optionalRecord = + testDsl() + .selectFrom(USERS) + .where(USERS.ID.eq(parsedResponse.id())) + .fetchOptional(); + assertTrue(optionalRecord.isPresent(), "New database record must be created"); + + final var databaseRecord = optionalRecord.get(); + assertEquals( + patchRequest.username(), + databaseRecord.getName(), + "Database username is not correct"); + assertArrayEquals( + patchRequest.password(), + databaseRecord.getPassword().toCharArray(), + "Database password is not correct"); + } + }); + } + + @Test + void when_user_delete_requested_with_incorrect_id_then_400_is_returned() { + JavalinTest.test( + javalin, + (server, client) -> { + try (final var response = client.delete("/api/users/invalidUuid")) { + assertEquals( + HttpStatus.BAD_REQUEST.getCode(), + response.code(), + "Response code is not Bad Request"); + } + }); + } + + @Test + void when_existing_user_delete_requested_then_it_is_returned() { + JavalinTest.test( + javalin, + (server, client) -> { + final var request = + new UserRequest( + RandomStringUtils.randomAlphanumeric(16), + RandomStringUtils.randomAlphanumeric(16).toCharArray()); + + final var userId = new AtomicReference(null); + + try (final var response = client.post("/api/users", request)) { + assertEquals(HttpStatus.OK.getCode(), response.code(), "Response code is not OK"); + + final var responseBody = response.body(); + assertNotNull(responseBody, "Response body is null"); + + // Check the response + final var parsedResponse = + assertDoesNotThrow( + () -> MAPPER.readValue(responseBody.bytes(), UserResponse.class)); + userId.set(parsedResponse.id()); + } + + try (final var response = client.delete("/api/users/" + userId.get())) { + assertEquals( + HttpStatus.NO_CONTENT.getCode(), response.code(), "Response code is not OK"); + + // Check the database + final var optionalRecord = + testDsl().selectFrom(USERS).where(USERS.ID.eq(userId.get())).fetchOptional(); + assertTrue(optionalRecord.isEmpty(), "Database record must be deleted"); + } + }); + } + } +} diff --git a/src/test/java/io/github/suppierk/jiqs/configuration/values/ServerPortTest.java b/src/test/java/io/github/suppierk/jiqs/configuration/values/ServerPortTest.java new file mode 100644 index 0000000..ebde108 --- /dev/null +++ b/src/test/java/io/github/suppierk/jiqs/configuration/values/ServerPortTest.java @@ -0,0 +1,30 @@ +package io.github.suppierk.jiqs.configuration.values; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.concurrent.ThreadLocalRandom; +import nl.jqno.equalsverifier.EqualsVerifier; +import org.junit.jupiter.api.Test; + +class ServerPortTest { + @Test + void verify_basic_object_properties() { + EqualsVerifier.forClass(ServerPort.class).verify(); + } + + @Test + void verify_constructor() { + assertThrows(IllegalStateException.class, () -> new ServerPort(null)); + + final var port = ThreadLocalRandom.current().nextInt(0, 65535); + final var serverPort = assertDoesNotThrow(() -> new ServerPort(port)); + assertEquals(port, serverPort.get()); + + assertNotNull(serverPort.toString()); + assertTrue(serverPort.toString().contains(Integer.toString(port))); + } +} diff --git a/src/test/java/io/github/suppierk/jiqs/models/requests/UserRequestTest.java b/src/test/java/io/github/suppierk/jiqs/models/requests/UserRequestTest.java new file mode 100644 index 0000000..9e5001d --- /dev/null +++ b/src/test/java/io/github/suppierk/jiqs/models/requests/UserRequestTest.java @@ -0,0 +1,31 @@ +package io.github.suppierk.jiqs.models.requests; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import nl.jqno.equalsverifier.EqualsVerifier; +import org.junit.jupiter.api.Test; +import org.testcontainers.shaded.org.apache.commons.lang3.RandomStringUtils; + +class UserRequestTest { + @Test + void verify_basic_object_properties() { + EqualsVerifier.forClass(UserRequest.class).verify(); + } + + @Test + void verify_constructor() { + final var username = RandomStringUtils.randomAlphabetic(10); + final var password = RandomStringUtils.randomAlphabetic(10); + final var passwordArray = password.toCharArray(); + + final var userProperties = assertDoesNotThrow(() -> new UserRequest(username, passwordArray)); + + assertNotNull(userProperties.toString()); + assertTrue(userProperties.toString().contains(username)); + assertFalse(userProperties.toString().contains("password")); + assertFalse(userProperties.toString().contains(password)); + } +} diff --git a/src/test/java/io/github/suppierk/test/AbstractDatabaseTest.java b/src/test/java/io/github/suppierk/test/AbstractDatabaseTest.java new file mode 100644 index 0000000..7356947 --- /dev/null +++ b/src/test/java/io/github/suppierk/test/AbstractDatabaseTest.java @@ -0,0 +1,84 @@ +package io.github.suppierk.test; + +import com.zaxxer.hikari.HikariConfig; +import com.zaxxer.hikari.HikariDataSource; +import java.time.Duration; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.shaded.org.awaitility.Awaitility; + +/** Abstract functionality which other tests can extend to verify database related operations. */ +public abstract class AbstractDatabaseTest { + private static final PostgreSQLContainer POSTGRESQL = + new PostgreSQLContainer<>("postgres:16-alpine"); + + private static HikariDataSource dataSource; + private static DSLContext dsl; + + @BeforeAll + static void beforeAll() { + // Kick off the database container + POSTGRESQL.setCommand("postgres", "-c", "fsync=off", "-c", "log_statement=all"); + POSTGRESQL.start(); + + // Wait until the database container is up + Awaitility.await() + .pollDelay(Duration.ofMillis(250)) + .pollInterval(Duration.ofMillis(250)) + .atMost(Duration.ofSeconds(10)) + .until(POSTGRESQL::isRunning); + + // Run migration against container + Flyway.configure() + .dataSource(POSTGRESQL.getJdbcUrl(), POSTGRESQL.getUsername(), POSTGRESQL.getPassword()) + .locations("classpath:db/migration") + .load() + .migrate(); + + // Create database connection pool for tests + HikariConfig hikariReadWriteConfig = new HikariConfig(); + hikariReadWriteConfig.setDriverClassName(POSTGRESQL.getDriverClassName()); + hikariReadWriteConfig.setJdbcUrl(POSTGRESQL.getJdbcUrl()); + hikariReadWriteConfig.setUsername(POSTGRESQL.getUsername()); + hikariReadWriteConfig.setPassword(POSTGRESQL.getPassword()); + dataSource = new HikariDataSource(hikariReadWriteConfig); + + // Create DSL context for direct database querying in tests + dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + } + + @AfterAll + static void afterAll() { + dataSource.close(); + POSTGRESQL.stop(); + } + + protected static String getDriverClassName() { + return POSTGRESQL.getDriverClassName(); + } + + protected static String getJdbcUrl() { + return POSTGRESQL.getJdbcUrl(); + } + + protected static String getDatabaseName() { + return POSTGRESQL.getDatabaseName(); + } + + protected static String getUsername() { + return POSTGRESQL.getUsername(); + } + + protected static String getPassword() { + return POSTGRESQL.getPassword(); + } + + protected static DSLContext testDsl() { + return dsl; + } +}