• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2012 Google Inc.
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 package com.google.mockwebserver;
17 
18 import java.net.HttpURLConnection;
19 import java.util.concurrent.BlockingQueue;
20 import java.util.concurrent.LinkedBlockingQueue;
21 
22 /**
23  * Default dispatcher that processes a script of responses.  Populate the script by calling
24  * {@link #enqueueResponse(MockResponse)}.
25  */
26 public class QueueDispatcher extends Dispatcher {
27     protected final BlockingQueue<MockResponse> responseQueue
28             = new LinkedBlockingQueue<MockResponse>();
29     private MockResponse failFastResponse;
30 
dispatch(RecordedRequest request)31     @Override public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
32         // to permit interactive/browser testing, ignore requests for favicons
33         final String requestLine = request.getRequestLine();
34         if (requestLine != null && requestLine.equals("GET /favicon.ico HTTP/1.1")) {
35             System.out.println("served " + requestLine);
36             return new MockResponse()
37                     .setResponseCode(HttpURLConnection.HTTP_NOT_FOUND);
38         }
39 
40         if (failFastResponse != null && responseQueue.peek() == null) {
41             // Fail fast if there's no response queued up.
42             return failFastResponse;
43         }
44 
45         return responseQueue.take();
46     }
47 
peek()48     @Override public MockResponse peek() {
49         MockResponse peek = responseQueue.peek();
50         if (peek != null) return peek;
51         if (failFastResponse != null) return failFastResponse;
52         return super.peek();
53     }
54 
enqueueResponse(MockResponse response)55     public void enqueueResponse(MockResponse response) {
56         responseQueue.add(response);
57     }
58 
setFailFast(boolean failFast)59     public void setFailFast(boolean failFast) {
60         MockResponse failFastResponse = failFast
61                 ? new MockResponse().setResponseCode(HttpURLConnection.HTTP_NOT_FOUND)
62                 : null;
63         setFailFast(failFastResponse);
64     }
65 
setFailFast(MockResponse failFastResponse)66     public void setFailFast(MockResponse failFastResponse) {
67         this.failFastResponse = failFastResponse;
68     }
69 }
70