Update Fenix initial_experiments.json based on the current first-run experiments...
[gecko.git] / mobile / android / android-components / buildSrc / src / main / java / GitHubClient.kt
blob3c5263f843fa1e9027689b95bf40045e14557bd0
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2  * License, v. 2.0. If a copy of the MPL was not distributed with this
3  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
5 import java.net.HttpURLConnection
6 import java.net.URL
7 import java.nio.charset.StandardCharsets
9 class GitHubClient(token: String) {
11     private val tokenHeader = "Authorization" to "Bearer $token"
13     companion object {
14         const val GITHUB_BASE_API = "https://api.github.com/repos"
15     }
17     fun createPullRequest(owner: String, repoName: String, bodyJson: String): Pair<Boolean, String> {
18         val url = "$GITHUB_BASE_API/$owner/$repoName/pulls"
20         return httpPOST(url, bodyJson, tokenHeader)
21     }
23     fun createIssue(owner: String, repoName: String, bodyJson: String): Pair<Boolean, String> {
24         val url = "$GITHUB_BASE_API/$owner/$repoName/issues"
26         return httpPOST(url, bodyJson, tokenHeader)
27     }
29     @Suppress("TooGenericExceptionCaught")
30     private fun httpPOST(urlString: String, json: String, vararg headers: Pair<String, String>): Pair<Boolean, String> {
31         val url = URL(urlString)
32         val http = url.openConnection() as HttpURLConnection
34         http.requestMethod = "POST"
35         http.doOutput = true
36         http.setRequestProperty("Content-Type", "application/json; charset=UTF-8")
38         headers.forEach {
39             http.setRequestProperty(it.first, it.second)
40         }
42         http.outputStream.use { os ->
43             os.write(json.toByteArray(StandardCharsets.UTF_8))
44         }
46         var responseSuccessful = true
47         val textResponse = try {
48             http.inputStream.bufferedReader().readText()
49         } catch (e: Exception) {
50             responseSuccessful = false
51             http.errorStream.bufferedReader().readText()
52         }
53         return responseSuccessful to textResponse
54     }