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
17package com.android.mtp;
18
19import android.database.ContentObserver;
20import android.net.Uri;
21import android.test.mock.MockContentResolver;
22
23import junit.framework.Assert;
24
25import java.util.HashMap;
26import java.util.Map;
27import java.util.concurrent.Phaser;
28import java.util.concurrent.TimeUnit;
29import java.util.concurrent.TimeoutException;
30
31class TestContentResolver extends MockContentResolver {
32    private static final int TIMEOUT_PERIOD_MS = 3000;
33    private final Map<Uri, Phaser> mPhasers = new HashMap<>();
34
35    @Override
36    public void notifyChange(Uri uri, ContentObserver observer, boolean syncToNetwork) {
37        getPhaser(uri).arrive();
38    }
39
40
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
46    int getChangeCount(Uri uri) {
47        if (mPhasers.containsKey(uri)) {
48            return mPhasers.get(uri).getPhase();
49        } else {
50            return 0;
51        }
52    }
53
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