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