Search in sources :

Example 81 with MediaType

use of com.reprezen.kaizen.oasparser.model3.MediaType in project firebase-android-sdk by firebase.

the class FirebaseFunctions method call.

/**
 * Calls a Callable HTTPS trigger endpoint.
 *
 * @param name The name of the HTTPS trigger.
 * @param data Parameters to pass to the function. Can be anything encodable as JSON.
 * @param context Metadata to supply with the function call.
 * @return A Task that will be completed when the request is complete.
 */
private Task<HttpsCallableResult> call(@NonNull String name, @Nullable Object data, HttpsCallableContext context, HttpsCallOptions options) {
    Preconditions.checkNotNull(name, "name cannot be null");
    URL url = getURL(name);
    Map<String, Object> body = new HashMap<>();
    Object encoded = serializer.encode(data);
    body.put("data", encoded);
    JSONObject bodyJSON = new JSONObject(body);
    MediaType contentType = MediaType.parse("application/json");
    RequestBody requestBody = RequestBody.create(contentType, bodyJSON.toString());
    Request.Builder request = new Request.Builder().url(url).post(requestBody);
    if (context.getAuthToken() != null) {
        request = request.header("Authorization", "Bearer " + context.getAuthToken());
    }
    if (context.getInstanceIdToken() != null) {
        request = request.header("Firebase-Instance-ID-Token", context.getInstanceIdToken());
    }
    if (context.getAppCheckToken() != null) {
        request = request.header("X-Firebase-AppCheck", context.getAppCheckToken());
    }
    OkHttpClient callClient = options.apply(client);
    Call call = callClient.newCall(request.build());
    TaskCompletionSource<HttpsCallableResult> tcs = new TaskCompletionSource<>();
    call.enqueue(new Callback() {

        @Override
        public void onFailure(Call ignored, IOException e) {
            if (e instanceof InterruptedIOException) {
                FirebaseFunctionsException exception = new FirebaseFunctionsException(Code.DEADLINE_EXCEEDED.name(), Code.DEADLINE_EXCEEDED, null, e);
                tcs.setException(exception);
            } else {
                FirebaseFunctionsException exception = new FirebaseFunctionsException(Code.INTERNAL.name(), Code.INTERNAL, null, e);
                tcs.setException(exception);
            }
        }

        @Override
        public void onResponse(Call ignored, Response response) throws IOException {
            Code code = Code.fromHttpStatus(response.code());
            String body = response.body().string();
            FirebaseFunctionsException exception = FirebaseFunctionsException.fromResponse(code, body, serializer);
            if (exception != null) {
                tcs.setException(exception);
                return;
            }
            JSONObject bodyJSON;
            try {
                bodyJSON = new JSONObject(body);
            } catch (JSONException je) {
                Exception e = new FirebaseFunctionsException("Response is not valid JSON object.", Code.INTERNAL, null, je);
                tcs.setException(e);
                return;
            }
            Object dataJSON = bodyJSON.opt("data");
            // TODO: Allow "result" instead of "data" for now, for backwards compatibility.
            if (dataJSON == null) {
                dataJSON = bodyJSON.opt("result");
            }
            if (dataJSON == null) {
                Exception e = new FirebaseFunctionsException("Response is missing data field.", Code.INTERNAL, null);
                tcs.setException(e);
                return;
            }
            HttpsCallableResult result = new HttpsCallableResult(serializer.decode(dataJSON));
            tcs.setResult(result);
        }
    });
    return tcs.getTask();
}
Also used : InterruptedIOException(java.io.InterruptedIOException) OkHttpClient(okhttp3.OkHttpClient) HashMap(java.util.HashMap) URL(java.net.URL) TaskCompletionSource(com.google.android.gms.tasks.TaskCompletionSource) MediaType(okhttp3.MediaType) RequestBody(okhttp3.RequestBody) Call(okhttp3.Call) Request(okhttp3.Request) JSONException(org.json.JSONException) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) Code(com.google.firebase.functions.FirebaseFunctionsException.Code) InterruptedIOException(java.io.InterruptedIOException) JSONException(org.json.JSONException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) Response(okhttp3.Response) Callback(okhttp3.Callback) JSONObject(org.json.JSONObject) JSONObject(org.json.JSONObject)

Example 82 with MediaType

use of com.reprezen.kaizen.oasparser.model3.MediaType in project mbed-cloud-sdk-java by ARMmbed.

the class DataFileAdapter method reverseMap.

/**
 * Reverses mapping of data file.
 *
 * @param partName
 *            name of the part to send
 * @param dataFile
 *            new data file
 * @return new data file request
 */
public static MultipartBody.Part reverseMap(String partName, DataFile dataFile) {
    if (dataFile == null) {
        return null;
    }
    final MediaType contentType = MediaType.parse(dataFile.getContentType());
    final RequestBody body = RequestBody.create(dataFile.getFile(), contentType);
    return MultipartBody.Part.createFormData(partName, dataFile.getFileName(), body);
}
Also used : MediaType(okhttp3.MediaType) RequestBody(okhttp3.RequestBody)

Example 83 with MediaType

use of com.reprezen.kaizen.oasparser.model3.MediaType in project mbed-cloud-sdk-java by ARMmbed.

the class OAuthOkHttpClient method execute.

@SuppressWarnings("resource")
@Override
public <T extends OAuthClientResponse> T execute(OAuthClientRequest request, Map<String, String> headers, String requestMethod, Class<T> responseClass) throws OAuthSystemException, OAuthProblemException {
    MediaType mediaType = MediaType.parse("application/json");
    Request.Builder requestBuilder = new Request.Builder().url(request.getLocationUri());
    if (headers != null) {
        for (Entry<String, String> entry : headers.entrySet()) {
            if (entry.getKey().equalsIgnoreCase("Content-Type")) {
                mediaType = MediaType.parse(entry.getValue());
            } else {
                requestBuilder.addHeader(entry.getKey(), entry.getValue());
            }
        }
    }
    RequestBody body = request.getBody() != null ? RequestBody.create(mediaType, request.getBody()) : null;
    requestBuilder.method(requestMethod, body);
    try {
        Response response = client.newCall(requestBuilder.build()).execute();
        return OAuthClientResponseFactory.createCustomResponse(response.body().string(), response.body().contentType().toString(), response.code(), null, responseClass);
    } catch (IOException e) {
        throw new OAuthSystemException(e);
    }
}
Also used : OAuthClientResponse(org.apache.oltu.oauth2.client.response.OAuthClientResponse) Response(okhttp3.Response) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) Request(okhttp3.Request) OAuthClientRequest(org.apache.oltu.oauth2.client.request.OAuthClientRequest) MediaType(okhttp3.MediaType) IOException(java.io.IOException) RequestBody(okhttp3.RequestBody)

Example 84 with MediaType

use of com.reprezen.kaizen.oasparser.model3.MediaType in project buck by facebook.

the class HttpArtifactCache method storeImpl.

@Override
protected void storeImpl(ArtifactInfo info, final Path file, final Finished.Builder eventBuilder) throws IOException {
    // Build the request, hitting the multi-key endpoint.
    Request.Builder builder = new Request.Builder();
    final HttpArtifactCacheBinaryProtocol.StoreRequest storeRequest = new HttpArtifactCacheBinaryProtocol.StoreRequest(info, new ByteSource() {

        @Override
        public InputStream openStream() throws IOException {
            return projectFilesystem.newFileInputStream(file);
        }
    });
    eventBuilder.getStoreBuilder().setRequestSizeBytes(storeRequest.getContentLength());
    // Wrap the file into a `RequestBody` which uses `ProjectFilesystem`.
    builder.put(new RequestBody() {

        @Override
        public MediaType contentType() {
            return OCTET_STREAM_CONTENT_TYPE;
        }

        @Override
        public long contentLength() throws IOException {
            return storeRequest.getContentLength();
        }

        @Override
        public void writeTo(BufferedSink bufferedSink) throws IOException {
            StoreWriteResult writeResult = storeRequest.write(bufferedSink.outputStream());
            eventBuilder.getStoreBuilder().setArtifactContentHash(writeResult.getArtifactContentHashCode().toString());
        }
    });
    // Dispatch the store operation and verify it succeeded.
    try (HttpResponse response = storeClient.makeRequest("/artifacts/key", builder)) {
        final boolean requestFailed = response.statusCode() != HttpURLConnection.HTTP_ACCEPTED;
        if (requestFailed) {
            reportFailure("store(%s, %s): unexpected response: [%d:%s].", response.requestUrl(), info.getRuleKeys(), response.statusCode(), response.statusMessage());
        }
        eventBuilder.getStoreBuilder().setWasStoreSuccessful(!requestFailed);
    }
}
Also used : DataInputStream(java.io.DataInputStream) InputStream(java.io.InputStream) Request(okhttp3.Request) HttpResponse(com.facebook.buck.slb.HttpResponse) BufferedSink(okio.BufferedSink) IOException(java.io.IOException) ByteSource(com.google.common.io.ByteSource) MediaType(okhttp3.MediaType) RequestBody(okhttp3.RequestBody)

Example 85 with MediaType

use of com.reprezen.kaizen.oasparser.model3.MediaType in project Rocket.Chat.Android by RocketChat.

the class FileUploadingWithUfsObserver method onUpdateResults.

@Override
public void onUpdateResults(List<FileUploading> results) {
    if (results.isEmpty()) {
        return;
    }
    List<FileUploading> uploadingList = realmHelper.executeTransactionForReadResults(realm -> realm.where(FileUploading.class).equalTo(FileUploading.SYNC_STATE, SyncState.SYNCING).findAll());
    if (uploadingList.size() >= 1) {
        // do not upload multiple files simultaneously
        return;
    }
    RealmUser currentUser = realmHelper.executeTransactionForRead(realm -> RealmUser.queryCurrentUser(realm).findFirst());
    RealmSession session = realmHelper.executeTransactionForRead(realm -> RealmSession.queryDefaultSession(realm).findFirst());
    if (currentUser == null || session == null) {
        return;
    }
    final String cookie = String.format("rc_uid=%s; rc_token=%s", currentUser.getId(), session.getToken());
    FileUploading fileUploading = results.get(0);
    final String roomId = fileUploading.getRoomId();
    final String uplId = fileUploading.getUplId();
    final String filename = fileUploading.getFilename();
    final long filesize = fileUploading.getFilesize();
    final String mimeType = fileUploading.getMimeType();
    final Uri fileUri = Uri.parse(fileUploading.getUri());
    final String store = FileUploading.STORAGE_TYPE_GRID_FS.equals(fileUploading.getStorageType()) ? "rocketchat_uploads" : (FileUploading.STORAGE_TYPE_FILE_SYSTEM.equals(fileUploading.getStorageType()) ? "fileSystem" : null);
    realmHelper.executeTransaction(realm -> realm.createOrUpdateObjectFromJson(FileUploading.class, new JSONObject().put(FileUploading.ID, uplId).put(FileUploading.SYNC_STATE, SyncState.SYNCING))).onSuccessTask(_task -> methodCall.ufsCreate(filename, filesize, mimeType, store, roomId)).onSuccessTask(task -> {
        final JSONObject info = task.getResult();
        final String fileId = info.getString("fileId");
        final String token = info.getString("token");
        final String url = info.getString("url");
        final int bufSize = 16384;
        final byte[] buffer = new byte[bufSize];
        int offset = 0;
        final MediaType contentType = MediaType.parse(mimeType);
        try (InputStream inputStream = context.getContentResolver().openInputStream(fileUri)) {
            int read;
            while ((read = inputStream.read(buffer)) > 0) {
                offset += read;
                double progress = 1.0 * offset / filesize;
                Request request = new Request.Builder().url(url + "&progress=" + progress).header("Cookie", cookie).post(RequestBody.create(contentType, buffer, 0, read)).build();
                Response response = OkHttpHelper.getClientForUploadFile().newCall(request).execute();
                if (response.isSuccessful()) {
                    final JSONObject obj = new JSONObject().put(FileUploading.ID, uplId).put(FileUploading.UPLOADED_SIZE, offset);
                    realmHelper.executeTransaction(realm -> realm.createOrUpdateObjectFromJson(FileUploading.class, obj));
                } else {
                    return Task.forError(new Exception(response.message()));
                }
            }
        }
        return methodCall.ufsComplete(fileId, token, store);
    }).onSuccessTask(task -> methodCall.sendFileMessage(roomId, null, task.getResult())).onSuccessTask(task -> realmHelper.executeTransaction(realm -> realm.createOrUpdateObjectFromJson(FileUploading.class, new JSONObject().put(FileUploading.ID, uplId).put(FileUploading.SYNC_STATE, SyncState.SYNCED).put(FileUploading.ERROR, JSONObject.NULL)))).continueWithTask(task -> {
        if (task.isFaulted()) {
            RCLog.w(task.getError());
            return realmHelper.executeTransaction(realm -> realm.createOrUpdateObjectFromJson(FileUploading.class, new JSONObject().put(FileUploading.ID, uplId).put(FileUploading.SYNC_STATE, SyncState.FAILED).put(FileUploading.ERROR, task.getError().getMessage())));
        } else {
            return Task.forResult(null);
        }
    });
}
Also used : Context(android.content.Context) Realm(io.realm.Realm) Request(okhttp3.Request) RealmUser(chat.rocket.persistence.realm.models.ddp.RealmUser) RealmSession(chat.rocket.persistence.realm.models.internal.RealmSession) RealmResults(io.realm.RealmResults) Uri(android.net.Uri) RCLog(chat.rocket.android.log.RCLog) LogIfError(chat.rocket.android.helper.LogIfError) RequestBody(okhttp3.RequestBody) List(java.util.List) JSONObject(org.json.JSONObject) RealmHelper(chat.rocket.persistence.realm.RealmHelper) SyncState(chat.rocket.core.SyncState) Response(okhttp3.Response) FileUploading(chat.rocket.persistence.realm.models.internal.FileUploading) DDPClientRef(chat.rocket.android.service.DDPClientRef) Task(bolts.Task) OkHttpHelper(chat.rocket.android.helper.OkHttpHelper) MediaType(okhttp3.MediaType) InputStream(java.io.InputStream) FileUploadingHelper(chat.rocket.android.api.FileUploadingHelper) InputStream(java.io.InputStream) RealmUser(chat.rocket.persistence.realm.models.ddp.RealmUser) Request(okhttp3.Request) Uri(android.net.Uri) Response(okhttp3.Response) JSONObject(org.json.JSONObject) FileUploading(chat.rocket.persistence.realm.models.internal.FileUploading) MediaType(okhttp3.MediaType) RealmSession(chat.rocket.persistence.realm.models.internal.RealmSession)

Aggregations

MediaType (okhttp3.MediaType)297 RequestBody (okhttp3.RequestBody)186 Request (okhttp3.Request)179 Response (okhttp3.Response)158 IOException (java.io.IOException)137 ResponseBody (okhttp3.ResponseBody)71 OkHttpClient (okhttp3.OkHttpClient)68 Charset (java.nio.charset.Charset)50 Buffer (okio.Buffer)50 Headers (okhttp3.Headers)48 JSONObject (org.json.JSONObject)38 BufferedSource (okio.BufferedSource)36 MultipartBody (okhttp3.MultipartBody)34 HttpUrl (okhttp3.HttpUrl)30 Map (java.util.Map)24 BufferedSink (okio.BufferedSink)23 File (java.io.File)22 InputStream (java.io.InputStream)21 ArrayList (java.util.ArrayList)21 Test (org.junit.Test)21