Search in sources :

Example 91 with MediaType

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());
}
Also used : Response(okhttp3.Response) LabService(com.jakdor.labday.common.network.LabService) InOrder(org.mockito.InOrder) AppData(com.jakdor.labday.common.model.AppData) RetrofitBuilder(com.jakdor.labday.common.network.RetrofitBuilder) Request(okhttp3.Request) ResponseBody(okhttp3.ResponseBody) Test(org.junit.Test)

Example 92 with MediaType

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;
    }
}
Also used : DestinationMemoryFullException(org.datatransferproject.spi.transfer.types.DestinationMemoryFullException) Request(okhttp3.Request) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) DestinationMemoryFullException(org.datatransferproject.spi.transfer.types.DestinationMemoryFullException) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) InvalidTokenException(org.datatransferproject.spi.transfer.types.InvalidTokenException) URIBuilder(org.apache.http.client.utils.URIBuilder) ResponseBody(okhttp3.ResponseBody) Response(okhttp3.Response) RequestBody(okhttp3.RequestBody)

Example 93 with MediaType

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;
}
Also used : Response(okhttp3.Response) DestinationMemoryFullException(org.datatransferproject.spi.transfer.types.DestinationMemoryFullException) Request(okhttp3.Request) IOException(java.io.IOException) RequestBody(okhttp3.RequestBody)

Example 94 with MediaType

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();
    }
}
Also used : OkHttpClient(okhttp3.OkHttpClient) InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) Request(okhttp3.Request) HttpResponse(com.facebook.buck.slb.HttpResponse) BufferedSink(okio.BufferedSink) IOException(java.io.IOException) RetryingHttpService(com.facebook.buck.slb.RetryingHttpService) RetryingHttpService(com.facebook.buck.slb.RetryingHttpService) HttpService(com.facebook.buck.slb.HttpService) MediaType(okhttp3.MediaType) LoadBalancedService(com.facebook.buck.slb.LoadBalancedService) RequestBody(okhttp3.RequestBody)

Example 95 with MediaType

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;
}
Also used : BuckCacheStoreRequest(com.facebook.buck.artifact_cache.thrift.BuckCacheStoreRequest) Request(okhttp3.Request) BuckCacheRequest(com.facebook.buck.artifact_cache.thrift.BuckCacheRequest) BuckCacheFetchRequest(com.facebook.buck.artifact_cache.thrift.BuckCacheFetchRequest) MediaType(okhttp3.MediaType) BufferedSink(okio.BufferedSink) IOException(java.io.IOException) RequestBody(okhttp3.RequestBody)

Aggregations

MediaType (okhttp3.MediaType)103 RequestBody (okhttp3.RequestBody)95 Request (okhttp3.Request)86 Response (okhttp3.Response)78 IOException (java.io.IOException)73 ResponseBody (okhttp3.ResponseBody)36 BufferedSink (okio.BufferedSink)34 Buffer (okio.Buffer)30 Charset (java.nio.charset.Charset)26 Headers (okhttp3.Headers)19 BufferedSource (okio.BufferedSource)19 Map (java.util.Map)17 OkHttpClient (okhttp3.OkHttpClient)17 InputStream (java.io.InputStream)12 HashMap (java.util.HashMap)12 MultipartBody (okhttp3.MultipartBody)12 MockResponse (okhttp3.mockwebserver.MockResponse)11 EOFException (java.io.EOFException)10 GzipSink (okio.GzipSink)10 JSONObject (org.json.JSONObject)10