Subversion Repositories SmartDukaan

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
21478 rajender 1
/*
2
 * Copyright (C) 2011 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.volley.mock;
18
 
19
import com.android.volley.NetworkResponse;
20
import com.android.volley.Request;
21
import com.android.volley.Response;
22
 
23
import java.util.concurrent.PriorityBlockingQueue;
24
import java.util.concurrent.Semaphore;
25
import java.util.concurrent.TimeUnit;
26
import java.util.concurrent.TimeoutException;
27
 
28
// TODO: the name of this class sucks
29
@SuppressWarnings("serial")
30
public class WaitableQueue extends PriorityBlockingQueue<Request<?>> {
31
    private final Request<?> mStopRequest = new MagicStopRequest();
32
    private final Semaphore mStopEvent = new Semaphore(0);
33
 
34
    // TODO: this isn't really "until empty" it's "until next call to take() after empty"
35
    public void waitUntilEmpty(long timeoutMillis)
36
            throws TimeoutException, InterruptedException {
37
        add(mStopRequest);
38
        if (!mStopEvent.tryAcquire(timeoutMillis, TimeUnit.MILLISECONDS)) {
39
            throw new TimeoutException();
40
        }
41
    }
42
 
43
    @Override
44
    public Request<?> take() throws InterruptedException {
45
        Request<?> item = super.take();
46
        if (item == mStopRequest) {
47
            mStopEvent.release();
48
            return take();
49
        }
50
        return item;
51
    }
52
 
53
    private static class MagicStopRequest extends Request<Object> {
54
        public MagicStopRequest() {
55
            super(Request.Method.GET, "", null);
56
        }
57
 
58
        @Override
59
        public Priority getPriority() {
60
            return Priority.LOW;
61
        }
62
 
63
        @Override
64
        protected Response<Object> parseNetworkResponse(NetworkResponse response) {
65
            return null;
66
        }
67
 
68
        @Override
69
        protected void deliverResponse(Object response) {
70
        }
71
    }
72
}