View Javadoc
1   /*
2    * ====================================================================
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *   http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing,
14   * software distributed under the License is distributed on an
15   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16   * KIND, either express or implied.  See the License for the
17   * specific language governing permissions and limitations
18   * under the License.
19   * ====================================================================
20   *
21   * This software consists of voluntary contributions made by many
22   * individuals on behalf of the Apache Software Foundation.  For more
23   * information on the Apache Software Foundation, please see
24   * <http://www.apache.org/>.
25   *
26   */
27  package org.apache.hc.client5.http.impl.cache;
28  
29  import java.io.InputStream;
30  import java.util.Date;
31  import java.util.HashMap;
32  import java.util.Iterator;
33  import java.util.Map;
34  import java.util.Random;
35  
36  import org.apache.hc.client5.http.cache.HttpCacheEntry;
37  import org.apache.hc.client5.http.utils.DateUtils;
38  import org.apache.hc.core5.http.ClassicHttpRequest;
39  import org.apache.hc.core5.http.ClassicHttpResponse;
40  import org.apache.hc.core5.http.Header;
41  import org.apache.hc.core5.http.HeaderElement;
42  import org.apache.hc.core5.http.HttpEntity;
43  import org.apache.hc.core5.http.HttpHeaders;
44  import org.apache.hc.core5.http.HttpMessage;
45  import org.apache.hc.core5.http.HttpRequest;
46  import org.apache.hc.core5.http.HttpResponse;
47  import org.apache.hc.core5.http.HttpStatus;
48  import org.apache.hc.core5.http.HttpVersion;
49  import org.apache.hc.core5.http.ProtocolVersion;
50  import org.apache.hc.core5.http.io.entity.ByteArrayEntity;
51  import org.apache.hc.core5.http.message.BasicClassicHttpRequest;
52  import org.apache.hc.core5.http.message.BasicClassicHttpResponse;
53  import org.apache.hc.core5.http.message.BasicHeader;
54  import org.apache.hc.core5.http.message.MessageSupport;
55  import org.apache.hc.core5.util.ByteArrayBuffer;
56  import org.apache.hc.core5.util.LangUtils;
57  import org.junit.Assert;
58  
59  public class HttpTestUtils {
60  
61      /*
62       * "The following HTTP/1.1 headers are hop-by-hop headers..."
63       *
64       * @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.5.1
65       */
66      private static final String[] HOP_BY_HOP_HEADERS = { "Connection", "Keep-Alive", "Proxy-Authenticate",
67          "Proxy-Authorization", "TE", "Trailers", "Transfer-Encoding", "Upgrade" };
68  
69      /*
70       * "Multiple message-header fields with the same field-name MAY be present
71       * in a message if and only if the entire field-value for that header field
72       * is defined as a comma-separated list [i.e., #(values)]."
73       *
74       * @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2
75       */
76      private static final String[] MULTI_HEADERS = { "Accept", "Accept-Charset", "Accept-Encoding",
77          "Accept-Language", "Allow", "Cache-Control", "Connection", "Content-Encoding",
78          "Content-Language", "Expect", "Pragma", "Proxy-Authenticate", "TE", "Trailer",
79          "Transfer-Encoding", "Upgrade", "Via", HttpHeaders.WARNING, "WWW-Authenticate" };
80      private static final String[] SINGLE_HEADERS = { "Accept-Ranges", "Age", "Authorization",
81          "Content-Length", "Content-Location", "Content-MD5", "Content-Range", "Content-Type",
82          "Date", "ETag", "Expires", "From", "Host", "If-Match", "If-Modified-Since",
83          "If-None-Match", "If-Range", "If-Unmodified-Since", "Last-Modified", "Location",
84          "Max-Forwards", "Proxy-Authorization", "Range", "Referer", "Retry-After", "Server",
85          "User-Agent", "Vary" };
86  
87      /*
88       * Determines whether the given header name is considered a hop-by-hop
89       * header.
90       *
91       * @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.5.1
92       */
93      public static boolean isHopByHopHeader(final String name) {
94          for (final String s : HOP_BY_HOP_HEADERS) {
95              if (s.equalsIgnoreCase(name)) {
96                  return true;
97              }
98          }
99          return false;
100     }
101 
102     /*
103      * Determines whether a given header name may only appear once in a message.
104      */
105     public static boolean isSingleHeader(final String name) {
106         for (final String s : SINGLE_HEADERS) {
107             if (s.equalsIgnoreCase(name)) {
108                 return true;
109             }
110         }
111         return false;
112     }
113     /*
114      * Assert.asserts that two request or response bodies are byte-equivalent.
115      */
116     public static boolean equivalent(final HttpEntity e1, final HttpEntity e2) throws Exception {
117         final InputStream i1 = e1.getContent();
118         final InputStream i2 = e2.getContent();
119         if (i1 == null && i2 == null) {
120             return true;
121         }
122         if (i1 == null || i2 == null) {
123             return false; // avoid possible NPEs below
124         }
125         int b1 = -1;
126         while ((b1 = i1.read()) != -1) {
127             if (b1 != i2.read()) {
128                 return false;
129             }
130         }
131         return (-1 == i2.read());
132     }
133 
134     /*
135      * Retrieves the full header value by combining multiple headers and
136      * separating with commas, canonicalizing whitespace along the way.
137      *
138      * @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2
139      */
140     public static String getCanonicalHeaderValue(final HttpMessage r, final String name) {
141         if (isSingleHeader(name)) {
142             final Header h = r.getFirstHeader(name);
143             return (h != null) ? h.getValue() : null;
144         }
145         final StringBuilder buf = new StringBuilder();
146         boolean first = true;
147         for (final Header h : r.getHeaders(name)) {
148             if (!first) {
149                 buf.append(", ");
150             }
151             buf.append(h.getValue().trim());
152             first = false;
153         }
154         return buf.toString();
155     }
156 
157     /*
158      * Assert.asserts that all the headers appearing in r1 also appear in r2
159      * with the same canonical header values.
160      */
161     public static boolean isEndToEndHeaderSubset(final HttpMessage r1, final HttpMessage r2) {
162         for (final Header h : r1.getHeaders()) {
163             if (!isHopByHopHeader(h.getName())) {
164                 final String r1val = getCanonicalHeaderValue(r1, h.getName());
165                 final String r2val = getCanonicalHeaderValue(r2, h.getName());
166                 if (!r1val.equals(r2val)) {
167                     return false;
168                 }
169             }
170         }
171         return true;
172     }
173 
174     /*
175      * Assert.asserts that message {@code r2} represents exactly the same
176      * message as {@code r1}, except for hop-by-hop headers. "When a cache
177      * is semantically transparent, the client receives exactly the same
178      * response (except for hop-by-hop headers) that it would have received had
179      * its request been handled directly by the origin server."
180      *
181      * @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec1.html#sec1.3
182      */
183     public static boolean semanticallyTransparent(
184             final ClassicHttpResponse r1, final ClassicHttpResponse r2) throws Exception {
185         final boolean entitiesEquivalent = equivalent(r1.getEntity(), r2.getEntity());
186         if (!entitiesEquivalent) {
187             return false;
188         }
189         final boolean statusLinesEquivalent = LangUtils.equals(r1.getReasonPhrase(), r2.getReasonPhrase())
190                 && r1.getCode() == r2.getCode();
191         if (!statusLinesEquivalent) {
192             return false;
193         }
194         return isEndToEndHeaderSubset(r1, r2);
195     }
196 
197     /* Assert.asserts that protocol versions equivalent. */
198     public static boolean equivalent(final ProtocolVersion v1, final ProtocolVersion v2) {
199         return LangUtils.equals(v1 != null ? v1 : HttpVersion.DEFAULT, v2 != null ? v2 : HttpVersion.DEFAULT );
200     }
201 
202     /* Assert.asserts that two requests are morally equivalent. */
203     public static boolean equivalent(final HttpRequest r1, final HttpRequest r2) {
204         return equivalent(r1.getVersion(), r2.getVersion()) &&
205                 LangUtils.equals(r1.getMethod(), r2.getMethod()) &&
206                 LangUtils.equals(r1.getRequestUri(), r2.getRequestUri()) &&
207                 isEndToEndHeaderSubset(r1, r2);
208     }
209 
210     /* Assert.asserts that two requests are morally equivalent. */
211     public static boolean equivalent(final HttpResponse r1, final HttpResponse r2) {
212         return equivalent(r1.getVersion(), r2.getVersion()) &&
213                 r1.getCode() == r2.getCode() &&
214                 LangUtils.equals(r1.getReasonPhrase(), r2.getReasonPhrase()) &&
215                 isEndToEndHeaderSubset(r1, r2);
216     }
217 
218     public static byte[] getRandomBytes(final int nbytes) {
219         final byte[] bytes = new byte[nbytes];
220         new Random().nextBytes(bytes);
221         return bytes;
222     }
223 
224     public static ByteArrayBuffer getRandomBuffer(final int nbytes) {
225         final ByteArrayBuffer buf = new ByteArrayBuffer(nbytes);
226         buf.setLength(nbytes);
227         new Random().nextBytes(buf.array());
228         return buf;
229     }
230 
231     /** Generates a response body with random content.
232      *  @param nbytes length of the desired response body
233      *  @return an {@link HttpEntity}
234      */
235     public static HttpEntity makeBody(final int nbytes) {
236         return new ByteArrayEntity(getRandomBytes(nbytes), null);
237     }
238 
239     public static HttpCacheEntry makeCacheEntry(final Date requestDate, final Date responseDate) {
240         final Date when = new Date((responseDate.getTime() + requestDate.getTime()) / 2);
241         return makeCacheEntry(requestDate, responseDate, getStockHeaders(when));
242     }
243 
244     public static Header[] getStockHeaders(final Date when) {
245         final Header[] headers = {
246                 new BasicHeader("Date", DateUtils.formatDate(when)),
247                 new BasicHeader("Server", "MockServer/1.0")
248         };
249         return headers;
250     }
251 
252     public static HttpCacheEntry makeCacheEntry(final Date requestDate,
253             final Date responseDate, final Header[] headers) {
254         final byte[] bytes = getRandomBytes(128);
255         return makeCacheEntry(requestDate, responseDate, headers, bytes);
256     }
257 
258     public static HttpCacheEntry makeCacheEntry(final Date requestDate,
259             final Date responseDate, final Header[] headers, final byte[] bytes) {
260         final Map<String,String> variantMap = null;
261         return makeCacheEntry(requestDate, responseDate, headers, bytes,
262                 variantMap);
263     }
264 
265     public static HttpCacheEntry makeCacheEntry(final Map<String,String> variantMap) {
266         final Date now = new Date();
267         return makeCacheEntry(now, now, getStockHeaders(now),
268                 getRandomBytes(128), variantMap);
269     }
270 
271     public static HttpCacheEntry makeCacheEntry(final Date requestDate,
272             final Date responseDate, final Header[] headers, final byte[] bytes,
273             final Map<String,String> variantMap) {
274         return new HttpCacheEntry(requestDate, responseDate, HttpStatus.SC_OK, headers, new HeapResource(bytes), variantMap);
275     }
276 
277     public static HttpCacheEntry makeCacheEntry(final Header[] headers, final byte[] bytes) {
278         final Date now = new Date();
279         return makeCacheEntry(now, now, headers, bytes);
280     }
281 
282     public static HttpCacheEntry makeCacheEntry(final byte[] bytes) {
283         return makeCacheEntry(getStockHeaders(new Date()), bytes);
284     }
285 
286     public static HttpCacheEntry makeCacheEntry(final Header[] headers) {
287         return makeCacheEntry(headers, getRandomBytes(128));
288     }
289 
290     public static HttpCacheEntry makeCacheEntry() {
291         final Date now = new Date();
292         return makeCacheEntry(now, now);
293     }
294 
295     public static HttpCacheEntry makeCacheEntryWithNoRequestMethodOrEntity(final Header[] headers) {
296         final Date now = new Date();
297         return new HttpCacheEntry(now, now, HttpStatus.SC_OK, headers, null, null);
298     }
299 
300     public static HttpCacheEntry makeCacheEntryWithNoRequestMethod(final Header[] headers) {
301         final Date now = new Date();
302         return new HttpCacheEntry(now, now, HttpStatus.SC_OK, headers, new HeapResource(getRandomBytes(128)), null);
303     }
304 
305     public static HttpCacheEntry make204CacheEntryWithNoRequestMethod(final Header[] headers) {
306         final Date now = new Date();
307         return new HttpCacheEntry(now, now, HttpStatus.SC_NO_CONTENT, headers, null, null);
308     }
309 
310     public static HttpCacheEntry makeHeadCacheEntry(final Header[] headers) {
311         final Date now = new Date();
312         return new HttpCacheEntry(now, now, HttpStatus.SC_OK, headers, null, null);
313     }
314 
315     public static HttpCacheEntry makeHeadCacheEntryWithNoRequestMethod(final Header[] headers) {
316         final Date now = new Date();
317         return new HttpCacheEntry(now, now, HttpStatus.SC_OK, headers, null, null);
318     }
319 
320     public static ClassicHttpResponse make200Response() {
321         final ClassicHttpResponse out = new BasicClassicHttpResponse(HttpStatus.SC_OK, "OK");
322         out.setHeader("Date", DateUtils.formatDate(new Date()));
323         out.setHeader("Server", "MockOrigin/1.0");
324         out.setHeader("Content-Length", "128");
325         out.setEntity(makeBody(128));
326         return out;
327     }
328 
329     public static final ClassicHttpResponse make200Response(final Date date, final String cacheControl) {
330         final ClassicHttpResponse response = HttpTestUtils.make200Response();
331         response.setHeader("Date", DateUtils.formatDate(date));
332         response.setHeader("Cache-Control",cacheControl);
333         response.setHeader("Etag","\"etag\"");
334         return response;
335     }
336 
337     public static ClassicHttpResponse make304Response() {
338         return new BasicClassicHttpResponse(HttpStatus.SC_NOT_MODIFIED, "Not modified");
339     }
340 
341     public static final void assert110WarningFound(final HttpResponse response) {
342         boolean found110Warning = false;
343         final Iterator<HeaderElement> it = MessageSupport.iterate(response, HttpHeaders.WARNING);
344         while (it.hasNext()) {
345             final HeaderElement elt = it.next();
346             final String[] parts = elt.getName().split("\\s");
347             if ("110".equals(parts[0])) {
348                 found110Warning = true;
349                 break;
350             }
351         }
352         Assert.assertTrue(found110Warning);
353     }
354 
355     public static ClassicHttpRequest makeDefaultRequest() {
356         return new BasicClassicHttpRequest("GET", "/");
357     }
358 
359     public static ClassicHttpRequest makeDefaultHEADRequest() {
360         return new BasicClassicHttpRequest("HEAD", "/");
361     }
362 
363     public static ClassicHttpResponse make500Response() {
364         return new BasicClassicHttpResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, "Internal Server Error");
365     }
366 
367     public static Map<String, String> makeDefaultVariantMap(final String key, final String value) {
368         final Map<String, String> variants = new HashMap<>();
369         variants.put(key, value);
370 
371         return variants;
372     }
373 }