Skip to content
This repository has been archived by the owner on Nov 22, 2020. It is now read-only.

Commit

Permalink
Merge pull request #18 from ToxicMushroom/master
Browse files Browse the repository at this point in the history
Changed logger implementation to be and actual api logger
  • Loading branch information
GSculerlor committed May 20, 2020
2 parents 2a34df2 + ca82383 commit dfe93db
Show file tree
Hide file tree
Showing 12 changed files with 446 additions and 231 deletions.
111 changes: 55 additions & 56 deletions build.gradle.kts
Original file line number Diff line number Diff line change
@@ -1,57 +1,56 @@
plugins {
kotlin("jvm") version "1.3.61"
maven
}

repositories {
mavenCentral()
jcenter()
maven("https://kotlin.bintray.com/ktor")
maven("https://kotlin.bintray.com/kotlinx")
}

group = "com.github.GSculerlor"
version = "1.3.0"

val ktorVersion: String by project
val gsonVersion: String by project
val coroutinesVersion: String by project

dependencies {
implementation(kotlin("stdlib-jdk8"))

//Coroutines
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutinesVersion")
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-jdk8:$coroutinesVersion")

//Ktor
implementation("io.ktor:ktor-client-core:$ktorVersion")
implementation("io.ktor:ktor-client-core-jvm:$ktorVersion")
implementation("io.ktor:ktor-client-json:$ktorVersion")
implementation("io.ktor:ktor-client-json-jvm:$ktorVersion")
implementation("io.ktor:ktor-client-okhttp:$ktorVersion")
implementation("io.ktor:ktor-client-gson:$ktorVersion")

//Gson
implementation("com.google.code.gson:gson:$gsonVersion")

//kotlin-logging
implementation("io.github.microutils:kotlin-logging:1.7.7")
implementation("org.slf4j:slf4j-simple:1.7.26")

testImplementation("org.junit.jupiter:junit-jupiter-api:5.3.1")
testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:5.3.1")
}

tasks {
compileKotlin {
kotlinOptions.jvmTarget = "1.8"
}
compileTestKotlin {
kotlinOptions.jvmTarget = "1.8"
}

test {
useJUnitPlatform()
}
plugins {
kotlin("jvm") version "1.3.72"
maven
}

repositories {
mavenCentral()
jcenter()
maven("https://kotlin.bintray.com/ktor")
maven("https://kotlin.bintray.com/kotlinx")
}

group = "com.github.GSculerlor"
version = "1.3.0"

val ktorVersion: String by project
val gsonVersion: String by project
val coroutinesVersion: String by project

dependencies {
implementation(kotlin("stdlib-jdk8"))

//Coroutines
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutinesVersion")
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-jdk8:$coroutinesVersion")

//Ktor
implementation("io.ktor:ktor-client-core:$ktorVersion")
implementation("io.ktor:ktor-client-core-jvm:$ktorVersion")
implementation("io.ktor:ktor-client-json:$ktorVersion")
implementation("io.ktor:ktor-client-json-jvm:$ktorVersion")
implementation("io.ktor:ktor-client-okhttp:$ktorVersion")
implementation("io.ktor:ktor-client-gson:$ktorVersion")

//Gson
implementation("com.google.code.gson:gson:$gsonVersion")

//kotlin-logging
api("org.slf4j:slf4j-api:1.7.25")

testImplementation("org.junit.jupiter:junit-jupiter-api:5.3.1")
testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:5.3.1")
}

tasks {
compileKotlin {
kotlinOptions.jvmTarget = "1.8"
}
compileTestKotlin {
kotlinOptions.jvmTarget = "1.8"
}

test {
useJUnitPlatform()
}
}
2 changes: 1 addition & 1 deletion gradle.properties
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@ kotlin.code.style=official

ktorVersion=1.3.2
gsonVersion=2.8.6
coroutinesVersion=1.3.5
coroutinesVersion=1.3.6
8 changes: 4 additions & 4 deletions src/main/kotlin/moe/ganen/jikankt/JikanClient.kt
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@ import io.ktor.client.HttpClient
import io.ktor.client.engine.okhttp.OkHttp
import io.ktor.client.features.json.GsonSerializer
import io.ktor.client.features.json.JsonFeature
import mu.KotlinLogging
import moe.ganen.jikankt.utils.JikanLogger
import okhttp3.Protocol
import org.slf4j.Logger

open class JikanClient {
protected val httpClient by lazy {
Expand All @@ -26,14 +27,13 @@ open class JikanClient {
}
}

protected val logger = KotlinLogging.logger(JIKANKT_NAME)

init {
logger.info { "Initialize $JIKANKT_NAME version $JIKANKT_VERSION" }
JIKANKT_LOG.info("Initialize $JIKANKT_NAME version $JIKANKT_VERSION")
}

companion object {
private const val JIKANKT_NAME = "JikanKt"
private const val JIKANKT_VERSION = "1.3.0"
val JIKANKT_LOG: Logger = JikanLogger().getLog(JIKANKT_NAME)
}
}
2 changes: 2 additions & 0 deletions src/main/kotlin/moe/ganen/jikankt/JikanKt.kt
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,11 @@ import moe.ganen.jikankt.utils.InterfaceAdapter
import moe.ganen.jikankt.utils.deserialize

object JikanKt {

var restClient = RestClient()
private val gson = GsonBuilder().registerTypeAdapter(Entity::class.java, InterfaceAdapter<Entity>()).create()


//region Anime

/**
Expand Down
186 changes: 93 additions & 93 deletions src/main/kotlin/moe/ganen/jikankt/connection/RestClient.kt
Original file line number Diff line number Diff line change
@@ -1,94 +1,94 @@
package moe.ganen.jikankt.connection

import com.google.gson.Gson
import com.google.gson.JsonElement
import com.google.gson.JsonObject
import io.ktor.client.request.get
import io.ktor.client.request.header
import io.ktor.client.statement.HttpResponse
import io.ktor.client.statement.readText
import io.ktor.http.HttpHeaders
import moe.ganen.jikankt.JikanClient
import moe.ganen.jikankt.exception.JikanException

/**
* Class that handle request.
* @param isDebug: a boolean that indicate if you run it on debug or not. If yes, it'll throw exception if something happen.
* @param url: Custom URL, will use default (Jikan URL) if null or empty.
*/
class RestClient(private val isDebug: Boolean = false, private val url: String? = null) : JikanClient() {
private val client = httpClient
private val gson = Gson()

private val usedURL = if (url.isNullOrEmpty()) BASE_URL else url

suspend fun request(endPoint: String, data: JsonObject? = null): JsonElement {
try {
var url = usedURL + endPoint
if (data != null) {
url += "?" + data.entrySet().joinToString("&") { entry ->
"${entry.key}=${entry.value}"
}
}

logger.info { "Requesting to Jikan: $url" }


val response = client.get<HttpResponse>(url) {
header(HttpHeaders.Accept, "application/json")
}

val contentType = response.headers["Content-Type"]
val body = response.readText()

val json = if (contentType?.equals("application/json", true) == true) {
gson.fromJson(body, JsonElement::class.java)
} else {
null
}

logger.debug("Response from Jikan: ${response.status.value}, body: $json")

if (response.status.value !in 200..299) {
if (response.status.value in 500..599) {
val ex = Exception("An internal server error has occurred, code: ${response.status.value}")
if (isDebug)
throw ex
else
exceptionHandler(ex)
} else {
val ex = JikanException(
"Jikan API returns code ${response.status.value} and body ${json?.toString()}",
response.status.value
)

if (isDebug)
throw ex
else
exceptionHandler(ex)
}
}

return json ?: JsonObject()
} catch (ex: Exception) {
if (!isDebug) {
return exceptionHandler(ex, "An unexpected error has occurred!")
} else
throw ex
}
}

private fun exceptionHandler(ex: java.lang.Exception, message: String? = null) : JsonObject {
if (message.isNullOrEmpty())
logger.error { "Something went wrong! Exception: ${ex.localizedMessage}" }
else
logger.error(ex) { message }

//Will return empty json object instead
return JsonObject()
}

companion object {
private const val BASE_URL = "https://api.jikan.moe/v3/"
}
package moe.ganen.jikankt.connection

import com.google.gson.Gson
import com.google.gson.JsonElement
import com.google.gson.JsonObject
import io.ktor.client.request.get
import io.ktor.client.request.header
import io.ktor.client.statement.HttpResponse
import io.ktor.client.statement.readText
import io.ktor.http.HttpHeaders
import moe.ganen.jikankt.JikanClient
import moe.ganen.jikankt.exception.JikanException

/**
* Class that handle request.
* @param isDebug: a boolean that indicate if you run it on debug or not. If yes, it'll throw exception if something happen.
* @param url: Custom URL, will use default (Jikan URL) if null or empty.
*/
class RestClient(private val isDebug: Boolean = false, private val url: String? = null) : JikanClient() {
private val client = httpClient
private val gson = Gson()

private val usedURL = if (url.isNullOrEmpty()) BASE_URL else url

suspend fun request(endPoint: String, data: JsonObject? = null): JsonElement {
try {
var url = usedURL + endPoint
if (data != null) {
url += "?" + data.entrySet().joinToString("&") { entry ->
"${entry.key}=${entry.value}"
}
}

JIKANKT_LOG.info("Requesting to Jikan: $url")


val response = client.get<HttpResponse>(url) {
header(HttpHeaders.Accept, "application/json")
}

val contentType = response.headers["Content-Type"]
val body = response.readText()

val json = if (contentType?.equals("application/json", true) == true) {
gson.fromJson(body, JsonElement::class.java)
} else {
null
}

JIKANKT_LOG.debug("Response from Jikan: ${response.status.value}, body: $json")

if (response.status.value !in 200..299) {
if (response.status.value in 500..599) {
val ex = Exception("An internal server error has occurred, code: ${response.status.value}")
if (isDebug)
throw ex
else
exceptionHandler(ex)
} else {
val ex = JikanException(
"Jikan API returns code ${response.status.value} and body ${json?.toString()}",
response.status.value
)

if (isDebug)
throw ex
else
exceptionHandler(ex)
}
}

return json ?: JsonObject()
} catch (ex: Exception) {
if (!isDebug) {
return exceptionHandler(ex, "An unexpected error has occurred!")
} else
throw ex
}
}

private fun exceptionHandler(ex: Exception, message: String? = null) : JsonObject {
if (message.isNullOrEmpty())
JIKANKT_LOG.error("Something went wrong! Exception: ${ex.localizedMessage}")
else
JIKANKT_LOG.error(message, ex)

//Will return empty json object instead
return JsonObject()
}

companion object {
const val BASE_URL = "https://api.jikan.moe/v3/"
}
}

0 comments on commit dfe93db

Please sign in to comment.