View Javadoc
1   /* 
2    * Licensed under the Apache License, Version 2.0 (the "License");
3    * you may not use this file except in compliance with the License.
4    * You may obtain a copy of the License at
5    *
6    * http://www.apache.org/licenses/LICENSE-2.0
7    *
8    * Unless required by applicable law or agreed to in writing, software
9    * distributed under the License is distributed on an "AS IS" BASIS,
10   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11   * See the License for the specific language governing permissions and
12   * limitations under the License.
13   *
14   */
15  package org.esigate.test.conn;
16  
17  import java.util.HashMap;
18  import java.util.Map;
19  
20  import org.apache.http.HttpRequest;
21  import org.apache.http.HttpResponse;
22  
23  /**
24   * 
25   * A response handler, which returns different HTTP reponses according to the requested URI.
26   * 
27   * Sends IllegalStateException if no reponse has been defined for the requested uri.
28   * 
29   * @author Nicolas Richeton
30   * 
31   */
32  public class UriResponse implements IResponseHandler {
33      private Map<String, HttpResponse> responses = new HashMap<>();
34  
35      @Override
36      public HttpResponse execute(HttpRequest request) {
37          String uri = request.getRequestLine().getUri();
38          HttpResponse result = this.responses.get(uri);
39          if (result == null) {
40              throw new IllegalStateException("No response for uri: " + uri);
41          }
42          return result;
43      }
44  
45      /**
46       * Add a Http reponse.
47       * 
48       * <p>
49       * 
50       * <pre>
51       * response(&quot;http://host/path1&quot;, httpResponse)
52       * </pre>
53       * 
54       * @param uri
55       *            Full uri including protocol, host, port if any, path and query params.
56       * 
57       * 
58       * @param response
59       * @return this object
60       */
61      public UriResponse response(String uri, HttpResponse response) {
62          this.responses.put(uri, response);
63          return this;
64      }
65  
66  }