Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 6 additions & 7 deletions build.gradle
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import org.apache.tools.ant.filters.ReplaceTokens

plugins {
id 'org.jetbrains.kotlin.jvm' version '1.6.0'
id 'org.jetbrains.kotlin.jvm' version '1.6.10'
id 'maven-publish'
id 'com.github.johnrengelman.shadow' version '7.1.0'
id 'com.github.johnrengelman.shadow' version '7.1.2'
id 'org.jetbrains.dokka' version '1.6.0'
}

Expand All @@ -23,16 +23,15 @@ repositories {
maven { url 'https://oss.sonatype.org/content/repositories/releases/' }
maven { url 'https://oss.sonatype.org/content/groups/public/' }
maven { url 'https://hub.spigotmc.org/nexus/content/repositories/snapshots/' }
maven { url 'https://repo.codemc.org/repository/maven-public' }
maven { url 'https://repo.codemc.org/repository/nms' }
maven { url 'https://jitpack.io' }
maven { url 'https://repo.codemc.org/repository/maven-public/' }
maven { url 'https://jitpack.io/' }
}

dependencies {
compileOnly 'org.jetbrains.kotlin:kotlin-stdlib:1.6.0'
compileOnly 'org.jetbrains.kotlin:kotlin-stdlib:1.6.10'
compileOnly 'org.spigotmc:spigot-api:1.18.1-R0.1-SNAPSHOT'
compileOnly 'net.md-5:bungeecord-api:1.18-R0.1-SNAPSHOT'
compileOnly 'xyz.theprogramsrc:simplecoreapi:0.1.9-SNAPSHOT'
compileOnly 'xyz.theprogramsrc:simplecoreapi:0.1.12-SNAPSHOT'

testImplementation 'org.junit.jupiter:junit-jupiter:5.8.2'
}
Expand Down
3 changes: 3 additions & 0 deletions src/main/kotlin/xyz/theprogramsrc/networkingmodule/Main.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
package xyz.theprogramsrc.networkingmodule

class Main
121 changes: 121 additions & 0 deletions src/main/kotlin/xyz/theprogramsrc/networkingmodule/builder/Request.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
package xyz.theprogramsrc.networkingmodule.builder

import xyz.theprogramsrc.networkingmodule.objects.Response
import java.net.HttpURLConnection
import java.net.URL

/**
* This class is used to build a request
* @param url The url of the request
*/
class Request(val url: String){

/**
* The method of the request.
* Defaults to GET
*/
var method: String = "GET"

/**
* The headers of the request.
* Defaults to map with User-Agent
*/
var headers: MutableMap<String, String> = mutableMapOf(
"User-Agent" to "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36"
)

/**
* The body of the request. (Set to empty string to ignore).
* Defaults to empty string
*/
var body: String = ""

/**
* The timeout of the request (Set to -1 to disable).
* Defaults to -1
*/
var timeout: Int = -1

/**
* True if the request should use the cache, false otherwise.
* Defaults to true
*/
var useCache: Boolean = true

/**
* Sets the request method to GET
* @return this
*/
fun get() = this.apply { method = "GET" }

/**
* Sets the request method to POST
* @return this
*/
fun post() = this.apply { method = "POST" }

/**
* Sets the request method to PUT
* @return this
*/
fun put() = this.apply { method = "PUT" }

/**
* Sets the request method to DELETE
* @return this
*/
fun delete() = this.apply { method = "DELETE" }

/**
* Sets the body of the request
* @param body The body of the request
* @return this
*/
fun body(body: String) = this.apply { this.body = body }

/**
* Sets the timeout of the request
* @param timeout The timeout of the request. (Set to -1 to disable)
* @return this
*/
fun timeout(timeout: Int) = this.apply { this.timeout = timeout }

/**
* Sets the header of the request. If the header already exists, it will be overwritten
* @param key The key of the header
* @param value The value of the header
* @return this
*/
fun header(key: String, value: String) = this.apply { headers[key] = value }

/**
* Sets if the request should use the cache
* @param useCache True if the request should use the cache, false otherwise
* @return this
*/
fun useCache(useCache: Boolean) = this.apply { this.useCache = useCache }

/**
* Sends the request and returns a response
* @return the [Response]
*/
fun connect(): Response {
val url = URL(
if(this.method == "GET" && this.body.isNotBlank()) {
"${this.url}?${this.body}"
} else {
this.url
}
)
val connection = url.openConnection() as HttpURLConnection
connection.requestMethod = this.method
connection.doOutput = this.method == "POST" || this.method == "PUT" || (this.body.isNotBlank() && this.method != "GET")
connection.doInput = true
connection.useCaches = this.useCache
if(this.timeout != -1) connection.connectTimeout = this.timeout
if(this.timeout != -1) connection.readTimeout = this.timeout
this.headers.forEach { connection.setRequestProperty(it.key, it.value) }
if(this.body.isNotEmpty() && this.method != "GET") connection.outputStream.write(this.body.toByteArray())
return Response(connection)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
package xyz.theprogramsrc.networkingmodule.objects

import java.io.InputStream
import java.net.HttpURLConnection

class Response(val connection: HttpURLConnection) {

/**
* The expected response code
*/
var expectedStatusCode: Int = 200

/**
* Checks if the status code is the same as the expected status code
* @return true if the status code is the same as the expected status code
*/
fun wasSuccessful(): Boolean = connection.responseCode == expectedStatusCode

/**
* Gets the status code
* @return the status code
*/
fun getStatusCode(): Int = connection.responseCode

/**
* Gets the response message
* @return the response message
*/
fun getResponseMessage(): String = connection.responseMessage

/**
* Gets the response stream
* @return the response stream
*/
fun getResponseStream(): InputStream = connection.inputStream

/**
* Gets the response string
* @return the response string
*/
fun getResponseString(): String = connection.inputStream.bufferedReader().use { it.readText() }

/**
* Gets the response headers
* @return the response headers
*/
fun getResponseHeaders(): Map<String, List<String>> = connection.headerFields

/**
* Gets the response header
* @return the response header
*/
fun getResponseHeader(header: String): String? = connection.headerFields[header]?.get(0)

/**
* Gets the response header
* @return the response header
*/
fun getResponseHeader(header: String, index: Int): String? = connection.headerFields[header]?.get(index)

/**
* Gets the response header count
* @return the response header count
*/
fun getResponseHeaderCount(header: String): Int = connection.headerFields[header]?.size ?: 0

/**
* Gets the response header names
* @return the response header names
*/
fun getResponseHeaderNames(): List<String> = connection.headerFields.keys.toList()

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
package xyz.theprogramsrc.networkingmodule.builder

import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
import xyz.theprogramsrc.simplecoreapi.libs.google.gson.JsonObject
import xyz.theprogramsrc.simplecoreapi.libs.google.gson.JsonParser

@DisplayName("Http Requests Test")
internal class RequestTest {

@Nested
@DisplayName("GET Request")
inner class GetRequest {

@Test fun getRequest() = assertTrue(
Request("https://httpbin.org/get")
.get()
.connect()
.wasSuccessful()
)

}

@Nested
@DisplayName("POST Request")
inner class PostRequest {

@Test fun postRequest() = assertTrue(
Request("https://httpbin.org/post")
.post()
.connect()
.wasSuccessful()
)

}

@Nested
@DisplayName("PUT Request")
inner class PutRequest {

@Test fun putRequest() = assertTrue(
Request("https://httpbin.org/put")
.put()
.connect()
.wasSuccessful()
)

}

@Nested
@DisplayName("DELETE Request")
inner class DeleteRequest {

@Test fun deleteRequest() = assertTrue(
Request("https://httpbin.org/delete")
.delete()
.connect()
.wasSuccessful()
)

}

@Nested
@DisplayName("Headers and Body Request")
inner class HeadersAndBodyRequest {

@Test fun headersRequest() {
val response = Request("https://httpbin.org/get")
.get()
.header("Accept", "application/json")
.header("My-Test-Header", "My-Test-Value")
.connect()
val json = JsonParser.parseString(response.getResponseString()).asJsonObject
val headers = json.getAsJsonObject("headers")
assertEquals("application/json", headers.get("Accept").asString)
assertEquals("My-Test-Value", headers.get("My-Test-Header").asString)
}

@Test fun bodyRequest() {
val response = Request("https://httpbin.org/get")
.get()
.body("argument=value&argument2=value2")
.connect()
val json = JsonParser.parseString(response.getResponseString()).asJsonObject
val args = json.getAsJsonObject("args")
assertEquals("value", args.get("argument").asString)
assertEquals("value2", args.get("argument2").asString)
}

}


}