Initial commit.
This commit is contained in:
commit
39faa04174
29 changed files with 1512 additions and 0 deletions
2
.editorconfig
Normal file
2
.editorconfig
Normal file
|
@ -0,0 +1,2 @@
|
|||
[*]
|
||||
insert_final_newline = true
|
5
.gitattributes
vendored
Normal file
5
.gitattributes
vendored
Normal file
|
@ -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
|
85
.gitignore
vendored
Normal file
85
.gitignore
vendored
Normal file
|
@ -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
|
3
.idea/.gitignore
generated
vendored
Normal file
3
.idea/.gitignore
generated
vendored
Normal file
|
@ -0,0 +1,3 @@
|
|||
# Default ignored files
|
||||
/shelf/
|
||||
/workspace.xml
|
6
.idea/compiler.xml
generated
Normal file
6
.idea/compiler.xml
generated
Normal file
|
@ -0,0 +1,6 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="CompilerConfiguration">
|
||||
<bytecodeTargetLevel target="11" />
|
||||
</component>
|
||||
</project>
|
6
.idea/copyright/Erik_s_Copyright_Notice.xml
generated
Normal file
6
.idea/copyright/Erik_s_Copyright_Notice.xml
generated
Normal file
|
@ -0,0 +1,6 @@
|
|||
<component name="CopyrightManager">
|
||||
<copyright>
|
||||
<option name="notice" value="&#36;file.fileName Copyright (c) &#36;today.year, 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." />
|
||||
<option name="myName" value="Erik's Copyright Notice" />
|
||||
</copyright>
|
||||
</component>
|
3
.idea/copyright/profiles_settings.xml
generated
Normal file
3
.idea/copyright/profiles_settings.xml
generated
Normal file
|
@ -0,0 +1,3 @@
|
|||
<component name="CopyrightManager">
|
||||
<settings default="Erik's Copyright Notice" />
|
||||
</component>
|
8
.idea/inspectionProfiles/Project_Default.xml
generated
Normal file
8
.idea/inspectionProfiles/Project_Default.xml
generated
Normal file
|
@ -0,0 +1,8 @@
|
|||
<component name="InspectionProjectProfileManager">
|
||||
<profile version="1.0">
|
||||
<option name="myName" value="Project Default" />
|
||||
<inspection_tool class="JavadocDeclaration" enabled="true" level="WARNING" enabled_by_default="true">
|
||||
<option name="ADDITIONAL_TAGS" value="created" />
|
||||
</inspection_tool>
|
||||
</profile>
|
||||
</component>
|
25
.idea/jarRepositories.xml
generated
Normal file
25
.idea/jarRepositories.xml
generated
Normal file
|
@ -0,0 +1,25 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="RemoteRepositoriesConfiguration">
|
||||
<remote-repository>
|
||||
<option name="id" value="central" />
|
||||
<option name="name" value="Maven Central repository" />
|
||||
<option name="url" value="https://repo1.maven.org/maven2" />
|
||||
</remote-repository>
|
||||
<remote-repository>
|
||||
<option name="id" value="jboss.community" />
|
||||
<option name="name" value="JBoss Community repository" />
|
||||
<option name="url" value="https://repository.jboss.org/nexus/content/repositories/public/" />
|
||||
</remote-repository>
|
||||
<remote-repository>
|
||||
<option name="id" value="MavenRepo" />
|
||||
<option name="name" value="MavenRepo" />
|
||||
<option name="url" value="https://repo.maven.apache.org/maven2/" />
|
||||
</remote-repository>
|
||||
<remote-repository>
|
||||
<option name="id" value="maven" />
|
||||
<option name="name" value="maven" />
|
||||
<option name="url" value="https://oss.sonatype.org/content/repositories/snapshots" />
|
||||
</remote-repository>
|
||||
</component>
|
||||
</project>
|
6
.idea/kotlinc.xml
generated
Normal file
6
.idea/kotlinc.xml
generated
Normal file
|
@ -0,0 +1,6 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="KotlinJpsPluginSettings">
|
||||
<option name="version" value="1.7.10" />
|
||||
</component>
|
||||
</project>
|
7
.idea/misc.xml
generated
Normal file
7
.idea/misc.xml
generated
Normal file
|
@ -0,0 +1,7 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ExternalStorageConfigurationManager" enabled="true" />
|
||||
<component name="ProjectRootManager" version="2" languageLevel="JDK_11" project-jdk-name="18" project-jdk-type="JavaSDK">
|
||||
<output url="file://$PROJECT_DIR$/out" />
|
||||
</component>
|
||||
</project>
|
27
LICENSE.txt
Normal file
27
LICENSE.txt
Normal file
|
@ -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.
|
168
build.gradle.kts
Normal file
168
build.gradle.kts
Normal file
|
@ -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<KotlinCompile>().configureEach {
|
||||
kotlinOptions.jvmTarget = java.targetCompatibility.toString()
|
||||
}
|
||||
|
||||
withType<Test> {
|
||||
testLogging {
|
||||
exceptionFormat = TestExceptionFormat.FULL
|
||||
events = setOf(TestLogEvent.PASSED, TestLogEvent.SKIPPED, TestLogEvent.FAILED)
|
||||
}
|
||||
}
|
||||
|
||||
withType<GenerateMavenPom> {
|
||||
destination = file("$projectDir/pom.xml")
|
||||
}
|
||||
|
||||
clean {
|
||||
doLast {
|
||||
project.delete(fileTree(deployDir))
|
||||
}
|
||||
}
|
||||
|
||||
withType<DokkaTask>().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<MavenPublication>(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])
|
||||
}
|
23
detekt-baseline.xml
Normal file
23
detekt-baseline.xml
Normal file
|
@ -0,0 +1,23 @@
|
|||
<?xml version='1.0' encoding='UTF-8'?>
|
||||
<SmellBaseline>
|
||||
<ManuallySuppressedIssues/>
|
||||
<CurrentIssues>
|
||||
<ID>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</ID>
|
||||
<ID>LongMethod:JokeApi.kt$JokeApi.Companion$@Throws(JokeException::class, IOException::class) private fun fetchUrl(url: String) : String</ID>
|
||||
<ID>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, )</ID>
|
||||
<ID>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 )</ID>
|
||||
<ID>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 )</ID>
|
||||
<ID>MagicNumber:JokeApi.kt$JokeApi.Companion$10</ID>
|
||||
<ID>MagicNumber:JokeApi.kt$JokeApi.Companion$200</ID>
|
||||
<ID>MagicNumber:JokeApi.kt$JokeApi.Companion$399</ID>
|
||||
<ID>MagicNumber:JokeApi.kt$JokeApi.Companion$400</ID>
|
||||
<ID>MagicNumber:JokeApi.kt$JokeApi.Companion$403</ID>
|
||||
<ID>MagicNumber:JokeApi.kt$JokeApi.Companion$404</ID>
|
||||
<ID>MagicNumber:JokeApi.kt$JokeApi.Companion$413</ID>
|
||||
<ID>MagicNumber:JokeApi.kt$JokeApi.Companion$428</ID>
|
||||
<ID>MagicNumber:JokeApi.kt$JokeApi.Companion$500</ID>
|
||||
<ID>MagicNumber:JokeApi.kt$JokeApi.Companion$523</ID>
|
||||
<ID>ThrowsCount:JokeApi.kt$JokeApi.Companion$@Throws(JokeException::class, IOException::class) private fun fetchUrl(url: String) : String</ID>
|
||||
<ID>UtilityClassWithPublicConstructor:JokeApi.kt$JokeApi</ID>
|
||||
</CurrentIssues>
|
||||
</SmellBaseline>
|
BIN
gradle/wrapper/gradle-wrapper.jar
vendored
Normal file
BIN
gradle/wrapper/gradle-wrapper.jar
vendored
Normal file
Binary file not shown.
5
gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
5
gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
|
@ -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
|
240
gradlew
vendored
Executable file
240
gradlew
vendored
Executable file
|
@ -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" "$@"
|
91
gradlew.bat
vendored
Normal file
91
gradlew.bat
vendored
Normal file
|
@ -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
|
3
settings.gradle.kts
Normal file
3
settings.gradle.kts
Normal file
|
@ -0,0 +1,3 @@
|
|||
|
||||
rootProject.name = "jokeapi"
|
||||
|
54
src/main/kotlin/net/thauvin/erik/jokeapi/Category.kt
Normal file
54
src/main/kotlin/net/thauvin/erik/jokeapi/Category.kt
Normal file
|
@ -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)
|
||||
}
|
46
src/main/kotlin/net/thauvin/erik/jokeapi/Flag.kt
Normal file
46
src/main/kotlin/net/thauvin/erik/jokeapi/Flag.kt
Normal file
|
@ -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}"),
|
||||
}
|
40
src/main/kotlin/net/thauvin/erik/jokeapi/Format.kt
Normal file
40
src/main/kotlin/net/thauvin/erik/jokeapi/Format.kt
Normal file
|
@ -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)
|
||||
}
|
35
src/main/kotlin/net/thauvin/erik/jokeapi/IdRange.kt
Normal file
35
src/main/kotlin/net/thauvin/erik/jokeapi/IdRange.kt
Normal file
|
@ -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)
|
44
src/main/kotlin/net/thauvin/erik/jokeapi/Joke.kt
Normal file
44
src/main/kotlin/net/thauvin/erik/jokeapi/Joke.kt
Normal file
|
@ -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<String>,
|
||||
val flags: Set<Flag>,
|
||||
val id: Int,
|
||||
val safe: Boolean,
|
||||
val language: Language?
|
||||
)
|
266
src/main/kotlin/net/thauvin/erik/jokeapi/JokeApi.kt
Normal file
266
src/main/kotlin/net/thauvin/erik/jokeapi/JokeApi.kt
Normal file
|
@ -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<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 {
|
||||
val urlBuilder = StringBuilder(API_URL)
|
||||
val urlParams = mutableListOf<String>()
|
||||
|
||||
// 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<Category> = setOf(Category.ANY),
|
||||
language: Language = Language.ENGLISH,
|
||||
flags: Set<Flag> = emptySet(),
|
||||
type: Set<Type> = 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<String>(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<String>()
|
||||
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<Flag>()
|
||||
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())
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
48
src/main/kotlin/net/thauvin/erik/jokeapi/JokeException.kt
Normal file
48
src/main/kotlin/net/thauvin/erik/jokeapi/JokeException.kt
Normal file
|
@ -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<String>,
|
||||
val additionalInfo: String,
|
||||
val timestamp: Long,
|
||||
cause: Throwable? = null
|
||||
) : Exception(message, cause) {
|
||||
companion object {
|
||||
private const val serialVersionUID = 1L
|
||||
}
|
||||
}
|
51
src/main/kotlin/net/thauvin/erik/jokeapi/Language.kt
Normal file
51
src/main/kotlin/net/thauvin/erik/jokeapi/Language.kt
Normal file
|
@ -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)
|
||||
}
|
41
src/main/kotlin/net/thauvin/erik/jokeapi/Type.kt
Normal file
41
src/main/kotlin/net/thauvin/erik/jokeapi/Type.kt
Normal file
|
@ -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")
|
||||
}
|
174
src/test/kotlin/net/thauvin/erik/jokeapi/JokeApiTest.kt
Normal file
174
src/test/kotlin/net/thauvin/erik/jokeapi/JokeApiTest.kt
Normal file
|
@ -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("<?xml version='1.0'?>\n<data>\n <error>false</error>"), "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
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue