use of okhttp3.MediaType in project LabDayApp by jakdor.
the class RetrofitBuilderTest method createServiceWithInterceptor.
/**
* test RetrofitBuilder in isolation from AuthenticationInterceptor
*/
@Test
public void createServiceWithInterceptor() throws Exception {
Request request = new Request.Builder().header("Authorization", dummyToken).get().url(dummyApiUrl).build();
ResponseBody dummyResponse = new ResponseBody() {
@Override
public MediaType contentType() {
return null;
}
@Override
public long contentLength() {
return 0;
}
@Override
public BufferedSource source() {
return null;
}
};
when(authenticationInterceptor.intercept(any())).thenReturn(new Response.Builder().request(request).protocol(Protocol.HTTP_2).code(200).body(dummyResponse).message(message).build());
LabService labService = retrofitBuilder.createService(dummyApiUrl, LabService.class, dummyToken);
TestObserver<AppData> testObserver = labService.getAppData().test();
testObserver.assertSubscribed();
testObserver.onComplete();
InOrder order = inOrder(authenticationInterceptor);
order.verify(authenticationInterceptor, calls(1)).setAuthToken(dummyToken);
order.verify(authenticationInterceptor, calls(1)).intercept(any());
}
use of okhttp3.MediaType in project data-transfer-project by google.
the class KoofrClient method uploadFile.
@SuppressWarnings("unchecked")
public String uploadFile(String parentPath, String name, InputStream inputStream, String mediaType, Date modified, String description) throws IOException, InvalidTokenException, DestinationMemoryFullException {
String url;
try {
URIBuilder builder = getUriBuilder().setPath(CONTENT_API_PATH_PREFIX + "/mounts/primary/files/put").setParameter("path", parentPath).setParameter("filename", name).setParameter("autorename", "true").setParameter("info", "true");
if (description != null && description.length() > 0) {
builder.setParameter("tags", "description=" + description);
}
if (modified != null) {
builder.setParameter("modified", Long.toString(modified.getTime()));
}
url = builder.build().toString();
} catch (URISyntaxException e) {
throw new IllegalStateException("Could not produce url.", e);
}
Request.Builder requestBuilder = getRequestBuilder(url);
RequestBody uploadBody = new InputStreamRequestBody(MediaType.parse(mediaType), inputStream);
requestBuilder.post(uploadBody);
// We need to reset the input stream because the request could already read some data
try (Response response = getResponse(fileUploadClient, requestBuilder, () -> inputStream.reset())) {
int code = response.code();
ResponseBody body = response.body();
if (code == 413) {
throw new DestinationMemoryFullException("Koofr quota exceeded", new Exception("Koofr file upload response code " + code));
}
if (code < 200 || code > 299) {
throw new IOException("Got error code: " + code + " message: " + response.message() + " body: " + body.string());
}
Map<String, Object> responseData = objectMapper.readValue(body.bytes(), Map.class);
String newName = (String) responseData.get("name");
Preconditions.checkState(!Strings.isNullOrEmpty(newName), "Expected name value to be present in %s", responseData);
return parentPath + "/" + newName;
}
}
use of okhttp3.MediaType in project data-transfer-project by google.
the class MicrosoftPhotosImporter method uploadChunk.
// Uploads a single DataChunk to an upload URL
// PUT to {photoUploadUrl}
// HEADERS
// Content-Length: {chunk size in bytes}
// Content-Range: bytes {begin}-{end}/{total size}
// body={bytes}
private Response uploadChunk(DataChunk chunk, String photoUploadUrl, int totalFileSize, String mediaType) throws IOException, DestinationMemoryFullException {
Request.Builder uploadRequestBuilder = new Request.Builder().url(photoUploadUrl);
uploadRequestBuilder.header("Authorization", "Bearer " + credential.getAccessToken());
// put chunk data in
RequestBody uploadChunkBody = RequestBody.create(MediaType.parse(mediaType), chunk.getData(), 0, chunk.getSize());
uploadRequestBuilder.put(uploadChunkBody);
// set chunk data headers, indicating size and chunk range
final String contentRange = String.format("bytes %d-%d/%d", chunk.getStart(), chunk.getEnd(), totalFileSize);
uploadRequestBuilder.header("Content-Range", contentRange);
uploadRequestBuilder.header("Content-Length", String.format("%d", chunk.getSize()));
// upload the chunk
Response chunkResponse = client.newCall(uploadRequestBuilder.build()).execute();
Preconditions.checkNotNull(chunkResponse, "chunkResponse is null");
if (chunkResponse.code() == 401) {
// If there was an unauthorized error, then try refreshing the creds
credentialFactory.refreshCredential(credential);
monitor.info(() -> "Refreshed authorization token successfuly");
// update auth info, reupload chunk
uploadRequestBuilder.header("Authorization", "Bearer " + credential.getAccessToken());
chunkResponse = client.newCall(uploadRequestBuilder.build()).execute();
}
int chunkCode = chunkResponse.code();
if (chunkCode == 507 && chunkResponse.message().contains("Insufficient Storage")) {
throw new DestinationMemoryFullException("Microsoft destination storage limit reached", new IOException(String.format("Got error code %d with message: %s", chunkCode, chunkResponse.message())));
} else if (chunkCode < 200 || chunkCode > 299) {
throw new IOException("Got error code: " + chunkCode + " message: " + chunkResponse.message() + " body: " + chunkResponse.body().string());
} else if (chunkCode == 200 || chunkCode == 201 || chunkCode == 202) {
monitor.info(() -> String.format("Uploaded chunk %s-%s successfuly, code %d", chunk.getStart(), chunk.getEnd(), chunkCode));
}
return chunkResponse;
}
use of okhttp3.MediaType in project buck by facebook.
the class DefaultDefectReporter method uploadReport.
private DefectSubmitResult uploadReport(final DefectReport defectReport, DefectSubmitResult.Builder defectSubmitResult, ClientSideSlb slb) throws IOException {
long timeout = rageConfig.getHttpTimeout();
OkHttpClient httpClient = new OkHttpClient.Builder().connectTimeout(timeout, TimeUnit.MILLISECONDS).readTimeout(timeout, TimeUnit.MILLISECONDS).writeTimeout(timeout, TimeUnit.MILLISECONDS).build();
HttpService httpService = new RetryingHttpService(buckEventBus, new LoadBalancedService(slb, httpClient, buckEventBus), rageConfig.getMaxUploadRetries());
try {
Request.Builder requestBuilder = new Request.Builder();
requestBuilder.addHeader(REQUEST_PROTOCOL_VERSION, rageConfig.getProtocolVersion().name().toLowerCase());
requestBuilder.post(new RequestBody() {
@Override
public MediaType contentType() {
return MediaType.parse("application/x-www-form-urlencoded");
}
@Override
public void writeTo(BufferedSink bufferedSink) throws IOException {
writeReport(defectReport, bufferedSink.outputStream());
}
});
HttpResponse response = httpService.makeRequest(rageConfig.getReportUploadPath(), requestBuilder);
String responseBody;
try (InputStream inputStream = response.getBody()) {
responseBody = CharStreams.toString(new InputStreamReader(inputStream, Charsets.UTF_8));
}
if (response.statusCode() == HTTP_SUCCESS_CODE) {
defectSubmitResult.setIsRequestSuccessful(true);
if (rageConfig.getProtocolVersion().equals(AbstractRageConfig.RageProtocolVersion.SIMPLE)) {
return defectSubmitResult.setReportSubmitMessage(responseBody).setReportSubmitLocation(responseBody).build();
} else {
// Decode Json response.
RageJsonResponse json = objectMapper.readValue(responseBody.getBytes(Charsets.UTF_8), RageJsonResponse.class);
return defectSubmitResult.setIsRequestSuccessful(json.getRequestSuccessful()).setReportSubmitErrorMessage(json.getErrorMessage()).setReportSubmitMessage(json.getMessage()).setReportSubmitLocation(json.getRageUrl()).build();
}
} else {
throw new IOException(String.format("Connection to %s returned code %d and message: %s", response.requestUrl(), response.statusCode(), responseBody));
}
} catch (IOException e) {
throw new IOException(String.format("Failed uploading report because [%s].", e.getMessage()));
} finally {
httpService.close();
}
}
use of okhttp3.MediaType in project buck by facebook.
the class ThriftArtifactCache method toOkHttpRequest.
private static Request.Builder toOkHttpRequest(final ThriftArtifactCacheProtocol.Request request) {
Request.Builder builder = new Request.Builder().addHeader(PROTOCOL_HEADER, PROTOCOL.toString().toLowerCase());
builder.post(new RequestBody() {
@Override
public MediaType contentType() {
return HYBRID_THRIFT_STREAM_CONTENT_TYPE;
}
@Override
public long contentLength() throws IOException {
return request.getRequestLengthBytes();
}
@Override
public void writeTo(BufferedSink bufferedSink) throws IOException {
request.writeAndClose(bufferedSink.outputStream());
}
});
return builder;
}
Aggregations