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