forked from LambdaTest/lambdatest-gradle-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUploaderUtil.java
72 lines (64 loc) · 2.79 KB
/
UploaderUtil.java
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package io.github.lambdatest.gradle;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.File;
import java.io.IOException;
import okhttp3.Credentials;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
/**
* Utility class providing common upload functionality for the LambdaTest Gradle plugin. This class
* handles the actual file upload process and response parsing.
*
* <p>This utility is used by both {@link AppUploader} and {@link TestSuiteUploader} to handle file
* uploads to the LambdaTest platform.
*/
public final class UploaderUtil {
/** Private constructor to prevent instantiation of this utility class. */
private UploaderUtil() {
throw new UnsupportedOperationException(
"This is a utility class and cannot be instantiated");
}
/**
* Uploads a file to LambdaTest and returns its ID.
*
* @param username The LambdaTest account username
* @param accessKey The LambdaTest account access key
* @param filePath The path to the file to be uploaded
* @return The ID of the uploaded file
* @throws IOException if there's an error during file upload or response parsing
* @implNote This method sends the file to {@link Constants#API_URL} and handles the multipart
* form data construction and response parsing
*/
public static String uploadAndGetId(String username, String accessKey, String filePath)
throws IOException {
OkHttpClient client = new OkHttpClient();
MediaType mediaType = MediaType.parse("application/octet-stream");
RequestBody body =
new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart(
"appFile",
filePath,
RequestBody.create(new File(filePath), mediaType))
.addFormDataPart("type", "espresso-android")
.build();
Request request =
new Request.Builder()
.url(Constants.API_URL)
.addHeader("Authorization", Credentials.basic(username, accessKey))
.post(body)
.build();
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
String responseBody = response.body().string();
JsonObject jsonObject = JsonParser.parseString(responseBody).getAsJsonObject();
String id = jsonObject.get("app_id").getAsString();
return id;
}
}
}