use of com.ecwid.consul.v1.Response 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);
}
});
}
use of com.ecwid.consul.v1.Response in project cw-omnibus by commonsguy.
the class LoadThread method run.
@Override
public void run() {
try {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(SO_URL).build();
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
Reader in = response.body().charStream();
BufferedReader reader = new BufferedReader(in);
SOQuestions questions = new Gson().fromJson(reader, SOQuestions.class);
reader.close();
EventBus.getDefault().post(new QuestionsLoadedEvent(questions));
} else {
Log.e(getClass().getSimpleName(), response.toString());
}
} catch (Exception e) {
Log.e(getClass().getSimpleName(), "Exception parsing JSON", e);
}
}
use of com.ecwid.consul.v1.Response in project cw-omnibus by commonsguy.
the class Downloader method onHandleIntent.
@Override
public void onHandleIntent(Intent i) {
mgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
try {
String filename = i.getData().getLastPathSegment();
NotificationCompat.Builder builder = buildForeground(filename);
final Notification notif = builder.build();
startForeground(FOREGROUND_ID, notif);
File root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
root.mkdirs();
File output = new File(root, filename);
if (output.exists()) {
output.delete();
}
final ProgressResponseBody.Listener progressListener = new ProgressResponseBody.Listener() {
long lastUpdateTime = 0L;
@Override
public void onProgressChange(long bytesRead, long contentLength, boolean done) {
long now = SystemClock.uptimeMillis();
if (now - lastUpdateTime > 1000) {
notif.contentView.setProgressBar(android.R.id.progress, (int) contentLength, (int) bytesRead, false);
mgr.notify(FOREGROUND_ID, notif);
lastUpdateTime = now;
}
}
};
Interceptor nightTrain = new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Response original = chain.proceed(chain.request());
Response.Builder b = original.newBuilder().body(new ProgressResponseBody(original.body(), progressListener));
return (b.build());
}
};
OkHttpClient client = new OkHttpClient.Builder().addNetworkInterceptor(nightTrain).build();
Request request = new Request.Builder().url(i.getData().toString()).build();
Response response = client.newCall(request).execute();
String contentType = response.header("Content-type");
BufferedSink sink = Okio.buffer(Okio.sink(new File(output.getPath())));
sink.writeAll(response.body().source());
sink.close();
stopForeground(true);
raiseNotification(contentType, output, null);
} catch (IOException e2) {
stopForeground(true);
raiseNotification(null, null, e2);
}
}
use of com.ecwid.consul.v1.Response in project azure-sdk-for-java by Azure.
the class KeyVaultClientImpl method decryptWithServiceResponseAsync.
/**
* Decrypts a single block of encrypted data.
*
* @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net.
* @param keyName The name of the key.
* @param keyVersion The version of the key.
* @param algorithm algorithm identifier. Possible values include: 'RSA-OAEP', 'RSA1_5'
* @param value the Base64Url value
* @return the observable to the KeyOperationResult object
*/
public Observable<ServiceResponse<KeyOperationResult>> decryptWithServiceResponseAsync(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value) {
if (vaultBaseUrl == null) {
throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null.");
}
if (keyName == null) {
throw new IllegalArgumentException("Parameter keyName is required and cannot be null.");
}
if (keyVersion == null) {
throw new IllegalArgumentException("Parameter keyVersion is required and cannot be null.");
}
if (this.apiVersion() == null) {
throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null.");
}
if (algorithm == null) {
throw new IllegalArgumentException("Parameter algorithm is required and cannot be null.");
}
if (value == null) {
throw new IllegalArgumentException("Parameter value is required and cannot be null.");
}
KeyOperationsParameters parameters = new KeyOperationsParameters();
parameters.withAlgorithm(algorithm);
parameters.withValue(value);
String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl);
return service.decrypt(keyName, keyVersion, this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()).flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<KeyOperationResult>>>() {
@Override
public Observable<ServiceResponse<KeyOperationResult>> call(Response<ResponseBody> response) {
try {
ServiceResponse<KeyOperationResult> clientResponse = decryptDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
use of com.ecwid.consul.v1.Response in project azure-sdk-for-java by Azure.
the class KeyVaultClientImpl method setSecretWithServiceResponseAsync.
/**
* Sets a secret in a specified key vault.
*
* @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net.
* @param secretName The name of the secret.
* @param value The value of the secret.
* @param tags Application specific metadata in the form of key-value pairs.
* @param contentType Type of the secret value such as a password.
* @param secretAttributes The secret management attributes.
* @return the observable to the SecretBundle object
*/
public Observable<ServiceResponse<SecretBundle>> setSecretWithServiceResponseAsync(String vaultBaseUrl, String secretName, String value, Map<String, String> tags, String contentType, SecretAttributes secretAttributes) {
if (vaultBaseUrl == null) {
throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null.");
}
if (secretName == null) {
throw new IllegalArgumentException("Parameter secretName is required and cannot be null.");
}
if (this.apiVersion() == null) {
throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null.");
}
if (value == null) {
throw new IllegalArgumentException("Parameter value is required and cannot be null.");
}
Validator.validate(tags);
Validator.validate(secretAttributes);
SecretSetParameters parameters = new SecretSetParameters();
parameters.withValue(value);
parameters.withTags(tags);
parameters.withContentType(contentType);
parameters.withSecretAttributes(secretAttributes);
String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl);
return service.setSecret(secretName, this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()).flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<SecretBundle>>>() {
@Override
public Observable<ServiceResponse<SecretBundle>> call(Response<ResponseBody> response) {
try {
ServiceResponse<SecretBundle> clientResponse = setSecretDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
Aggregations