View Javadoc

1   // ========================================================================
2   // Copyright (c) 2006-2009 Mort Bay Consulting Pty. Ltd.
3   // ------------------------------------------------------------------------
4   // All rights reserved. This program and the accompanying materials
5   // are made available under the terms of the Eclipse Public License v1.0
6   // and Apache License v2.0 which accompanies this distribution.
7   // The Eclipse Public License is available at
8   // http://www.eclipse.org/legal/epl-v10.html
9   // The Apache License v2.0 is available at
10  // http://www.opensource.org/licenses/apache2.0.php
11  // You may elect to redistribute this code under either of these licenses.
12  // ========================================================================
13  package org.eclipse.jetty.client;
14  
15  import java.io.IOException;
16  
17  import org.eclipse.jetty.http.HttpFields;
18  import org.eclipse.jetty.io.Buffer;
19  
20  /**
21   * An exchange that retains response status and response headers for later use.
22   */
23  public class CachedExchange extends HttpExchange
24  {
25      private final HttpFields _responseFields;
26      private volatile int _responseStatus;
27  
28      /**
29       * Creates a new CachedExchange.
30       *
31       * @param cacheHeaders true to cache response headers, false to not cache them
32       */
33      public CachedExchange(boolean cacheHeaders)
34      {
35          _responseFields = cacheHeaders ? new HttpFields() : null;
36      }
37  
38      public synchronized int getResponseStatus()
39      {
40          if (getStatus() < HttpExchange.STATUS_PARSING_HEADERS)
41              throw new IllegalStateException("Response not received yet");
42          return _responseStatus;
43      }
44  
45      public synchronized HttpFields getResponseFields()
46      {
47          if (getStatus() < HttpExchange.STATUS_PARSING_CONTENT)
48              throw new IllegalStateException("Headers not completely received yet");
49          return _responseFields;
50      }
51  
52      @Override
53      protected synchronized void onResponseStatus(Buffer version, int status, Buffer reason) throws IOException
54      {
55          _responseStatus = status;
56          super.onResponseStatus(version, status, reason);
57      }
58  
59      @Override
60      protected synchronized void onResponseHeader(Buffer name, Buffer value) throws IOException
61      {
62          if (_responseFields != null)
63              _responseFields.add(name, value);
64          super.onResponseHeader(name, value);
65      }
66  }