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();
}
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);
}
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);
}
}
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);
}
}
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);
}
});
}
Aggregations