commit 39faa04174a2f1d42ed93eb7c316bc57429909c1 Author: Erik C. Thauvin Date: Wed Sep 21 02:50:11 2022 -0700 Initial commit. diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..1f808de --- /dev/null +++ b/.editorconfig @@ -0,0 +1,2 @@ +[*] +insert_final_newline = true diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..6ec2ae2 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,5 @@ +# Set the default behavior, in case people don't have core.autocrlf set. +* text=auto + +# batch files are specific to windows and always crlf +*.bat eol=crlf diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..13a066e --- /dev/null +++ b/.gitignore @@ -0,0 +1,85 @@ +!.vscode/extensions.json +!.vscode/launch.json +!.vscode/settings.json +!.vscode/tasks.json +*.class +*.code-workspace +*.ctxt +*.iws +*.log +*.nar +*.rar +*.sublime-* +*.tar.gz +*.zip +.DS_Store +.classpath +.gradle +.history +.kobalt +.mtj.tmp/ +.mvn/timing.properties +.mvn/wrapper/maven-wrapper.jar +.nb-gradle +.project +.scannerwork +.settings +.vscode/* +/**/.idea/$CACHE_FILE$ +/**/.idea/$PRODUCT_WORKSPACE_FILE$ +/**/.idea/**/caches/build_file_checksums.ser +/**/.idea/**/contentModel.xml +/**/.idea/**/dataSources.ids +/**/.idea/**/dataSources.local.xml +/**/.idea/**/dataSources/ +/**/.idea/**/dbnavigator.xml +/**/.idea/**/dictionaries +/**/.idea/**/dynamic.xml +/**/.idea/**/gradle.xml +/**/.idea/**/httpRequests +/**/.idea/**/libraries +/**/.idea/**/mongoSettings.xml +/**/.idea/**/replstate.xml +/**/.idea/**/shelf +/**/.idea/**/shelf/ +/**/.idea/**/sqlDataSources.xml +/**/.idea/**/tasks.xml +/**/.idea/**/uiDesigner.xml +/**/.idea/**/usage.statistics.xml +/**/.idea/**/workspace.xml +/**/.idea/sonarlint* +/**/.idea_modules/ +Thumbs.db +__pycache__ +atlassian-ide-plugin.xml +bin/ +build/ +cmake-build-*/ +com_crashlytics_export_strings.xml +crashlytics-build.properties +crashlytics.properties +dependency-reduced-pom.xml +deploy/ +dist/ +ehthumbs.db +fabric.properties +gen/ +gradle.properties +hs_err_pid* +kobaltBuild +kobaltw*-test +lib/kotlin* +libs/ +local.properties +out/ +pom.xml.asc +pom.xml.next +pom.xml.releaseBackup +pom.xml.tag +pom.xml.versionsBackup +proguard-project.txt +project.properties +release.properties +target/ +test-output +venv diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..26d3352 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,3 @@ +# Default ignored files +/shelf/ +/workspace.xml diff --git a/.idea/compiler.xml b/.idea/compiler.xml new file mode 100644 index 0000000..fb7f4a8 --- /dev/null +++ b/.idea/compiler.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/.idea/copyright/Erik_s_Copyright_Notice.xml b/.idea/copyright/Erik_s_Copyright_Notice.xml new file mode 100644 index 0000000..08660a1 --- /dev/null +++ b/.idea/copyright/Erik_s_Copyright_Notice.xml @@ -0,0 +1,6 @@ + + + + \ No newline at end of file diff --git a/.idea/copyright/profiles_settings.xml b/.idea/copyright/profiles_settings.xml new file mode 100644 index 0000000..1419e40 --- /dev/null +++ b/.idea/copyright/profiles_settings.xml @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/.idea/inspectionProfiles/Project_Default.xml b/.idea/inspectionProfiles/Project_Default.xml new file mode 100644 index 0000000..1e01b48 --- /dev/null +++ b/.idea/inspectionProfiles/Project_Default.xml @@ -0,0 +1,8 @@ + + + + \ No newline at end of file diff --git a/.idea/jarRepositories.xml b/.idea/jarRepositories.xml new file mode 100644 index 0000000..cfd3ca8 --- /dev/null +++ b/.idea/jarRepositories.xml @@ -0,0 +1,25 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/kotlinc.xml b/.idea/kotlinc.xml new file mode 100644 index 0000000..b1077fb --- /dev/null +++ b/.idea/kotlinc.xml @@ -0,0 +1,6 @@ + + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..2dbd526 --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..09e222b --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,27 @@ +Copyright (c) 2022, Erik C. Thauvin (erik@thauvin.net) +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +* Neither the name of this project nor the names of its contributors may be + used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..4990c29 --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,168 @@ +import org.gradle.api.tasks.testing.logging.TestExceptionFormat +import org.gradle.api.tasks.testing.logging.TestLogEvent +import org.jetbrains.dokka.gradle.DokkaTask +import org.jetbrains.kotlin.gradle.tasks.KotlinCompile + +plugins { + id("com.github.ben-manes.versions") version "0.42.0" + id("io.gitlab.arturbosch.detekt") version "1.21.0" + id("java") + id("maven-publish") + id("org.jetbrains.dokka") version "1.7.10" + id("org.jetbrains.kotlinx.kover") version "0.6.0" + id("org.sonarqube") version "3.4.0.2513" + id("signing") + kotlin("jvm") version "1.7.10" +} + +description = "Kotlin/Java Wrapper for Sv443's JokeApi" +group = "net.thauvin.erik" +version = "0.9-SNAPSHOT" + +val deployDir = "deploy" +val gitHub = "ethauvin/$name" +val mavenUrl = "https://github.com/$gitHub" +val publicationName = "mavenJava" + +repositories { + mavenCentral() + maven { url = uri("https://oss.sonatype.org/content/repositories/snapshots") } +} + +dependencies { + implementation(platform(kotlin("bom"))) + + implementation("org.json:json:20220320") + + testImplementation(kotlin("test")) + testImplementation("org.junit.jupiter:junit-jupiter:5.9.1") +} + +tasks.test { + useJUnitPlatform() +} + +java { + sourceCompatibility = JavaVersion.VERSION_11 + targetCompatibility = JavaVersion.VERSION_11 + withSourcesJar() +} + +sonarqube { + properties { + property("sonar.projectKey", "ethauvin_$name") + property("sonar.organization", "ethauvin-github") + property("sonar.host.url", "https://sonarcloud.io") + property("sonar.sourceEncoding", "UTF-8") + property("sonar.coverage.jacoco.xmlReportPaths", "${project.buildDir}/reports/kover/xml/report.xml") + } +} + +val javadocJar by tasks.creating(Jar::class) { + dependsOn(tasks.dokkaJavadoc) + from(tasks.dokkaJavadoc) + archiveClassifier.set("javadoc") +} + +tasks { + withType().configureEach { + kotlinOptions.jvmTarget = java.targetCompatibility.toString() + } + + withType { + testLogging { + exceptionFormat = TestExceptionFormat.FULL + events = setOf(TestLogEvent.PASSED, TestLogEvent.SKIPPED, TestLogEvent.FAILED) + } + } + + withType { + destination = file("$projectDir/pom.xml") + } + + clean { + doLast { + project.delete(fileTree(deployDir)) + } + } + + withType().configureEach { + dokkaSourceSets { + named("main") { + moduleName.set("Joke API") + } + } + } + + val copyToDeploy by registering(Copy::class) { + from(configurations.runtimeClasspath) { + exclude("annotations-*.jar") + } + from(jar) + into(deployDir) + } + + register("deploy") { + description = "Copies all needed files to the $deployDir directory." + group = PublishingPlugin.PUBLISH_TASK_GROUP + dependsOn(clean, wrapper, build, jar) + outputs.dir(deployDir) + inputs.files(copyToDeploy) + mustRunAfter(clean) + } + + "sonarqube" { + dependsOn(koverReport) + } +} + +publishing { + publications { + create(publicationName) { + from(components["java"]) + artifact(javadocJar) + pom { + name.set(project.name) + description.set(project.description) + url.set(mavenUrl) + licenses { + license { + name.set("BSD 3-Clause") + url.set("https://opensource.org/licenses/BSD-3-Clause") + } + } + developers { + developer { + id.set("ethauvin") + name.set("Erik C. Thauvin") + email.set("erik@thauvin.net") + url.set("https://erik.thauvin.net/") + } + } + scm { + connection.set("scm:git:git://github.com/$gitHub.git") + developerConnection.set("scm:git:git@github.com:$gitHub.git") + url.set(mavenUrl) + } + issueManagement { + system.set("GitHub") + url.set("$mavenUrl/issues") + } + } + } + } + repositories { + maven { + name = "ossrh" + url = if (project.version.toString().contains("SNAPSHOT")) + uri("https://oss.sonatype.org/content/repositories/snapshots/") else + uri("https://oss.sonatype.org/service/local/staging/deploy/maven2/") + credentials(PasswordCredentials::class) + } + } +} + +signing { + useGpgCmd() + sign(publishing.publications[publicationName]) +} \ No newline at end of file diff --git a/detekt-baseline.xml b/detekt-baseline.xml new file mode 100644 index 0000000..b268e77 --- /dev/null +++ b/detekt-baseline.xml @@ -0,0 +1,23 @@ + + + + + ComplexMethod:JokeApi.kt$JokeApi.Companion$@JvmStatic @JvmOverloads @Throws(IOException::class) fun apiCall( categories: Set<Category> = setOf(Category.ANY), language: Language = Language.ENGLISH, flags: Set<Flag> = emptySet(), type: Set<Type> = emptySet(), format: Format = Format.JSON, search: String = "", idRange: IdRange = IdRange(), amount: Int = 1, safe: Boolean = false, ): String + LongMethod:JokeApi.kt$JokeApi.Companion$@Throws(JokeException::class, IOException::class) private fun fetchUrl(url: String) : String + LongParameterList:JokeApi.kt$JokeApi.Companion$( categories: Set<Category> = setOf(Category.ANY), language: Language = Language.ENGLISH, flags: Set<Flag> = emptySet(), type: Set<Type> = emptySet(), format: Format = Format.JSON, search: String = "", idRange: IdRange = IdRange(), amount: Int = 1, safe: Boolean = false, ) + LongParameterList:JokeApi.kt$JokeApi.Companion$( categories: Set<Category> = setOf(Category.ANY), language: Language = Language.ENGLISH, flags: Set<Flag> = emptySet(), type: Set<Type> = emptySet(), search: String = "", idRange: IdRange = IdRange(), safe: Boolean = false ) + LongParameterList:JokeException.kt$JokeException$( val error: Boolean, val internalError: Boolean, val code: Int, message: String, val causedBy: List<String>, val additionalInfo: String, val timestamp: Long, cause: Throwable? = null ) + MagicNumber:JokeApi.kt$JokeApi.Companion$10 + MagicNumber:JokeApi.kt$JokeApi.Companion$200 + MagicNumber:JokeApi.kt$JokeApi.Companion$399 + MagicNumber:JokeApi.kt$JokeApi.Companion$400 + MagicNumber:JokeApi.kt$JokeApi.Companion$403 + MagicNumber:JokeApi.kt$JokeApi.Companion$404 + MagicNumber:JokeApi.kt$JokeApi.Companion$413 + MagicNumber:JokeApi.kt$JokeApi.Companion$428 + MagicNumber:JokeApi.kt$JokeApi.Companion$500 + MagicNumber:JokeApi.kt$JokeApi.Companion$523 + ThrowsCount:JokeApi.kt$JokeApi.Companion$@Throws(JokeException::class, IOException::class) private fun fetchUrl(url: String) : String + UtilityClassWithPublicConstructor:JokeApi.kt$JokeApi + + diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..249e583 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..ae04661 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-7.5.1-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..a69d9cb --- /dev/null +++ b/gradlew @@ -0,0 +1,240 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${0##*/} + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# 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..f127cfd --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,91 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% 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.kts b/settings.gradle.kts new file mode 100644 index 0000000..dc0111b --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1,3 @@ + +rootProject.name = "jokeapi" + diff --git a/src/main/kotlin/net/thauvin/erik/jokeapi/Category.kt b/src/main/kotlin/net/thauvin/erik/jokeapi/Category.kt new file mode 100644 index 0000000..1cb7b4e --- /dev/null +++ b/src/main/kotlin/net/thauvin/erik/jokeapi/Category.kt @@ -0,0 +1,54 @@ +/* + * Category.kt + * + * Copyright (c) 2022, Erik C. Thauvin (erik@thauvin.net) + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * Neither the name of this project nor the names of its contributors may be + * used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package net.thauvin.erik.jokeapi + +/** + * Categories and aliases. + */ +enum class Category(val value: String) { + ANY("Any"), + CHRISTMAS("Christmas"), + DARK("Dark"), + + MISC("Misc"), + MISCELLANEOUS(MISC.value), + + PROGRAMMING("Programming"), + CODING(PROGRAMMING.value), + DEVELOPMENT(PROGRAMMING.value), + + PUN("Pun"), + + SPOOKY("Spooky"), + HALLOWEEN(SPOOKY.value) +} diff --git a/src/main/kotlin/net/thauvin/erik/jokeapi/Flag.kt b/src/main/kotlin/net/thauvin/erik/jokeapi/Flag.kt new file mode 100644 index 0000000..f43bed7 --- /dev/null +++ b/src/main/kotlin/net/thauvin/erik/jokeapi/Flag.kt @@ -0,0 +1,46 @@ +/* + * Flag.kt + * + * Copyright (c) 2022, Erik C. Thauvin (erik@thauvin.net) + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * Neither the name of this project nor the names of its contributors may be + * used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package net.thauvin.erik.jokeapi + +/** + * Blacklist flags. + */ +enum class Flag(val value: String) { + NSFW("nsfw"), + RELIGIOUS("religious"), + POLITICAL("political"), + RACIST("racist"), + SEXIST("sexist"), + EXPLICIT("explicit"), + ALL("${NSFW.value},${RELIGIOUS.value},${POLITICAL.value},${RACIST.value},${SEXIST.value},${EXPLICIT.value}"), +} diff --git a/src/main/kotlin/net/thauvin/erik/jokeapi/Format.kt b/src/main/kotlin/net/thauvin/erik/jokeapi/Format.kt new file mode 100644 index 0000000..9784907 --- /dev/null +++ b/src/main/kotlin/net/thauvin/erik/jokeapi/Format.kt @@ -0,0 +1,40 @@ +/* + * Format.kt + * + * Copyright (c) 2022, Erik C. Thauvin (erik@thauvin.net) + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * Neither the name of this project nor the names of its contributors may be + * used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package net.thauvin.erik.jokeapi + +/** + * Response formats. + */ +enum class Format(val value: String) { + JSON("json"), XML("xml"), YAML("yaml"), TEXT("txt"), TXT(TEXT.value) +} diff --git a/src/main/kotlin/net/thauvin/erik/jokeapi/IdRange.kt b/src/main/kotlin/net/thauvin/erik/jokeapi/IdRange.kt new file mode 100644 index 0000000..84b4d66 --- /dev/null +++ b/src/main/kotlin/net/thauvin/erik/jokeapi/IdRange.kt @@ -0,0 +1,35 @@ +/* + * IdRange.kt + * + * Copyright (c) 2022, Erik C. Thauvin (erik@thauvin.net) + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * Neither the name of this project nor the names of its contributors may be + * used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package net.thauvin.erik.jokeapi + +data class IdRange(val start: Int = -1, val end: Int = -1) diff --git a/src/main/kotlin/net/thauvin/erik/jokeapi/Joke.kt b/src/main/kotlin/net/thauvin/erik/jokeapi/Joke.kt new file mode 100644 index 0000000..7ee80ce --- /dev/null +++ b/src/main/kotlin/net/thauvin/erik/jokeapi/Joke.kt @@ -0,0 +1,44 @@ +/* + * Joke.kt + * + * Copyright (c) 2022, Erik C. Thauvin (erik@thauvin.net) + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * Neither the name of this project nor the names of its contributors may be + * used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package net.thauvin.erik.jokeapi + +data class Joke( + val error: Boolean, + val category: Category, + val type: Type, + val joke: Set, + val flags: Set, + val id: Int, + val safe: Boolean, + val language: Language? +) diff --git a/src/main/kotlin/net/thauvin/erik/jokeapi/JokeApi.kt b/src/main/kotlin/net/thauvin/erik/jokeapi/JokeApi.kt new file mode 100644 index 0000000..0bfef52 --- /dev/null +++ b/src/main/kotlin/net/thauvin/erik/jokeapi/JokeApi.kt @@ -0,0 +1,266 @@ +/* + * JokeApi.kt + * + * Copyright (c) 2022, Erik C. Thauvin (erik@thauvin.net) + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * Neither the name of this project nor the names of its contributors may be + * used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package net.thauvin.erik.jokeapi + +import org.json.JSONObject +import java.io.IOException +import java.net.HttpURLConnection +import java.net.URL +import java.net.URLEncoder +import java.nio.charset.StandardCharsets +import java.util.logging.Level +import java.util.logging.Logger +import java.util.stream.Collectors + +class JokeApi { + companion object { + private const val API_URL = "https://v2.jokeapi.dev/joke/" + val logger: Logger = Logger.getLogger(JokeApi::class.java.simpleName) + + @JvmStatic + @JvmOverloads + @Throws(IOException::class) + fun apiCall( + categories: Set = setOf(Category.ANY), + language: Language = Language.ENGLISH, + flags: Set = emptySet(), + type: Set = emptySet(), + format: Format = Format.JSON, + search: String = "", + idRange: IdRange = IdRange(), + amount: Int = 1, + safe: Boolean = false, + ): String { + val urlBuilder = StringBuilder(API_URL) + val urlParams = mutableListOf() + + // Category + if (!categories.contains(Category.ANY)) { + urlBuilder.append(categories.stream().map(Category::value).collect(Collectors.joining(","))) + } else { + urlBuilder.append(Category.ANY.value) + } + + // Language + if (language != Language.ENGLISH) { + urlParams.add("lang=${language.value}") + } + + // Flags + if (flags.isNotEmpty()) { + if (flags.contains(Flag.ALL)) { + urlParams.add("blacklistFlags=${Flag.ALL.value}") + } else { + urlParams.add( + "blacklistFlags=" + flags.stream().map(Flag::value).collect(Collectors.joining(",")) + ) + } + } + + // Type + if (type.isNotEmpty()) { + urlParams.add("type=" + type.stream().map(Type::value).collect(Collectors.joining(","))) + } + + // Format + if (format != Format.JSON) { + urlParams.add("format=${format.value}") + } + + // Contains + if (search.isNotBlank()) { + urlParams.add("contains=${URLEncoder.encode(search, StandardCharsets.UTF_8)}") + } + + // Range + if (idRange.start >= 0) { + if (idRange.end == -1 || idRange.start == idRange.end) { + urlParams.add("idRange=${idRange.start}") + } else if (idRange.end > idRange.start) { + urlParams.add("idRange=${idRange.start}-${idRange.end}") + } + } + + // Amount + if (amount in 2..10) { + urlParams.add("amount=${amount}") + } + + // Safe + if (safe) { + urlParams.add("safe-mode") + } + + if (urlParams.isNotEmpty()) { + urlBuilder.append('?') + val it = urlParams.iterator() + while (it.hasNext()) { + urlBuilder.append(it.next()) + if (it.hasNext()) { + urlBuilder.append("&") + } + } + } + + return fetchUrl(urlBuilder.toString()) + } + + @Throws(JokeException::class, IOException::class) + private fun fetchUrl(url: String) : String { + logger.log(Level.FINE, url) + + val connection = URL(url).openConnection() as HttpURLConnection + connection.setRequestProperty( + "User-Agent", + "Mozilla/5.0 (Linux x86_64; rv:104.0) Gecko/20100101 Firefox/104.0" + ) + + if (connection.responseCode in 200..399) { + val body = connection.inputStream.bufferedReader().readText() + if (logger.isLoggable(Level.FINE)) { + logger.log(Level.FINE, body) + } + return body + } else { + when (connection.responseCode) { + 400 -> throw IOException( + "400: Bad Request", + IOException( + "The request you have sent to JokeAPI is formatted incorrectly and cannot be" + + " processed" + ) + ) + + 403 -> throw IOException( + "4o3: Forbidden", + IOException( + "You have been added to the blacklist due to malicious behavior and are not allowed" + + " to send requests to JokeAPI anymore" + ) + ) + + 404 -> throw IOException( + "404: Not Found", + IOException("The URL you have requested couldn't be found") + ) + + 413 -> throw IOException( + "413: Payload Too Large", + IOException("The payload data sent to the server exceeds the maximum size of 5120 bytes") + ) + + 428 -> throw IOException( + "429: Too Many Requests", + IOException( + "You have exceeded the limit of 120 requests per minute and have to wait a bit" + + " until you are allowed to send requests again" + ) + ) + + 500 -> throw IOException( + "500: Internal Server Error", + IOException( + "There was a general internal error within JokeAPI. You can get more info from" + + " the properties in the response text" + ) + ) + + 523 -> throw IOException( + "523: Origin Unreachable", + IOException( + "The server is temporarily offline due to maintenance or a dynamic IP update." + + " Please be patient in this case." + ) + ) + + else -> throw IOException("${connection.responseCode}: Unknown Error") + } + } + } + + @JvmStatic + @JvmOverloads + @Throws(JokeException::class, IOException::class) + fun getJoke( + categories: Set = setOf(Category.ANY), + language: Language = Language.ENGLISH, + flags: Set = emptySet(), + type: Set = emptySet(), + search: String = "", + idRange: IdRange = IdRange(), + safe: Boolean = false + ): Joke { + val json = + JSONObject(apiCall(categories, language, flags, type, search = search, idRange = idRange, safe = safe)) + if (json.getBoolean("error")) { + val causedBy = json.getJSONArray("causedBy") + val causes = MutableList(causedBy.length()) { i -> causedBy.getString(i) } + + throw JokeException( + error = true, + internalError = json.getBoolean("internalError"), + code = json.getInt("code"), + message = json.getString("message"), + causedBy = causes, + additionalInfo = json.getString("additionalInfo"), + timestamp = json.getLong("timestamp") + ) + } else { + val jokes = mutableSetOf() + if (json.has("setup")) { + jokes.add(json.getString("setup")) + jokes.add(json.getString(("delivery"))) + } else { + jokes.addAll(json.getString("joke").split("\n")) + } + val enabledFlags = mutableSetOf() + val flagObject = json.getJSONObject("flags") + for (flag in Flag.values()) { + if (flag != Flag.ALL && flagObject.getBoolean(flag.value)) { + enabledFlags.add(flag) + } + } + return Joke( + error = false, + category = Category.valueOf(json.getString("category").uppercase()), + type = Type.valueOf(json.getString("type").uppercase()), + joke = jokes, + flags = enabledFlags, + safe = json.getBoolean("safe"), + id = json.getInt("id"), + language = Language.valueOf(json.getString("lang").uppercase()) + ) + } + } + } +} diff --git a/src/main/kotlin/net/thauvin/erik/jokeapi/JokeException.kt b/src/main/kotlin/net/thauvin/erik/jokeapi/JokeException.kt new file mode 100644 index 0000000..6a89ce8 --- /dev/null +++ b/src/main/kotlin/net/thauvin/erik/jokeapi/JokeException.kt @@ -0,0 +1,48 @@ +/* + * JokeException.kt + * + * Copyright (c) 2022, Erik C. Thauvin (erik@thauvin.net) + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * Neither the name of this project nor the names of its contributors may be + * used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package net.thauvin.erik.jokeapi + +class JokeException @JvmOverloads constructor( + val error: Boolean, + val internalError: Boolean, + val code: Int, + message: String, + val causedBy: List, + val additionalInfo: String, + val timestamp: Long, + cause: Throwable? = null +) : Exception(message, cause) { + companion object { + private const val serialVersionUID = 1L + } +} diff --git a/src/main/kotlin/net/thauvin/erik/jokeapi/Language.kt b/src/main/kotlin/net/thauvin/erik/jokeapi/Language.kt new file mode 100644 index 0000000..dd17c5c --- /dev/null +++ b/src/main/kotlin/net/thauvin/erik/jokeapi/Language.kt @@ -0,0 +1,51 @@ +/* + * Language.kt + * + * Copyright (c) 2022, Erik C. Thauvin (erik@thauvin.net) + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * Neither the name of this project nor the names of its contributors may be + * used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package net.thauvin.erik.jokeapi + +/** + * Supported languages. + */ +enum class Language(val value: String) { + ENGLISH("en"), + EN(ENGLISH.value), + CZECH("cs"), + CS(CZECH.value), + GERMAN("de"), + DE(GERMAN.value), + SPANISH("es"), + ES(SPANISH.value), + FRENCH("fr"), + FR(FRENCH.value), + PORTUGUESE("pt"), + PT(PORTUGUESE.value) +} diff --git a/src/main/kotlin/net/thauvin/erik/jokeapi/Type.kt b/src/main/kotlin/net/thauvin/erik/jokeapi/Type.kt new file mode 100644 index 0000000..68f87c5 --- /dev/null +++ b/src/main/kotlin/net/thauvin/erik/jokeapi/Type.kt @@ -0,0 +1,41 @@ +/* + * Type.kt + * + * Copyright (c) 2022, Erik C. Thauvin (erik@thauvin.net) + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * Neither the name of this project nor the names of its contributors may be + * used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package net.thauvin.erik.jokeapi + +/** + * Joke types. + */ +enum class Type(val value: String) { + SINGLE("single"), + TWOPART("twopart") +} diff --git a/src/test/kotlin/net/thauvin/erik/jokeapi/JokeApiTest.kt b/src/test/kotlin/net/thauvin/erik/jokeapi/JokeApiTest.kt new file mode 100644 index 0000000..1b7661a --- /dev/null +++ b/src/test/kotlin/net/thauvin/erik/jokeapi/JokeApiTest.kt @@ -0,0 +1,174 @@ +/* + * JokeApiTest.kt + * + * Copyright (c) 2022, Erik C. Thauvin (erik@thauvin.net) + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * Neither the name of this project nor the names of its contributors may be + * used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package net.thauvin.erik.jokeapi + +import net.thauvin.erik.jokeapi.JokeApi.Companion.apiCall +import net.thauvin.erik.jokeapi.JokeApi.Companion.getJoke +import net.thauvin.erik.jokeapi.JokeApi.Companion.logger +import org.junit.jupiter.api.Assertions.assertAll +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertFalse +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.BeforeAll +import org.junit.jupiter.api.Test +import java.util.logging.ConsoleHandler +import java.util.logging.Level + +internal class JokeApiTest { + @Test + fun apiTxtCallTest() { + val response = apiCall(format = Format.TEXT) + logger.log(Level.FINE, response) + assertAll("plain text", + { assertTrue(response.isNotEmpty(), "should be not empty") }, + { assertFalse(response.startsWith("Error "), "should not be an error") } + ) + } + + @Test + fun apiTxtErrorCallTest() { + val response = apiCall(format = Format.TXT, idRange = IdRange(0, 30000)) + logger.log(Level.FINE, response) + assertTrue(response.startsWith("Error "), "should be an error") + } + + @Test + fun apiXmlCallTest() { + val response = apiCall(format = Format.XML) + logger.log(Level.FINE, response) + assertTrue(response.startsWith("\n\n false"), "should be xml") + } + + @Test + fun apiYamlCallTest() { + val response = apiCall(format = Format.YAML) + logger.log(Level.FINE, response) + assertTrue(response.startsWith("error: false"), "should be xml") + } + + @Test + fun jokeExceptionTest() { + try { + getJoke(categories = setOf(Category.CHRISTMAS), search = "man") + } catch (e: JokeException) { + assertAll("exception validation", + { assertEquals(106, e.code, "code should be valid") }, + { assertTrue(e.error, "should be an error") }, + { assertFalse(e.internalError, "should not be internal error") }, + { assertEquals("No matching joke found", e.message, "message should match") }, + { assertEquals(1, e.causedBy.size, "causedby size should be 1") }, + { assertTrue(e.additionalInfo.isNotEmpty(), "additional info should not be empty") }, + { assertTrue(e.timestamp > 0, "timestamp should be > 0") } + ) + } + } + + @Test + fun getJokeTest() { + val joke = getJoke() + logger.log(Level.FINE, joke.toString()) + assertAll("no param", + { assertFalse(joke.error, "error should be false") }, + { assertTrue(joke.joke.isNotEmpty(), "joke should not be empty") }, + { assertTrue(joke.type == Type.TWOPART || joke.type == Type.SINGLE, "type should validate") }, + { assertTrue(joke.id >= 0, "id should be >= 0") }, + { assertEquals(Language.EN, joke.language, "language should be english") } + ) + } + + @Test + fun getJokeIdTest() { + val id = 172 + val joke = getJoke(idRange = IdRange(id)) + logger.log(Level.FINE, joke.toString()) + assertAll("joke by id", + { assertTrue(joke.flags.contains(Flag.NSFW) && joke.flags.contains(Flag.EXPLICIT), "nsfw & explicit") }, + { assertEquals(172, joke.id, "id is $id") }, + { assertEquals(Category.PUN, joke.category, "category should be pun") } + ) + } + + @Test + fun getJokeIdRangeTest() { + val idRange = IdRange(1, 100) + val joke = getJoke(idRange = idRange) + logger.log(Level.FINE, joke.toString()) + assertTrue(joke.id >= idRange.start && joke.id <= idRange.end, "id should be in range") + } + + @Test + fun getSafeJokeTest() { + val joke = getJoke(safe = true) + logger.log(Level.FINE, joke.toString()) + assertAll("safe joke", + { assertTrue(joke.safe, "should be safe") }, + { assertTrue(joke.flags.isEmpty(), "flags should be empty") } + ) + } + + @Test + fun getSingleJokeTest() { + val joke = getJoke(type = setOf(Type.SINGLE)) + logger.log(Level.FINE, joke.toString()) + assertEquals(Type.SINGLE, joke.type, "type should be single") + } + + @Test + fun getTwoPartJokeTest() { + val joke = getJoke(type = setOf(Type.TWOPART)) + logger.log(Level.FINE, joke.toString()) + assertAll("two-part joke", + { assertEquals(Type.TWOPART, joke.type, "type should be two-part") }, + { assertTrue(joke.joke.size > 1, "should have multiple lines") } + ) + } + + @Test + fun getJokeSearchTest() { + val id = 1 + val joke = getJoke(search = "man", categories = setOf(Category.PROGRAMMING), idRange = IdRange(id), safe = true) + logger.log(Level.FINE, joke.toString()) + assertEquals(id, joke.id, "id should be 1") + } + + companion object { + @JvmStatic + @BeforeAll + fun beforeAll() { + with(logger) { + addHandler(ConsoleHandler().apply { level = Level.FINE }) + level = Level.FINE + } + } + } +}