diff --git a/src/main/kotlin/org/web3j/quorum/enclave/EnclaveClientConnectionException.kt b/src/main/kotlin/org/web3j/quorum/enclave/EnclaveClientConnectionException.kt new file mode 100644 index 0000000..aa0f51a --- /dev/null +++ b/src/main/kotlin/org/web3j/quorum/enclave/EnclaveClientConnectionException.kt @@ -0,0 +1,5 @@ +package org.web3j.quorum.enclave + +import org.web3j.protocol.exceptions.ClientConnectionException + +class EnclaveClientConnectionException(message: String) : ClientConnectionException(message) \ No newline at end of file diff --git a/src/main/kotlin/org/web3j/quorum/enclave/protocol/http/EnclaveHttpService.kt b/src/main/kotlin/org/web3j/quorum/enclave/protocol/http/EnclaveHttpService.kt index b458eb4..27c3e24 100644 --- a/src/main/kotlin/org/web3j/quorum/enclave/protocol/http/EnclaveHttpService.kt +++ b/src/main/kotlin/org/web3j/quorum/enclave/protocol/http/EnclaveHttpService.kt @@ -5,26 +5,26 @@ import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper import org.web3j.quorum.enclave.protocol.EnclaveService import okhttp3.* import okhttp3.OkHttpClient +import org.web3j.quorum.enclave.EnclaveClientConnectionException /** * EnclaveHttpService implements send methods that support communication with the private enclave via Http. * Currently Http communication is only supported in Tessera. */ -class EnclaveHttpService(private val url: String, private val port: Int) : EnclaveService { +class EnclaveHttpService(private val url: String, private val port: Int, private val client: OkHttpClient = OkHttpClient()) : EnclaveService { private val objectMapper = jacksonObjectMapper() .setSerializationInclusion(JsonInclude.Include.NON_NULL) - private val JSON = MediaType.parse("application/json; charset=utf-8") + private val JSON_MEDIA_TYPE = MediaType.parse("application/json; charset=utf-8") /** * Send a new raw payload to Enclave */ override fun send(request: S, path: String, responseType: Class): T { val payload = objectMapper.writeValueAsString(request) - val client = OkHttpClient() val uri = "$url:$port/$path" - val body = RequestBody.create(JSON, objectMapper.writeValueAsString(payload)) + val body = RequestBody.create(JSON_MEDIA_TYPE, payload) val request = Request.Builder() .url(uri) .post(body) @@ -32,8 +32,15 @@ class EnclaveHttpService(private val url: String, private val port: Int) : Encla val response = client.newCall(request).execute() - val chunk = response.body().toString() - return objectMapper.readValue(chunk, responseType) + if(response.isSuccessful) { + val chunk = response.body()?.string() + return objectMapper.readValue(chunk, responseType) + } else { + val statusCode = response.code() + val text = if (response.body() == null) "N/A" else response.body()?.string() + + throw EnclaveClientConnectionException("Invalid response received from enclave: $statusCode $text") + } } /**