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 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 48 @Override public SocketPolicy peekSocketPolicy() { 49 MockResponse peek = responseQueue.peek(); 50 if (peek == null) { 51 return failFastResponse != null 52 ? failFastResponse.getSocketPolicy() 53 : SocketPolicy.KEEP_OPEN; 54 } 55 return peek.getSocketPolicy(); 56 } 57 58 public void enqueueResponse(MockResponse response) { 59 responseQueue.add(response); 60 } 61 62 public void setFailFast(boolean failFast) { 63 MockResponse failFastResponse = failFast 64 ? new MockResponse().setResponseCode(HttpURLConnection.HTTP_NOT_FOUND) 65 : null; 66 setFailFast(failFastResponse); 67 } 68 69 public void setFailFast(MockResponse failFastResponse) { 70 this.failFastResponse = failFastResponse; 71 } 72 } 73