• 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.squareup.okhttp.mockwebserver;
17 
18 import java.net.HttpURLConnection;
19 import java.util.concurrent.BlockingQueue;
20 import java.util.concurrent.LinkedBlockingQueue;
21 import java.util.logging.Logger;
22 
23 /**
24  * Default dispatcher that processes a script of responses. Populate the script
25  * by calling {@link #enqueueResponse(MockResponse)}.
26  */
27 public class QueueDispatcher extends Dispatcher {
28   private static final Logger logger = Logger.getLogger(QueueDispatcher.class.getName());
29   protected final BlockingQueue<MockResponse> responseQueue = new LinkedBlockingQueue<>();
30   private MockResponse failFastResponse;
31 
dispatch(RecordedRequest request)32   @Override public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
33     // To permit interactive/browser testing, ignore requests for favicons.
34     final String requestLine = request.getRequestLine();
35     if (requestLine != null && requestLine.equals("GET /favicon.ico HTTP/1.1")) {
36       logger.info("served " + requestLine);
37       return new MockResponse().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