1 /*
2 * Copyright (c) 2002-2026 Gargoyle Software 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 * https://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15 package org.htmlunit;
16
17 import java.util.Collections;
18 import java.util.List;
19
20 import org.htmlunit.util.NameValuePair;
21 import org.htmlunit.util.WebResponseWrapper;
22
23 /**
24 * A {@link WebResponse} implementation to deliver with content from cache. The response
25 * is the same but the request may have some variation like an anchor.
26 *
27 * @author Marc Guillemot
28 * @author Ronald Brill
29 */
30 class WebResponseFromCache extends WebResponseWrapper {
31
32 private final WebRequest request_;
33 private final List<NameValuePair> responseHeaders_;
34
35 /**
36 * Wraps the provided cached response for a new request.
37 * @param cachedResponse the response from cache
38 * @param overwriteHeaders list of headers to overwrite cachedResponse headers
39 * @param currentRequest the new request
40 */
41 WebResponseFromCache(final WebResponse cachedResponse,
42 final List<NameValuePair> overwriteHeaders, final WebRequest currentRequest) {
43 super(cachedResponse);
44 request_ = currentRequest;
45 responseHeaders_ = Collections.unmodifiableList(overwriteHeaders);
46 }
47
48 /**
49 * Wraps the provided response for the given request
50 * @param cachedResponse the response from cache
51 * @param currentRequest the new request
52 */
53 WebResponseFromCache(final WebResponse cachedResponse, final WebRequest currentRequest) {
54 super(cachedResponse);
55 request_ = currentRequest;
56 responseHeaders_ = null;
57 }
58
59 /**
60 * {@inheritDoc}
61 */
62 @Override
63 public WebRequest getWebRequest() {
64 return request_;
65 }
66
67 /**
68 * {@inheritDoc}
69 */
70 @Override
71 public List<NameValuePair> getResponseHeaders() {
72 return responseHeaders_ != null ? responseHeaders_ : super.getResponseHeaders();
73 }
74
75 /**
76 * {@inheritDoc}
77 */
78 @Override
79 public String getResponseHeaderValue(final String headerName) {
80 if (responseHeaders_ == null) {
81 return super.getResponseHeaderValue(headerName);
82 }
83
84 for (final NameValuePair pair : responseHeaders_) {
85 if (pair.getName().equalsIgnoreCase(headerName)) {
86 return pair.getValue();
87 }
88 }
89 return null;
90 }
91 }