Search in sources :

Example 16 with Task

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();
}
Also used : RealmObject(io.realm.RealmObject) TextUtils(android.text.TextUtils) HashMap(java.util.HashMap) UUID(java.util.UUID) RCLog(chat.rocket.android.log.RCLog) RealmObjectObserver(chat.rocket.persistence.realm.RealmObjectObserver) TaskCompletionSource(bolts.TaskCompletionSource) PrimaryKey(io.realm.annotations.PrimaryKey) JSONObject(org.json.JSONObject) RealmHelper(chat.rocket.persistence.realm.RealmHelper) SyncState(chat.rocket.core.SyncState) LogcatIfError(chat.rocket.persistence.realm.helpers.LogcatIfError) Task(bolts.Task) TaskCompletionSource(bolts.TaskCompletionSource) JSONObject(org.json.JSONObject) LogcatIfError(chat.rocket.persistence.realm.helpers.LogcatIfError) LogcatIfError(chat.rocket.persistence.realm.helpers.LogcatIfError)

Example 17 with Task

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));
    });
}
Also used : Context(android.content.Context) DDPClientCallback(chat.rocket.android_ddp.DDPClientCallback) ConnectivityManager(chat.rocket.android.service.ConnectivityManager) RealmMessage(chat.rocket.persistence.realm.models.ddp.RealmMessage) DebugLog(hugo.weaving.DebugLog) JSONException(org.json.JSONException) Patterns(android.util.Patterns) JSONObject(org.json.JSONObject) SyncState(chat.rocket.core.SyncState) RealmRoomRole(chat.rocket.persistence.realm.models.ddp.RealmRoomRole) Task(bolts.Task) TextUtils(chat.rocket.android.helper.TextUtils) MethodCall(chat.rocket.persistence.realm.models.internal.MethodCall) Continuation(bolts.Continuation) RealmSpotlightRoom(chat.rocket.persistence.realm.models.ddp.RealmSpotlightRoom) RealmSession(chat.rocket.persistence.realm.models.internal.RealmSession) UUID(java.util.UUID) RealmPublicSetting(chat.rocket.persistence.realm.models.ddp.RealmPublicSetting) RealmSpotlightUser(chat.rocket.persistence.realm.models.ddp.RealmSpotlightUser) RealmRoom(chat.rocket.persistence.realm.models.ddp.RealmRoom) RealmHelper(chat.rocket.persistence.realm.RealmHelper) DDPClientRef(chat.rocket.android.service.DDPClientRef) RealmPermission(chat.rocket.persistence.realm.models.ddp.RealmPermission) CheckSum(chat.rocket.android.helper.CheckSum) JSONArray(org.json.JSONArray) RealmStore(chat.rocket.persistence.realm.RealmStore) JSONObject(org.json.JSONObject) JSONArray(org.json.JSONArray) RealmMessage(chat.rocket.persistence.realm.models.ddp.RealmMessage)

Example 18 with Task

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));
    }
}
Also used : RxWebSocketCallback(chat.rocket.android_ddp.rx.RxWebSocketCallback) TimeoutException(java.util.concurrent.TimeoutException) TextUtils(android.text.TextUtils) NonNull(android.support.annotation.NonNull) RCLog(chat.rocket.android.log.RCLog) TaskCompletionSource(bolts.TaskCompletionSource) TimeUnit(java.util.concurrent.TimeUnit) CompositeDisposable(io.reactivex.disposables.CompositeDisposable) JSONException(org.json.JSONException) RxWebSocket(chat.rocket.android_ddp.rx.RxWebSocket) JSONObject(org.json.JSONObject) OkHttpClient(okhttp3.OkHttpClient) Flowable(io.reactivex.Flowable) Nullable(android.support.annotation.Nullable) Task(bolts.Task) JSONArray(org.json.JSONArray) JSONArray(org.json.JSONArray) RxWebSocketCallback(chat.rocket.android_ddp.rx.RxWebSocketCallback) CompositeDisposable(io.reactivex.disposables.CompositeDisposable)

Example 19 with Task

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

Example 20 with Task

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;
                }
            });
        }
    });
}
Also used : Task(bolts.Task) Continuation(bolts.Continuation) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AggregateException(bolts.AggregateException) CancellationException(java.util.concurrent.CancellationException)

Aggregations

Task (bolts.Task)46 JSONObject (org.json.JSONObject)27 Continuation (bolts.Continuation)23 JSONException (org.json.JSONException)20 ArrayList (java.util.ArrayList)15 JSONArray (org.json.JSONArray)14 RCLog (chat.rocket.android.log.RCLog)11 TaskCompletionSource (bolts.TaskCompletionSource)10 List (java.util.List)8 Context (android.content.Context)7 Uri (android.net.Uri)7 RealmHelper (chat.rocket.persistence.realm.RealmHelper)7 CancellationException (java.util.concurrent.CancellationException)7 TextUtils (android.text.TextUtils)6 SyncState (chat.rocket.core.SyncState)6 IOException (java.io.IOException)6 NonNull (android.support.annotation.NonNull)5 Nullable (android.support.annotation.Nullable)5 AggregateException (bolts.AggregateException)5 AppLink (bolts.AppLink)5