1 /*
2 * Copyright (c) 2002-2025 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 */
29 class WebResponseFromCache extends WebResponseWrapper {
30
31 private final WebRequest request_;
32 private final List<NameValuePair> responseHeaders_;
33
34 /**
35 * Wraps the provided cached response for a new request.
36 * @param cachedResponse the response from cache
37 * @param overwriteHeaders list of headers to overwrite cachedResponse headers
38 * @param currentRequest the new request
39 */
40 WebResponseFromCache(final WebResponse cachedResponse,
41 final List<NameValuePair> overwriteHeaders, final WebRequest currentRequest) {
42 super(cachedResponse);
43 request_ = currentRequest;
44 responseHeaders_ = Collections.unmodifiableList(overwriteHeaders);
45 }
46
47 /**
48 * Wraps the provided response for the given request
49 * @param cachedResponse the response from cache
50 * @param currentRequest the new request
51 */
52 WebResponseFromCache(final WebResponse cachedResponse, final WebRequest currentRequest) {
53 super(cachedResponse);
54 request_ = currentRequest;
55 responseHeaders_ = null;
56 }
57
58 /**
59 * {@inheritDoc}
60 */
61 @Override
62 public WebRequest getWebRequest() {
63 return request_;
64 }
65
66 /**
67 * {@inheritDoc}
68 */
69 @Override
70 public List<NameValuePair> getResponseHeaders() {
71 return responseHeaders_ != null ? responseHeaders_ : super.getResponseHeaders();
72 }
73
74 /**
75 * {@inheritDoc}
76 */
77 @Override
78 public String getResponseHeaderValue(final String headerName) {
79 if (responseHeaders_ == null) {
80 return super.getResponseHeaderValue(headerName);
81 }
82
83 for (final NameValuePair pair : responseHeaders_) {
84 if (pair.getName().equalsIgnoreCase(headerName)) {
85 return pair.getValue();
86 }
87 }
88 return null;
89 }
90 }