├── settings.gradle ├── src └── main │ └── kotlin │ └── pl │ └── qus │ └── qotlin │ ├── model │ ├── QACalibration.kt │ ├── QAError.kt │ ├── QALoginResponse.kt │ ├── QAsm.kt │ ├── QAResult.kt │ ├── QAJob.kt │ ├── QADevice.kt │ └── QARetrofitInterface.kt │ ├── Main.kt │ ├── QAssmeblerDSL.kt │ └── Qotlin.kt ├── .gitignore ├── README.md └── LICENSE /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'qasm' 2 | 3 | -------------------------------------------------------------------------------- /src/main/kotlin/pl/qus/qotlin/model/QACalibration.kt: -------------------------------------------------------------------------------- 1 | package pl.qus.qotlin.model 2 | 3 | class QACalibration { 4 | var stub: Any? = null 5 | } 6 | -------------------------------------------------------------------------------- /src/main/kotlin/pl/qus/qotlin/model/QAError.kt: -------------------------------------------------------------------------------- 1 | package pl.qus.qotlin.model 2 | 3 | class QAError { 4 | val name: String = "" 5 | var status: Int = 0 6 | var message: String = "" 7 | val statusCode: Int = 0 8 | var code: String = "" 9 | } 10 | -------------------------------------------------------------------------------- /src/main/kotlin/pl/qus/qotlin/model/QALoginResponse.kt: -------------------------------------------------------------------------------- 1 | package pl.qus.qotlin.model 2 | 3 | import java.util.* 4 | 5 | class QALoginResponse { 6 | val id : String = "" 7 | val ttl : Long = 0L 8 | val created : Date? = null 9 | val userId : String = "" 10 | val error : QAError? = null 11 | } -------------------------------------------------------------------------------- /src/main/kotlin/pl/qus/qotlin/model/QAsm.kt: -------------------------------------------------------------------------------- 1 | package pl.qus.qotlin.model 2 | 3 | open class QAsm ( 4 | var qasm: String = "", 5 | val status : QasmStatus? = null, 6 | val executionId : String = "", 7 | val result : QAResult? = null 8 | ) 9 | 10 | enum class QasmStatus { 11 | DONE, WORK_IN_PROGRESS 12 | } 13 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled class file 2 | *.class 3 | 4 | # Log file 5 | *.log 6 | 7 | # BlueJ files 8 | *.ctxt 9 | 10 | # Mobile Tools for Java (J2ME) 11 | .mtj.tmp/ 12 | 13 | # Package Files # 14 | *.jar 15 | *.war 16 | *.nar 17 | *.ear 18 | *.zip 19 | *.tar.gz 20 | *.rar 21 | 22 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 23 | hs_err_pid* 24 | -------------------------------------------------------------------------------- /src/main/kotlin/pl/qus/qotlin/model/QAResult.kt: -------------------------------------------------------------------------------- 1 | package pl.qus.qotlin.model 2 | 3 | import com.google.gson.annotations.SerializedName 4 | 5 | import java.util.Date 6 | 7 | 8 | class QAResult { 9 | var date: Date? = null 10 | var data: QAData? = null 11 | 12 | override fun toString(): String { 13 | return "$date\n$data" 14 | } 15 | } 16 | 17 | class QAData { 18 | @SerializedName("creg_labels") 19 | var cregLabels: String = "" 20 | var additionalData: QAAdditional? = null 21 | var time: Double = 0.toDouble() 22 | var counts: Map? = null 23 | 24 | override fun toString(): String { 25 | return "$cregLabels time=$time counts=$counts" 26 | } 27 | } 28 | 29 | class QAAdditional { 30 | internal var seed: Long = 0 31 | } 32 | -------------------------------------------------------------------------------- /src/main/kotlin/pl/qus/qotlin/model/QAJob.kt: -------------------------------------------------------------------------------- 1 | package pl.qus.qotlin.model 2 | 3 | import pl.qus.qotlin.Qotlin 4 | import java.util.* 5 | 6 | open class QAJob ( 7 | var backend: QADevice? = null, 8 | var shots: Int = 0, 9 | var maxCredits: Int = 0, 10 | val qasms : List? = null, 11 | val status : StatusEnum? = null, 12 | val usedCredits : Int = 0, 13 | val creationDate : Date? = null, 14 | val id : String = "", 15 | val userId : String = "", 16 | var deleted: Boolean = false, 17 | var calibration: QACalibration? = null, 18 | var error : QAError? = null, 19 | @Transient 20 | var api: Qotlin? = null 21 | ) { 22 | override fun toString(): String { 23 | return "$backend, id:$id, status:$status" 24 | } 25 | 26 | fun onStatus(timeoutSeconds : Int,onCompleted: (QAJob) -> Unit, 27 | onError: (Throwable) -> Unit = {}) { 28 | api?.onJobStatus(this,timeoutSeconds,onCompleted,onError) ?: throw(IllegalStateException("You have to obtain QAJob instance from submitJob method")) 29 | } 30 | } 31 | 32 | enum class StatusEnum { 33 | RUNNING, COMPLETED 34 | } -------------------------------------------------------------------------------- /src/main/kotlin/pl/qus/qotlin/model/QADevice.kt: -------------------------------------------------------------------------------- 1 | package pl.qus.qotlin.model 2 | 3 | import pl.qus.qotlin.Qotlin 4 | import java.util.Date 5 | 6 | class QADevice(var name: String) { 7 | var status: QADeviceStatus? = null 8 | var serialNumber: String = "" 9 | var description: String = "" 10 | var id: String = "" 11 | var topologyId: String = "" 12 | var simulator: Boolean = false 13 | var nQubits: Int = 0 14 | //var couplingMap: Array? = null // TODO - can't decode as it is either array or string 15 | 16 | var chipName: String = "" 17 | var onlineDate: Date? = null 18 | var gateSet: String = "" 19 | var basisGates: String = "" 20 | var version: String = "" 21 | var url: String = "" 22 | var allowQObject: Boolean = false 23 | 24 | @Transient 25 | var api: Qotlin? = null 26 | 27 | override fun toString(): String { 28 | return "$name - $description, status: $status, real:${!simulator}, qbits:$nQubits, gates:$basisGates" 29 | } 30 | 31 | fun submitJob(shots: Int = 1, maxCredits: Int = 1, vararg sources: QAsm): QAJob { 32 | val job = QAJob(backend = this,shots = shots, maxCredits = maxCredits, qasms = listOf(*sources)) 33 | return api?.submitJob(job)?.apply { 34 | this.api = this@QADevice.api 35 | } ?: throw(IllegalStateException("You have to obtain device instance from Qotlin instance")) 36 | } 37 | 38 | } 39 | 40 | enum class QADeviceStatus { 41 | on, off, standby 42 | } -------------------------------------------------------------------------------- /src/main/kotlin/pl/qus/qotlin/Main.kt: -------------------------------------------------------------------------------- 1 | package pl.qus.qotlin 2 | 3 | object Main { 4 | @JvmStatic 5 | fun main(args: Array) { 6 | val qex = Qotlin() 7 | 8 | qex.login("YOUR_API_TOKEN_HERE") 9 | 10 | qex.enumerateDevices() 11 | 12 | println("Currently available:") 13 | qex.devices.forEach { 14 | println(it) 15 | } 16 | 17 | println("\nRunning Bell state experiment") 18 | qex.simulator 19 | .submitJob(256, 1, qasm { 20 | qreg(2) 21 | creg(5) 22 | h(0) 23 | cx(0, 1) 24 | measure(0, 1) 25 | measure(1, 1) 26 | }) 27 | .onStatus(60, 28 | { 29 | finishedJob -> 30 | finishedJob.qasms?.forEach { 31 | qasm -> 32 | println(qasm.result) 33 | } 34 | }, 35 | { 36 | println("Job failed") 37 | } 38 | ) 39 | 40 | println("Running quantum Fourier transform") 41 | //qex.devices.firstOrNull { !it.simulator } 42 | qex.simulator 43 | ?.submitJob(256,100, qasm { 44 | // quantum Fourier transform 45 | qreg(4) 46 | creg(4) 47 | x(0) 48 | x(2) 49 | barrier() 50 | h(0) 51 | cu1(Math.PI/2,1,0) 52 | h(1) 53 | cu1(Math.PI/4,2,0) 54 | cu1(Math.PI/2,2,1) 55 | h(2) 56 | cu1(Math.PI/8,3,0) 57 | cu1(Math.PI/4,3,1) 58 | cu1(Math.PI/2,3,2) 59 | h(3) 60 | measure() 61 | }) 62 | ?.onStatus(500,{ 63 | finishedJob -> 64 | finishedJob.qasms?.forEach { 65 | qasm -> 66 | println(qasm.result) 67 | } 68 | },{ 69 | 70 | }) 71 | 72 | } 73 | } -------------------------------------------------------------------------------- /src/main/kotlin/pl/qus/qotlin/model/QARetrofitInterface.kt: -------------------------------------------------------------------------------- 1 | package pl.qus.qotlin.model 2 | 3 | import pl.qus.qotlin.model.Const.HD_CLIENT_APP 4 | import pl.qus.qotlin.model.Const.HD_ENCODING 5 | import pl.qus.qotlin.model.Const.HD_JSON 6 | import pl.qus.qotlin.model.Const.HD_USER_AGENT 7 | import retrofit2.Call 8 | import retrofit2.http.* 9 | import retrofit2.http.Body 10 | 11 | object Const { 12 | const val HD_USER_AGENT = "User-Agent:python-requests/2.18.4" 13 | const val HD_CLIENT_APP = "x-qx-client-application:qiskit-api-py" 14 | const val HD_ENCODING = "Accept-Encoding:identity" 15 | const val HD_JSON = "Content-Type:application/json" 16 | } 17 | 18 | interface QARetrofitInterface { 19 | /** 20 | * Logs in to the server. Creates an access token for the current session. 21 | * 22 | * @return an access token - z pola id 23 | */ 24 | @Headers( 25 | HD_USER_AGENT, 26 | HD_CLIENT_APP, 27 | HD_ENCODING 28 | ) 29 | @FormUrlEncoded 30 | @POST("api/users/loginWithToken") 31 | fun login( 32 | @Field("apiToken") apiToken : String 33 | ) : Call 34 | 35 | /** 36 | * Returns the devices (backends) on the server. 37 | * 38 | * @return a map of devices keyed with their names, null for none 39 | */ 40 | 41 | @Headers( 42 | HD_USER_AGENT, 43 | HD_CLIENT_APP, 44 | HD_ENCODING 45 | ) 46 | @GET("api/backends") 47 | fun listDevices( 48 | @Query("access_token") accessToken : String 49 | ) : Call> 50 | 51 | /** 52 | * Sends a new job. 53 | * 54 | * @param newJob a new job, with one or more tasks 55 | * @return the jobs just sent, with new ids attached 56 | */ 57 | @Headers( 58 | HD_USER_AGENT, 59 | HD_CLIENT_APP, 60 | HD_ENCODING, 61 | HD_JSON 62 | ) 63 | @POST("api/Jobs") 64 | fun sendJob( 65 | @Query("access_token") accessToken: String, 66 | @Body newJob: QAJob 67 | ) : Call 68 | 69 | /** 70 | * Receives a given job from the server, with its status and possible computation results. 71 | * 72 | * @param job a job to fetch from the server 73 | * @return a description of the same job, with its current status and a possible result 74 | */ 75 | @Headers( 76 | HD_USER_AGENT, 77 | HD_CLIENT_APP, 78 | HD_ENCODING 79 | ) 80 | @GET("api/Jobs/{jobId}") 81 | fun receiveJob( 82 | @Path("jobId") jobId: String, 83 | @Query("access_token") accessToken : String 84 | ): Call 85 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Qotlin 2 | 3 | This is a Kotlin library for developing, deploying and running quantum assembler (QASM) programs on quantum computers available in IBM Q Experience program. 4 | 5 | See below to get a taste: 6 | 7 | ```kotlin 8 | object Main { 9 | @JvmStatic 10 | fun main(args: Array) { 11 | val qex = Qotlin() 12 | 13 | qex.login("YOUR_API_TOKEN_HERE") 14 | 15 | qex.enumerateDevices() 16 | 17 | println("Currently available:") 18 | qex.devices.forEach { 19 | println(it) 20 | } 21 | 22 | println("\nRunning Bell state experiment") 23 | qex.simulator 24 | .submitJob(256, 1, qasm { 25 | qreg(2) 26 | creg(5) 27 | h(0) 28 | cx(0, 1) 29 | measure(0, 1) 30 | measure(1, 1) 31 | }) 32 | .onStatus(60, 33 | { 34 | finishedJob -> 35 | finishedJob.qasms?.forEach { 36 | qasm -> 37 | println(qasm.result) 38 | } 39 | }, 40 | { 41 | println("Job failed") 42 | } 43 | ) 44 | 45 | println("Running quantum Fourier transform") 46 | //qex.devices.firstOrNull { !it.simulator } 47 | qex.simulator 48 | ?.submitJob(256,100, qasm { 49 | // quantum Fourier transform 50 | qreg(4) 51 | creg(4) 52 | x(0) 53 | x(2) 54 | barrier() 55 | h(0) 56 | cu1(Math.PI/2,1,0) 57 | h(1) 58 | cu1(Math.PI/4,2,0) 59 | cu1(Math.PI/2,2,1) 60 | h(2) 61 | cu1(Math.PI/8,3,0) 62 | cu1(Math.PI/4,3,1) 63 | cu1(Math.PI/2,3,2) 64 | h(3) 65 | measure() 66 | }) 67 | ?.onStatus(500,{ 68 | finishedJob -> 69 | finishedJob.qasms?.forEach { 70 | qasm -> 71 | println(qasm.result) 72 | } 73 | },{ 74 | 75 | }) 76 | 77 | } 78 | } 79 | ``` 80 | 81 | ### Prerequisites 82 | 83 | Obtain an API key at (https://quantumexperience.ng.bluemix.net/qx/experience) 84 | 85 | ## Built With 86 | 87 | * [Gradle](https://gradle.org/) 88 | ## Authors 89 | 90 | * **ssuukk** - *Initial work* 91 | 92 | ## License 93 | 94 | This project is licensed under the Apache License - see the [LICENSE.md](LICENSE.md) file for details 95 | -------------------------------------------------------------------------------- /src/main/kotlin/pl/qus/qotlin/QAssmeblerDSL.kt: -------------------------------------------------------------------------------- 1 | package pl.qus.qotlin 2 | 3 | import pl.qus.qotlin.model.QAsm 4 | 5 | interface Element { 6 | fun render(builder: StringBuilder, indent: String) 7 | } 8 | 9 | 10 | fun QasmBody.measure(qreg: Int, creg: Int) { 11 | source+="measure q[$qreg] -> c[$creg];\n" 12 | } 13 | 14 | fun QasmBody.measure() { 15 | source+="measure q -> c;\n" 16 | } 17 | 18 | fun QasmBody.barrier() { 19 | source+="barrier q;\n" 20 | } 21 | 22 | fun QasmBody.barrier(qreg : Int) { 23 | source+="barrier q[$qreg];\n" 24 | } 25 | 26 | fun QasmBody.creg(count: Int) { 27 | source+="creg c[$count];\n" 28 | } 29 | 30 | fun QasmBody.qreg(count: Int) { 31 | source+="qreg q[$count];\n" 32 | } 33 | 34 | 35 | /** 36 | * 3-parameter 2-pulse single qubit gate 37 | */ 38 | fun QasmBody.u3(theta : Double, phi : Double, lambda : Double) { 39 | source+="u3 ($theta,$phi,$lambda);\n" 40 | } 41 | 42 | /** 43 | * 2-parameter 1-pulse single qubit gate 44 | */ 45 | fun QasmBody.u2(phi : Double, lambda : Double) { 46 | source+="u2 ($phi,$lambda);\n" 47 | } 48 | 49 | /** 50 | * 1-parameter 0-pulse single qubit gate 51 | */ 52 | fun QasmBody.u1(lambda : Double) { 53 | source+="u1 ($lambda);\n" 54 | } 55 | 56 | /** 57 | * Controlled-NOT 58 | * 59 | * May be used to entangle quantum states 60 | * 61 | * @param qreg1 source register 62 | * @param qreg2 destination register 63 | */ 64 | fun QasmBody.cx(qreg1: Int, qreg2: Int) { 65 | source+="cx q[$qreg1],q[$qreg2];\n" 66 | } 67 | 68 | /** 69 | * NOP 70 | * 71 | * Idle gate (identity) 72 | */ 73 | fun QasmBody.id(qreg: Int) { 74 | source+="id q[$qreg];\n" 75 | } 76 | 77 | /** 78 | * Pauli gate: bit-flip 79 | */ 80 | fun QasmBody.x(qreg: Int) { 81 | source+="x q[$qreg];\n" 82 | } 83 | 84 | /** 85 | * Pauli gate: bit and phase flip 86 | */ 87 | fun QasmBody.y(qreg: Int) { 88 | source+="y q[$qreg];\n" 89 | } 90 | 91 | /** 92 | * Pauli gate: phase flip 93 | */ 94 | fun QasmBody.z(qreg: Int) { 95 | source+="z q[$qreg];\n" 96 | } 97 | 98 | /** 99 | * Clifford gate: hadamard 100 | * 101 | * May be used to put qbit in superposition state or measure 102 | */ 103 | fun QasmBody.h(qreg: Int) { 104 | source+="h q[$qreg];\n" 105 | } 106 | 107 | /** 108 | * Clifford gate: sqrt(Z) phase gate 109 | */ 110 | fun QasmBody.s(qreg: Int) { 111 | source+="s q[$qreg];\n" 112 | } 113 | 114 | /** 115 | * Clifford gate: conjugate of sqrt(Z) 116 | */ 117 | fun QasmBody.sdg(qreg: Int) { 118 | source+="sdg q[$qreg];\n" 119 | } 120 | 121 | /** 122 | * C3 gate: sqrt(S) phase gate 123 | */ 124 | fun QasmBody.t(qreg: Int) { 125 | source+="t q[$qreg];\n" 126 | } 127 | 128 | /** 129 | * C3 gate: conjugate of sqrt(S) 130 | */ 131 | fun QasmBody.tdg(qreg: Int) { 132 | source+="tdg q[$qreg];\n" 133 | } 134 | 135 | /** 136 | * Rotation around X-axis 137 | */ 138 | fun QasmBody.rx(qreg: Int) { 139 | source+="rx q[$qreg];\n" 140 | } 141 | 142 | /** 143 | * rotation around Y-axis 144 | */ 145 | fun QasmBody.ry(qreg: Int) { 146 | source+="ry q[$qreg];\n" 147 | } 148 | 149 | /** 150 | * rotation around Z axis 151 | */ 152 | fun QasmBody.rz(qreg: Int) { 153 | source+="rz q[$qreg];\n" 154 | } 155 | 156 | /** 157 | * controlled-Phase 158 | */ 159 | fun QasmBody.cz(qreg1: Int, qreg2: Int) { 160 | source+="cz q[$qreg1],q[$qreg2];\n" 161 | } 162 | 163 | /** 164 | * controlled-Y 165 | */ 166 | fun QasmBody.cy(qreg1: Int, qreg2: Int) { 167 | source+="cy q[$qreg1],q[$qreg2];\n" 168 | } 169 | 170 | /** 171 | * controlled-H 172 | */ 173 | fun QasmBody.ch(qreg1: Int, qreg2: Int) { 174 | source+="ch q[$qreg1],q[$qreg2];\n" 175 | } 176 | 177 | /** 178 | * C3 gate: Toffoli 179 | */ 180 | fun QasmBody.ccx(qreg1: Int, qreg2: Int, qreg3: Int) { 181 | source+="ccx q[$qreg1],q[$qreg2],q[$qreg3];\n" 182 | } 183 | 184 | /** 185 | * controlled rz rotation 186 | */ 187 | fun QasmBody.crz(lambda: Double, qreg1: Int, qreg2: Int) { 188 | source+="crz ($lambda) q[$qreg1],q[$qreg2];\n" 189 | } 190 | 191 | /** 192 | * controlled phase rotation 193 | */ 194 | fun QasmBody.cu1(lambda: Double, qreg1: Int, qreg2: Int) { 195 | source+="cu1 ($lambda) q[$qreg1],q[$qreg2];\n" 196 | } 197 | 198 | /** 199 | * controlled-U 200 | * 201 | * implements controlled-U(theta,phi,lambda) with target t and control c 202 | */ 203 | fun QasmBody.cu3(theta : Double, phi : Double, lambda : Double) { 204 | source+="cu3 ($theta,$phi,$lambda);\n" 205 | } 206 | 207 | 208 | class TextElement(val text: String) : Element { 209 | override fun render(builder: StringBuilder, indent: String) { 210 | builder.append("$indent$text\n") 211 | } 212 | } 213 | 214 | class QasmBody { 215 | var source : String = "include \"qelib1.inc\";\n" 216 | } 217 | 218 | 219 | fun qasm(init: QasmBody.() -> Unit): QAsm { 220 | val html = QasmBody() 221 | html.init() 222 | return QAsm(html.source) 223 | } -------------------------------------------------------------------------------- /src/main/kotlin/pl/qus/qotlin/Qotlin.kt: -------------------------------------------------------------------------------- 1 | package pl.qus.qotlin 2 | 3 | import com.google.gson.GsonBuilder 4 | import okhttp3.* 5 | import okhttp3.logging.HttpLoggingInterceptor 6 | import pl.qus.qotlin.model.* 7 | import retrofit2.Retrofit 8 | import retrofit2.converter.gson.GsonConverterFactory 9 | import java.net.InetSocketAddress 10 | import java.net.Proxy 11 | import java.util.* 12 | import java.util.concurrent.TimeoutException 13 | 14 | /** 15 | * A connection layer to an IBM Quantum Experience server. 16 | */ 17 | open class Qotlin 18 | /** 19 | * Creates a session for a given user. 20 | * 21 | * @param apiToken api token of the user 22 | */ 23 | { 24 | /** 25 | * An access token for the current session. 26 | */ 27 | private var sessionToken: String = "" 28 | 29 | var devices = listOf() 30 | 31 | private val gson = GsonBuilder() 32 | .setLenient() 33 | .create() 34 | 35 | private val interceptor = HttpLoggingInterceptor().apply { 36 | this.level = HttpLoggingInterceptor.Level.BODY 37 | } 38 | 39 | //private val anotherInterceptor = 40 | 41 | private val cookies = object : CookieJar { 42 | var cookies = mutableListOf() 43 | 44 | override fun saveFromResponse(p0: HttpUrl?, p1: MutableList) { 45 | cookies = p1 46 | } 47 | 48 | override fun loadForRequest(p0: HttpUrl?): MutableList { 49 | return cookies 50 | } 51 | 52 | } 53 | 54 | private val proxy = Proxy(Proxy.Type.HTTP, InetSocketAddress("surfproxy.de.db.com", 3128)) 55 | 56 | private val okHttp = OkHttpClient.Builder() 57 | .proxy(proxy) 58 | .cookieJar(cookies) 59 | .addInterceptor { 60 | chain -> 61 | 62 | val resp = chain.proceed(chain.request()) 63 | 64 | val body = resp.body()?.string() 65 | 66 | //println("stat=${resp.code()} ${resp.body()!!.contentType().toString()}***$body***") 67 | 68 | val newBody = ResponseBody.create(resp.body()!!.contentType(),body) 69 | 70 | if(resp.code()==400) 71 | resp.newBuilder().code(200).body(newBody).build() 72 | else 73 | resp.newBuilder().body(newBody).build() 74 | } 75 | //.addInterceptor(interceptor) 76 | .build() 77 | 78 | private var retrofit: Retrofit = Retrofit.Builder() 79 | .client(okHttp) 80 | .baseUrl("https://quantumexperience.ng.bluemix.net") 81 | .addConverterFactory(GsonConverterFactory.create(gson)) 82 | //.addCallAdapterFactory(instance()) 83 | .build() 84 | 85 | private var api = retrofit.create(QARetrofitInterface::class.java) 86 | 87 | fun login(apiToken: String) { 88 | val result = api.login(apiToken).execute() 89 | 90 | if (result.body()?.userId?.isNotEmpty() == true) { 91 | sessionToken = result.body()?.id ?: "" 92 | true 93 | } else { 94 | false 95 | } 96 | } 97 | 98 | fun enumerateDevices() { 99 | devices = api.listDevices(sessionToken).execute()?.body() ?: listOf() 100 | 101 | devices.forEach { 102 | it.api = this 103 | } 104 | } 105 | 106 | fun device(name : String) = devices.firstOrNull { it.name == name && it.status == QADeviceStatus.on } ?: throw (IllegalStateException("No such device: $name" )) 107 | 108 | val simulator 109 | get() = devices.firstOrNull { it.simulator } ?: throw (IllegalStateException("Simulator not found" )) 110 | 111 | fun submitJob(newJob: QAJob): QAJob { 112 | val result = api.sendJob(sessionToken, newJob).execute() 113 | return if(result.body()?.error ==null) result.body()!! else throw RuntimeException("${result.body()?.error?.message}") 114 | } 115 | 116 | private fun receiveJob(job: QAJob): QAJob { 117 | val result = api.receiveJob(job.id, sessionToken).execute() 118 | return if(result.body()?.error ==null) result.body()!! else throw RuntimeException("${result.body()?.error?.message}") 119 | } 120 | 121 | 122 | /** 123 | * 124 | * Callback for receiving results of a job 125 | * 126 | * @param job a job to fetch from the server 127 | * @param maxTime fail if this waiting time is reached 128 | */ 129 | fun onJobStatus( 130 | job: QAJob, 131 | maxTime: Int, 132 | onCompleted: (QAJob) -> Unit, 133 | onError: (Throwable) -> Unit = {}) { 134 | 135 | val jobStart = Calendar.getInstance() 136 | var sleep = 1 137 | 138 | do { 139 | val elapsed = (Calendar.getInstance().timeInMillis - jobStart.timeInMillis) / 1000.0 140 | 141 | if (sleep > maxTime) { 142 | onError(TimeoutException("timeout waiting for a completed job: ${elapsed}s")) 143 | break 144 | } else { 145 | try { 146 | Thread.sleep((sleep * 1000.0).toLong()) 147 | sleep++ 148 | } catch (e: InterruptedException) { 149 | onError(e) 150 | break 151 | } 152 | } 153 | 154 | try { 155 | val serverJob = receiveJob(job) 156 | if (serverJob.status == StatusEnum.COMPLETED) { 157 | onCompleted(serverJob) 158 | break 159 | } 160 | } catch (ex :Exception) { 161 | onError(ex) 162 | break 163 | } 164 | } while (true) 165 | } 166 | } 167 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------