use of bolts.Task in project Rocket.Chat.Android by RocketChat.
the class MethodCall method execute.
/**
* insert a new record to request a method call.
*/
public static Task<String> execute(RealmHelper realmHelper, String name, String paramsJson, long timeout) {
final String newId = UUID.randomUUID().toString();
TaskCompletionSource<String> task = new TaskCompletionSource<>();
realmHelper.executeTransaction(realm -> {
MethodCall call = realm.createObjectFromJson(MethodCall.class, new JSONObject().put(ID, newId).put(SYNC_STATE, SyncState.NOT_SYNCED).put(TIMEOUT, timeout).put(NAME, name));
call.setParamsJson(paramsJson);
return null;
}).continueWith(_task -> {
if (_task.isFaulted()) {
task.setError(_task.getError());
} else {
final RealmObjectObserver<MethodCall> observer = realmHelper.createObjectObserver(realm -> realm.where(MethodCall.class).equalTo(ID, newId));
observer.setOnUpdateListener(methodCall -> {
if (methodCall == null) {
observer.unsub();
REF_MAP.remove(newId);
return;
}
int syncState = methodCall.getSyncState();
RCLog.d("MethodCall[%s] syncstate=%d", methodCall.getMethodCallId(), syncState);
if (syncState == SyncState.SYNCED) {
String resultJson = methodCall.getResultJson();
if (TextUtils.isEmpty(resultJson)) {
task.setResult(null);
} else {
task.setResult(resultJson);
}
observer.unsub();
REF_MAP.remove(methodCall.getMethodCallId());
remove(realmHelper, methodCall.getMethodCallId()).continueWith(new LogcatIfError());
} else if (syncState == SyncState.FAILED) {
task.setError(new Error(methodCall.getResultJson()));
observer.unsub();
REF_MAP.remove(methodCall.getMethodCallId());
remove(realmHelper, methodCall.getMethodCallId()).continueWith(new LogcatIfError());
}
});
observer.sub();
REF_MAP.put(newId, observer);
}
return null;
});
return task.getTask();
}
use of bolts.Task in project Rocket.Chat.Android by RocketChat.
the class MethodCallHelper method loadHistory.
/**
* Load messages for room.
*/
public Task<JSONArray> loadHistory(final String roomId, final long timestamp, final int count, final long lastSeen) {
return call("loadHistory", TIMEOUT_MS, () -> new JSONArray().put(roomId).put(timestamp > 0 ? new JSONObject().put("$date", timestamp) : JSONObject.NULL).put(count).put(lastSeen > 0 ? new JSONObject().put("$date", lastSeen) : JSONObject.NULL)).onSuccessTask(CONVERT_TO_JSON_OBJECT).onSuccessTask(task -> {
JSONObject result = task.getResult();
final JSONArray messages = result.getJSONArray("messages");
for (int i = 0; i < messages.length(); i++) {
RealmMessage.customizeJson(messages.getJSONObject(i));
}
return realmHelper.executeTransaction(realm -> {
if (timestamp == 0) {
realm.where(RealmMessage.class).equalTo("rid", roomId).equalTo("syncstate", SyncState.SYNCED).findAll().deleteAllFromRealm();
}
if (messages.length() > 0) {
realm.createOrUpdateAllFromJson(RealmMessage.class, messages);
}
return null;
}).onSuccessTask(_task -> Task.forResult(messages));
});
}
use of bolts.Task in project Rocket.Chat.Android by RocketChat.
the class DDPClientImpl method sub.
public void sub(final TaskCompletionSource<DDPSubscription.Ready> task, String name, JSONArray params, String id) {
final boolean requested = sendMessage("sub", json -> json.put("id", id).put("name", name).put("params", params));
if (requested) {
CompositeDisposable subscriptions = new CompositeDisposable();
subscriptions.add(flowable.filter(callback -> callback instanceof RxWebSocketCallback.Message).map(callback -> ((RxWebSocketCallback.Message) callback).responseBodyString).map(DDPClientImpl::toJson).subscribe(response -> {
String msg = extractMsg(response);
if ("ready".equals(msg) && !response.isNull("subs")) {
JSONArray ids = response.optJSONArray("subs");
for (int i = 0; i < ids.length(); i++) {
String _id = ids.optString(i);
if (id.equals(_id)) {
task.setResult(new DDPSubscription.Ready(client, id));
subscriptions.dispose();
break;
}
}
} else if ("nosub".equals(msg) && !response.isNull("id") && !response.isNull("error")) {
String _id = response.optString("id");
if (id.equals(_id)) {
task.setError(new DDPSubscription.NoSub.Error(client, id, response.optJSONObject("error")));
subscriptions.dispose();
}
}
}, err -> {
}));
addErrorCallback(subscriptions, task);
} else {
task.trySetError(new DDPClientCallback.Closed(client));
}
}
use of bolts.Task 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 bolts.Task in project Bolts-Java by BoltsFramework.
the class TaskTest method testContinueWhile.
public void testContinueWhile() {
final AtomicInteger count = new AtomicInteger(0);
runTaskTest(new Callable<Task<?>>() {
public Task<?> call() throws Exception {
return Task.forResult(null).continueWhile(new Callable<Boolean>() {
public Boolean call() throws Exception {
return count.get() < 10;
}
}, new Continuation<Void, Task<Void>>() {
public Task<Void> then(Task<Void> task) throws Exception {
count.incrementAndGet();
return null;
}
}).continueWith(new Continuation<Void, Void>() {
public Void then(Task<Void> task) throws Exception {
assertEquals(10, count.get());
return null;
}
});
}
});
}
Aggregations