summaryrefslogtreecommitdiff
path: root/opendc-common/src/main/kotlin/org/opendc/common/utils/HTTPClient.kt
blob: cc89d48f4a514c7c9e2c238daa74096909675103 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package org.opendc.common.utils

import java.io.File
import java.net.URI
import java.net.http.*
import java.net.http.HttpResponse.BodyHandlers.ofString
/**
 * Singleton class representing the real datacenter client.
 * The client is asynchronous and initiates the connection first.
 *
 * @constructor Initiates the connection.
 *
 * @author Mateusz Kwiatkowski
 */

public class HTTPClient private constructor() {
    public companion object {
        private var instance: HTTPClient? = null
        private var client: HttpClient? = null
        private var handshake = HttpRequest.newBuilder()
            .uri(URI.create("http://localhost:8080/"))
            .build()

        public fun getInstance(): HTTPClient? {
            if (instance == null) {
                try {
                    client = HttpClient.newBuilder().build()
                    val response = client?.send(handshake, ofString())
                    check(response?.statusCode() == 200)
                } catch (e: IllegalStateException) {
                    println("${e.message}")
                }
                instance = HTTPClient()
            }
            return instance
        }
    }

    // TODO: this class must send the experiment JSON file to the digital twin
    public fun sendExperiment(experiment: File) {
        val body : HttpRequest.BodyPublisher
        val request = HttpRequest.newBuilder()
            .uri(URI.create("http://localhost:8080/"))
            .header("Content-type", "application/json")
            // TODO: this is obviously wrong, find an efficient way to send JSON over network
            .POST(HttpRequest.BodyPublishers.ofString(experiment))
            .build()
        println("Haha")
    }
}