Using default singleton OwnCloudClientManager instead of holding a reference in appli...
[pub/Android/ownCloud.git] / src / com / owncloud / android / services / OperationsService.java
1 /* ownCloud Android client application
2 * Copyright (C) 2012-2014 ownCloud Inc.
3 *
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License version 2,
6 * as published by the Free Software Foundation.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
15 *
16 */
17
18 package com.owncloud.android.services;
19
20 import java.io.IOException;
21 import java.util.Iterator;
22 import java.util.concurrent.ConcurrentHashMap;
23 import java.util.concurrent.ConcurrentLinkedQueue;
24 import java.util.concurrent.ConcurrentMap;
25
26 import com.owncloud.android.MainApp;
27 import com.owncloud.android.R;
28 import com.owncloud.android.datamodel.FileDataStorageManager;
29 import com.owncloud.android.lib.common.OwnCloudAccount;
30 import com.owncloud.android.lib.common.OwnCloudClient;
31 import com.owncloud.android.lib.common.OwnCloudClientManagerFactory;
32 import com.owncloud.android.lib.common.OwnCloudCredentials;
33 import com.owncloud.android.lib.common.OwnCloudCredentialsFactory;
34 import com.owncloud.android.lib.common.accounts.AccountUtils.AccountNotFoundException;
35 import com.owncloud.android.lib.common.operations.OnRemoteOperationListener;
36 import com.owncloud.android.lib.common.operations.RemoteOperation;
37 import com.owncloud.android.lib.common.operations.RemoteOperationResult;
38 import com.owncloud.android.lib.resources.files.ExistenceCheckRemoteOperation;
39 import com.owncloud.android.lib.resources.shares.ShareType;
40 import com.owncloud.android.lib.resources.users.GetRemoteUserNameOperation;
41 import com.owncloud.android.operations.common.SyncOperation;
42 import com.owncloud.android.operations.CreateFolderOperation;
43 import com.owncloud.android.operations.CreateShareOperation;
44 import com.owncloud.android.operations.GetServerInfoOperation;
45 import com.owncloud.android.operations.OAuth2GetAccessToken;
46 import com.owncloud.android.operations.RemoveFileOperation;
47 import com.owncloud.android.operations.RenameFileOperation;
48 import com.owncloud.android.operations.SynchronizeFileOperation;
49 import com.owncloud.android.operations.UnshareLinkOperation;
50 import com.owncloud.android.utils.Log_OC;
51
52 import android.accounts.Account;
53 import android.accounts.AccountsException;
54 import android.accounts.AuthenticatorException;
55 import android.accounts.OperationCanceledException;
56 import android.app.Service;
57 import android.content.Intent;
58 import android.net.Uri;
59 import android.os.Binder;
60 import android.os.Handler;
61 import android.os.HandlerThread;
62 import android.os.IBinder;
63 import android.os.Looper;
64 import android.os.Message;
65 import android.os.Process;
66 import android.util.Pair;
67
68 public class OperationsService extends Service {
69
70 private static final String TAG = OperationsService.class.getSimpleName();
71
72 public static final String EXTRA_ACCOUNT = "ACCOUNT";
73 public static final String EXTRA_SERVER_URL = "SERVER_URL";
74 public static final String EXTRA_AUTH_TOKEN_TYPE = "AUTH_TOKEN_TYPE";
75 public static final String EXTRA_OAUTH2_QUERY_PARAMETERS = "OAUTH2_QUERY_PARAMETERS";
76 public static final String EXTRA_REMOTE_PATH = "REMOTE_PATH";
77 public static final String EXTRA_SEND_INTENT = "SEND_INTENT";
78 public static final String EXTRA_NEWNAME = "NEWNAME";
79 public static final String EXTRA_REMOVE_ONLY_LOCAL = "REMOVE_LOCAL_COPY";
80 public static final String EXTRA_CREATE_FULL_PATH = "CREATE_FULL_PATH";
81 public static final String EXTRA_SYNC_FILE_CONTENTS = "SYNC_FILE_CONTENTS";
82 public static final String EXTRA_RESULT = "RESULT";
83
84 // TODO review if ALL OF THEM are necessary
85 public static final String EXTRA_SUCCESS_IF_ABSENT = "SUCCESS_IF_ABSENT";
86 public static final String EXTRA_USERNAME = "USERNAME";
87 public static final String EXTRA_PASSWORD = "PASSWORD";
88 public static final String EXTRA_AUTH_TOKEN = "AUTH_TOKEN";
89 public static final String EXTRA_FOLLOW_REDIRECTS = "FOLLOW_REDIRECTS";
90 public static final String EXTRA_COOKIE = "COOKIE";
91
92 public static final String ACTION_CREATE_SHARE = "CREATE_SHARE";
93 public static final String ACTION_UNSHARE = "UNSHARE";
94 public static final String ACTION_GET_SERVER_INFO = "GET_SERVER_INFO";
95 public static final String ACTION_OAUTH2_GET_ACCESS_TOKEN = "OAUTH2_GET_ACCESS_TOKEN";
96 public static final String ACTION_EXISTENCE_CHECK = "EXISTENCE_CHECK";
97 public static final String ACTION_GET_USER_NAME = "GET_USER_NAME";
98 public static final String ACTION_RENAME = "RENAME";
99 public static final String ACTION_REMOVE = "REMOVE";
100 public static final String ACTION_CREATE_FOLDER = "CREATE_FOLDER";
101 public static final String ACTION_SYNC_FILE = "SYNC_FILE";
102
103 public static final String ACTION_OPERATION_ADDED = OperationsService.class.getName() + ".OPERATION_ADDED";
104 public static final String ACTION_OPERATION_FINISHED = OperationsService.class.getName() + ".OPERATION_FINISHED";
105
106 private ConcurrentLinkedQueue<Pair<Target, RemoteOperation>> mPendingOperations =
107 new ConcurrentLinkedQueue<Pair<Target, RemoteOperation>>();
108
109 private ConcurrentMap<Integer, Pair<RemoteOperation, RemoteOperationResult>>
110 mUndispatchedFinishedOperations =
111 new ConcurrentHashMap<Integer, Pair<RemoteOperation, RemoteOperationResult>>();
112
113 private static class Target {
114 public Uri mServerUrl = null;
115 public Account mAccount = null;
116 public String mUsername = null;
117 public String mPassword = null;
118 public String mAuthToken = null;
119 public boolean mFollowRedirects = true;
120 public String mCookie = null;
121
122 public Target(Account account, Uri serverUrl, String username, String password, String authToken,
123 boolean followRedirects, String cookie) {
124 mAccount = account;
125 mServerUrl = serverUrl;
126 mUsername = username;
127 mPassword = password;
128 mAuthToken = authToken;
129 mFollowRedirects = followRedirects;
130 mCookie = cookie;
131 }
132 }
133
134 private Looper mServiceLooper;
135 private ServiceHandler mServiceHandler;
136 private OperationsServiceBinder mBinder;
137 private OwnCloudClient mOwnCloudClient = null;
138 private Target mLastTarget = null;
139 private FileDataStorageManager mStorageManager;
140 private RemoteOperation mCurrentOperation = null;
141
142
143 /**
144 * Service initialization
145 */
146 @Override
147 public void onCreate() {
148 super.onCreate();
149 HandlerThread thread = new HandlerThread("Operations service thread", Process.THREAD_PRIORITY_BACKGROUND);
150 thread.start();
151 mServiceLooper = thread.getLooper();
152 mServiceHandler = new ServiceHandler(mServiceLooper, this);
153 mBinder = new OperationsServiceBinder();
154 }
155
156
157 /**
158 * Entry point to add a new operation to the queue of operations.
159 *
160 * New operations are added calling to startService(), resulting in a call to this method.
161 * This ensures the service will keep on working although the caller activity goes away.
162 *
163 * IMPORTANT: the only operations performed here right now is {@link GetSharedFilesOperation}. The class
164 * is taking advantage of it due to time constraints.
165 */
166 @Override
167 public int onStartCommand(Intent intent, int flags, int startId) {
168 //Log_OC.wtf(TAG, "onStartCommand init" );
169 Message msg = mServiceHandler.obtainMessage();
170 msg.arg1 = startId;
171 mServiceHandler.sendMessage(msg);
172 //Log_OC.wtf(TAG, "onStartCommand end" );
173 return START_NOT_STICKY;
174 }
175
176 @Override
177 public void onDestroy() {
178 //Log_OC.wtf(TAG, "onDestroy init" );
179 // Saving cookies
180 try {
181 OwnCloudClientManagerFactory.getDefaultSingleton().
182 saveAllClients(this, MainApp.getAccountType());
183
184 // TODO - get rid of these exceptions
185 } catch (AccountNotFoundException e) {
186 e.printStackTrace();
187 } catch (AuthenticatorException e) {
188 e.printStackTrace();
189 } catch (OperationCanceledException e) {
190 e.printStackTrace();
191 } catch (IOException e) {
192 e.printStackTrace();
193 }
194
195 //Log_OC.wtf(TAG, "Clear mUndispatchedFinisiedOperations" );
196 mUndispatchedFinishedOperations.clear();
197
198 //Log_OC.wtf(TAG, "onDestroy end" );
199 super.onDestroy();
200 }
201
202
203 /**
204 * Provides a binder object that clients can use to perform actions on the queue of operations,
205 * except the addition of new operations.
206 */
207 @Override
208 public IBinder onBind(Intent intent) {
209 //Log_OC.wtf(TAG, "onBind" );
210 return mBinder;
211 }
212
213
214 /**
215 * Called when ALL the bound clients were unbound.
216 */
217 @Override
218 public boolean onUnbind(Intent intent) {
219 ((OperationsServiceBinder)mBinder).clearListeners();
220 return false; // not accepting rebinding (default behaviour)
221 }
222
223
224 /**
225 * Binder to let client components to perform actions on the queue of operations.
226 *
227 * It provides by itself the available operations.
228 */
229 public class OperationsServiceBinder extends Binder /* implements OnRemoteOperationListener */ {
230
231 /**
232 * Map of listeners that will be reported about the end of operations from a {@link OperationsServiceBinder} instance
233 */
234 private ConcurrentMap<OnRemoteOperationListener, Handler> mBoundListeners =
235 new ConcurrentHashMap<OnRemoteOperationListener, Handler>();
236
237 /**
238 * Cancels an operation
239 *
240 * TODO
241 */
242 public void cancel() {
243 // TODO
244 }
245
246
247 public void clearListeners() {
248
249 mBoundListeners.clear();
250 }
251
252
253 /**
254 * Adds a listener interested in being reported about the end of operations.
255 *
256 * @param listener Object to notify about the end of operations.
257 * @param callbackHandler {@link Handler} to access the listener without breaking Android threading protection.
258 */
259 public void addOperationListener (OnRemoteOperationListener listener, Handler callbackHandler) {
260 synchronized (mBoundListeners) {
261 mBoundListeners.put(listener, callbackHandler);
262 }
263 }
264
265
266 /**
267 * Removes a listener from the list of objects interested in the being reported about the end of operations.
268 *
269 * @param listener Object to notify about progress of transfer.
270 */
271 public void removeOperationListener (OnRemoteOperationListener listener) {
272 synchronized (mBoundListeners) {
273 mBoundListeners.remove(listener);
274 }
275 }
276
277
278 /**
279 * TODO - IMPORTANT: update implementation when more operations are moved into the service
280 *
281 * @return 'True' when an operation that enforces the user to wait for completion is in process.
282 */
283 public boolean isPerformingBlockingOperation() {
284 return (!mPendingOperations.isEmpty());
285 }
286
287
288 /**
289 * Creates and adds to the queue a new operation, as described by operationIntent
290 *
291 * @param operationIntent Intent describing a new operation to queue and execute.
292 * @return Identifier of the operation created, or null if failed.
293 */
294 public long newOperation(Intent operationIntent) {
295 RemoteOperation operation = null;
296 Target target = null;
297 try {
298 if (!operationIntent.hasExtra(EXTRA_ACCOUNT) &&
299 !operationIntent.hasExtra(EXTRA_SERVER_URL)) {
300 Log_OC.e(TAG, "Not enough information provided in intent");
301
302 } else {
303 Account account = operationIntent.getParcelableExtra(EXTRA_ACCOUNT);
304 String serverUrl = operationIntent.getStringExtra(EXTRA_SERVER_URL);
305 String username = operationIntent.getStringExtra(EXTRA_USERNAME);
306 String password = operationIntent.getStringExtra(EXTRA_PASSWORD);
307 String authToken = operationIntent.getStringExtra(EXTRA_AUTH_TOKEN);
308 boolean followRedirects = operationIntent.getBooleanExtra(EXTRA_FOLLOW_REDIRECTS, true);
309 String cookie = operationIntent.getStringExtra(EXTRA_COOKIE);
310 target = new Target(
311 account,
312 (serverUrl == null) ? null : Uri.parse(serverUrl),
313 username,
314 password,
315 authToken,
316 followRedirects,
317 cookie
318 );
319
320 String action = operationIntent.getAction();
321 if (action.equals(ACTION_CREATE_SHARE)) { // Create Share
322 String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
323 Intent sendIntent = operationIntent.getParcelableExtra(EXTRA_SEND_INTENT);
324 if (remotePath.length() > 0) {
325 operation = new CreateShareOperation(remotePath, ShareType.PUBLIC_LINK,
326 "", false, "", 1, sendIntent);
327 }
328
329 } else if (action.equals(ACTION_UNSHARE)) { // Unshare file
330 String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
331 if (remotePath.length() > 0) {
332 operation = new UnshareLinkOperation(
333 remotePath,
334 OperationsService.this);
335 }
336
337 } else if (action.equals(ACTION_GET_SERVER_INFO)) {
338 // check OC server and get basic information from it
339 String authTokenType =
340 operationIntent.getStringExtra(EXTRA_AUTH_TOKEN_TYPE);
341 operation = new GetServerInfoOperation(
342 serverUrl, authTokenType, OperationsService.this);
343
344 } else if (action.equals(ACTION_OAUTH2_GET_ACCESS_TOKEN)) {
345 /// GET ACCESS TOKEN to the OAuth server
346 String oauth2QueryParameters =
347 operationIntent.getStringExtra(EXTRA_OAUTH2_QUERY_PARAMETERS);
348 operation = new OAuth2GetAccessToken(
349 getString(R.string.oauth2_client_id),
350 getString(R.string.oauth2_redirect_uri),
351 getString(R.string.oauth2_grant_type),
352 oauth2QueryParameters);
353
354 } else if (action.equals(ACTION_EXISTENCE_CHECK)) {
355 // Existence Check
356 String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
357 boolean successIfAbsent = operationIntent.getBooleanExtra(EXTRA_SUCCESS_IF_ABSENT, true);
358 operation = new ExistenceCheckRemoteOperation(remotePath, OperationsService.this, successIfAbsent);
359
360 } else if (action.equals(ACTION_GET_USER_NAME)) {
361 // Get User Name
362 operation = new GetRemoteUserNameOperation();
363
364 } else if (action.equals(ACTION_RENAME)) {
365 // Rename file or folder
366 String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
367 String newName = operationIntent.getStringExtra(EXTRA_NEWNAME);
368 operation = new RenameFileOperation(remotePath, account, newName);
369
370 } else if (action.equals(ACTION_REMOVE)) {
371 // Remove file or folder
372 String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
373 boolean onlyLocalCopy = operationIntent.getBooleanExtra(EXTRA_REMOVE_ONLY_LOCAL, false);
374 operation = new RemoveFileOperation(remotePath, onlyLocalCopy);
375
376 } else if (action.equals(ACTION_CREATE_FOLDER)) {
377 // Create Folder
378 String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
379 boolean createFullPath = operationIntent.getBooleanExtra(EXTRA_CREATE_FULL_PATH, true);
380 operation = new CreateFolderOperation(remotePath, createFullPath);
381
382 } else if (action.equals(ACTION_SYNC_FILE)) {
383 // Sync file
384 String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
385 boolean syncFileContents = operationIntent.getBooleanExtra(EXTRA_SYNC_FILE_CONTENTS, true);
386 operation = new SynchronizeFileOperation(remotePath, account, syncFileContents, getApplicationContext());
387 }
388
389 }
390
391 } catch (IllegalArgumentException e) {
392 Log_OC.e(TAG, "Bad information provided in intent: " + e.getMessage());
393 operation = null;
394 }
395
396 if (operation != null) {
397 mPendingOperations.add(new Pair<Target , RemoteOperation>(target, operation));
398 startService(new Intent(OperationsService.this, OperationsService.class));
399 //Log_OC.wtf(TAG, "New operation added, opId: " + operation.hashCode());
400 // better id than hash? ; should be good enough by the time being
401 return operation.hashCode();
402
403 } else {
404 //Log_OC.wtf(TAG, "New operation failed, returned Long.MAX_VALUE");
405 return Long.MAX_VALUE;
406 }
407 }
408
409 public boolean dispatchResultIfFinished(int operationId, OnRemoteOperationListener listener) {
410 Pair<RemoteOperation, RemoteOperationResult> undispatched =
411 mUndispatchedFinishedOperations.remove(operationId);
412 if (undispatched != null) {
413 listener.onRemoteOperationFinish(undispatched.first, undispatched.second);
414 return true;
415 //Log_OC.wtf(TAG, "Sending callback later");
416 } else {
417 if (!mPendingOperations.isEmpty()) {
418 return true;
419 } else {
420 return false;
421 }
422 //Log_OC.wtf(TAG, "Not finished yet");
423 }
424 }
425
426 }
427
428
429 /**
430 * Operations worker. Performs the pending operations in the order they were requested.
431 *
432 * Created with the Looper of a new thread, started in {@link OperationsService#onCreate()}.
433 */
434 private static class ServiceHandler extends Handler {
435 // don't make it a final class, and don't remove the static ; lint will warn about a possible memory leak
436 OperationsService mService;
437 public ServiceHandler(Looper looper, OperationsService service) {
438 super(looper);
439 if (service == null) {
440 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
441 }
442 mService = service;
443 }
444
445 @Override
446 public void handleMessage(Message msg) {
447 mService.nextOperation();
448 mService.stopSelf(msg.arg1);
449 }
450 }
451
452
453 /**
454 * Performs the next operation in the queue
455 */
456 private void nextOperation() {
457
458 //Log_OC.wtf(TAG, "nextOperation init" );
459
460 Pair<Target, RemoteOperation> next = null;
461 synchronized(mPendingOperations) {
462 next = mPendingOperations.peek();
463 }
464
465 if (next != null) {
466
467 mCurrentOperation = next.second;
468 RemoteOperationResult result = null;
469 try {
470 /// prepare client object to send the request to the ownCloud server
471 if (mLastTarget == null || !mLastTarget.equals(next.first)) {
472 mLastTarget = next.first;
473 if (mLastTarget.mAccount != null) {
474 OwnCloudAccount ocAccount = new OwnCloudAccount(mLastTarget.mAccount, this);
475 mOwnCloudClient = OwnCloudClientManagerFactory.getDefaultSingleton().
476 getClientFor(ocAccount, this);
477 mStorageManager =
478 new FileDataStorageManager(
479 mLastTarget.mAccount,
480 getContentResolver());
481 } else {
482 OwnCloudCredentials credentials = null;
483 if (mLastTarget.mUsername != null) {
484 credentials = OwnCloudCredentialsFactory.newBasicCredentials(
485 mLastTarget.mUsername,
486 mLastTarget.mPassword); // basic
487
488 } else if (mLastTarget.mAuthToken != null) {
489 credentials = OwnCloudCredentialsFactory.newBearerCredentials(
490 mLastTarget.mAuthToken); // bearer token
491
492 } else if (mLastTarget.mCookie != null) {
493 credentials = OwnCloudCredentialsFactory.newSamlSsoCredentials(
494 mLastTarget.mCookie); // SAML SSO
495 }
496 OwnCloudAccount ocAccount = new OwnCloudAccount(
497 mLastTarget.mServerUrl, credentials);
498 mOwnCloudClient = OwnCloudClientManagerFactory.getDefaultSingleton().
499 getClientFor(ocAccount, this);
500 mOwnCloudClient.setFollowRedirects(mLastTarget.mFollowRedirects);
501 mStorageManager = null;
502 }
503 }
504
505 /// perform the operation
506 if (mCurrentOperation instanceof SyncOperation) {
507 result = ((SyncOperation)mCurrentOperation).execute(mOwnCloudClient, mStorageManager);
508 } else {
509 result = mCurrentOperation.execute(mOwnCloudClient);
510 }
511
512 } catch (AccountsException e) {
513 if (mLastTarget.mAccount == null) {
514 Log_OC.e(TAG, "Error while trying to get authorization for a NULL account", e);
515 } else {
516 Log_OC.e(TAG, "Error while trying to get authorization for " + mLastTarget.mAccount.name, e);
517 }
518 result = new RemoteOperationResult(e);
519
520 } catch (IOException e) {
521 if (mLastTarget.mAccount == null) {
522 Log_OC.e(TAG, "Error while trying to get authorization for a NULL account", e);
523 } else {
524 Log_OC.e(TAG, "Error while trying to get authorization for " + mLastTarget.mAccount.name, e);
525 }
526 result = new RemoteOperationResult(e);
527 } catch (Exception e) {
528 if (mLastTarget.mAccount == null) {
529 Log_OC.e(TAG, "Unexpected error for a NULL account", e);
530 } else {
531 Log_OC.e(TAG, "Unexpected error for " + mLastTarget.mAccount.name, e);
532 }
533 result = new RemoteOperationResult(e);
534
535 } finally {
536 synchronized(mPendingOperations) {
537 mPendingOperations.poll();
538 }
539 }
540
541 //sendBroadcastOperationFinished(mLastTarget, mCurrentOperation, result);
542 dispatchResultToOperationListeners(mLastTarget, mCurrentOperation, result);
543 }
544 }
545
546
547 /**
548 * Sends a broadcast when a new operation is added to the queue.
549 *
550 * Local broadcasts are only delivered to activities in the same process, but can't be done sticky :\
551 *
552 * @param target Account or URL pointing to an OC server.
553 * @param operation Added operation.
554 */
555 private void sendBroadcastNewOperation(Target target, RemoteOperation operation) {
556 Intent intent = new Intent(ACTION_OPERATION_ADDED);
557 if (target.mAccount != null) {
558 intent.putExtra(EXTRA_ACCOUNT, target.mAccount);
559 } else {
560 intent.putExtra(EXTRA_SERVER_URL, target.mServerUrl);
561 }
562 //LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
563 //lbm.sendBroadcast(intent);
564 sendStickyBroadcast(intent);
565 }
566
567
568 // TODO - maybe add a notification for real start of operations
569
570 /**
571 * Sends a LOCAL broadcast when an operations finishes in order to the interested activities can update their view
572 *
573 * Local broadcasts are only delivered to activities in the same process.
574 *
575 * @param target Account or URL pointing to an OC server.
576 * @param operation Finished operation.
577 * @param result Result of the operation.
578 */
579 private void sendBroadcastOperationFinished(Target target, RemoteOperation operation, RemoteOperationResult result) {
580 Intent intent = new Intent(ACTION_OPERATION_FINISHED);
581 intent.putExtra(EXTRA_RESULT, result);
582 if (target.mAccount != null) {
583 intent.putExtra(EXTRA_ACCOUNT, target.mAccount);
584 } else {
585 intent.putExtra(EXTRA_SERVER_URL, target.mServerUrl);
586 }
587 //LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
588 //lbm.sendBroadcast(intent);
589 sendStickyBroadcast(intent);
590 }
591
592
593 /**
594 * Notifies the currently subscribed listeners about the end of an operation.
595 *
596 * @param target Account or URL pointing to an OC server.
597 * @param operation Finished operation.
598 * @param result Result of the operation.
599 */
600 private void dispatchResultToOperationListeners(
601 Target target, final RemoteOperation operation, final RemoteOperationResult result) {
602 int count = 0;
603 Iterator<OnRemoteOperationListener> listeners = mBinder.mBoundListeners.keySet().iterator();
604 while (listeners.hasNext()) {
605 final OnRemoteOperationListener listener = listeners.next();
606 final Handler handler = mBinder.mBoundListeners.get(listener);
607 if (handler != null) {
608 handler.post(new Runnable() {
609 @Override
610 public void run() {
611 listener.onRemoteOperationFinish(operation, result);
612 }
613 });
614 count += 1;
615 }
616 }
617 if (count == 0) {
618 //mOperationResults.put(operation.hashCode(), result);
619 Pair<RemoteOperation, RemoteOperationResult> undispatched =
620 new Pair<RemoteOperation, RemoteOperationResult>(operation, result);
621 mUndispatchedFinishedOperations.put(operation.hashCode(), undispatched);
622 }
623 Log_OC.d(TAG, "Called " + count + " listeners");
624 }
625
626
627 }