1 /*
2  * Copyright (C) 2015 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.mtp;
18 
19 import android.database.ContentObserver;
20 import android.net.Uri;
21 import android.test.mock.MockContentResolver;
22 
23 import junit.framework.Assert;
24 
25 import java.util.HashMap;
26 import java.util.Map;
27 import java.util.concurrent.Phaser;
28 import java.util.concurrent.TimeUnit;
29 import java.util.concurrent.TimeoutException;
30 
31 class TestContentResolver extends MockContentResolver {
32     private static final int TIMEOUT_PERIOD_MS = 3000;
33     private final Map<Uri, Phaser> mPhasers = new HashMap<>();
34 
35     @Override
notifyChange(Uri uri, ContentObserver observer, boolean syncToNetwork)36     public void notifyChange(Uri uri, ContentObserver observer, boolean syncToNetwork) {
37         getPhaser(uri).arrive();
38     }
39 
40 
waitForNotification(Uri uri, int count)41     void waitForNotification(Uri uri, int count) throws InterruptedException, TimeoutException {
42         Assert.assertEquals(count, getPhaser(uri).awaitAdvanceInterruptibly(
43                 count - 1, TIMEOUT_PERIOD_MS, TimeUnit.MILLISECONDS));
44     }
45 
getChangeCount(Uri uri)46     int getChangeCount(Uri uri) {
47         if (mPhasers.containsKey(uri)) {
48             return mPhasers.get(uri).getPhase();
49         } else {
50             return 0;
51         }
52     }
53 
getPhaser(Uri uri)54     private synchronized Phaser getPhaser(Uri uri) {
55         Phaser phaser = mPhasers.get(uri);
56         if (phaser == null) {
57             phaser = new Phaser(1);
58             mPhasers.put(uri, phaser);
59         }
60         return phaser;
61     }
62 }
63